from __future__ import annotations

from typing import Any

from app.models.schemas import (
    CompanyOperationalProjectState,
    CompanyOperationalRiskItem,
    CompanyOperationalStateResponse,
    CompanyOperationalWorkforceStatus,
)

from .helpers import (
    extract_string_list,
    is_high_severity,
    is_open_status,
)


def build_project_state(item: Any) -> CompanyOperationalProjectState:
    """Map project state."""
    return CompanyOperationalProjectState(
        project_code=item.project_code,
        project_name=item.project_name,
        client_name=item.client_name,
        location=item.location,
        project_manager=item.project_manager,
        status=item.status,
        current_phase=item.current_phase,
        overall_progress_percent=item.overall_progress_percent,
        budget_status=item.budget_status,
        open_risks_count=sum(1 for risk in item.risks if is_open_status(risk.status)),
        blocked_items_count=sum(
            1
            for risk in item.risks
            if is_high_severity(risk.severity) and is_open_status(risk.status)
        ),
        upcoming_tasks_count=len(item.upcoming_tasks),
        milestone_count=len(item.milestones),
        summary=item.status,
        source="project_management",
        metadata={
            "phase_progress_count": len(item.phase_progress),
            "timeline_event_count": len(item.timeline),
            "summary_card_count": len(item.summary_cards),
        },
    )


def build_risks(
    projects: list[Any], dossier_reviews: list[dict[str, Any]]
) -> list[CompanyOperationalRiskItem]:
    """Tạo danh sách risk."""
    items: list[CompanyOperationalRiskItem] = []
    for project in projects:
        for risk in project.risks:
            items.append(
                CompanyOperationalRiskItem(
                    project_code=project.project_code,
                    project_name=project.project_name,
                    title=risk.title,
                    severity=risk.severity,
                    status=risk.status,
                    owner=risk.owner,
                    source_type="project_management",
                    reference_id=None,
                    mitigation=risk.mitigation,
                    metadata={
                        "current_phase": project.current_phase,
                        "budget_status": project.budget_status,
                    },
                )
            )
    for review in dossier_reviews:
        for finding in review.get("findings", []):
            items.append(
                CompanyOperationalRiskItem(
                    project_code=str(review.get("project_code") or ""),
                    project_name=str(review.get("project_name") or ""),
                    title=str(finding.get("title") or ""),
                    severity=str(finding.get("severity") or ""),
                    status=str(finding.get("status") or ""),
                    owner=str(finding.get("responsible_department_code") or ""),
                    source_type="dossier_review",
                    reference_id=str(finding.get("finding_id") or ""),
                    mitigation=finding.get("resolution_note"),
                    metadata={
                        "dossier_stage": finding.get("dossier_stage"),
                        "finding_type": finding.get("finding_type"),
                        "is_blocking": bool(finding.get("is_blocking")),
                    },
                )
            )
    return items


def build_workforce(items: list[Any]) -> CompanyOperationalWorkforceStatus:
    """Tổng hợp workforce."""
    blocked_statuses = {"blocked", "bị chặn", "vướng", "overdue"}
    in_progress_statuses = {
        "đang xử lý",
        "in_progress",
        "in progress",
        "assigned",
        "pending_verification",
    }
    completed_statuses = {"hoàn thành", "completed", "done", "verified", "resolved"}
    employees_blocked = 0
    employees_in_progress = 0
    employees_completed = 0
    for item in items:
        normalized_status = str(item.status or "").strip().lower()
        if normalized_status in blocked_statuses:
            employees_blocked += 1
        elif normalized_status in completed_statuses:
            employees_completed += 1
        elif normalized_status in in_progress_statuses or normalized_status:
            employees_in_progress += 1
    notes: list[str] = []
    if not items:
        notes.append(
            "Chưa có employee work logs khả dụng để tổng hợp trạng thái workforce."
        )
    return CompanyOperationalWorkforceStatus(
        total_employees_active=len(items),
        employees_blocked=employees_blocked,
        employees_in_progress=employees_in_progress,
        employees_completed=employees_completed,
        notes=notes,
    )


def build_policy_overview(*, dossier_reviews: list[dict[str, Any]]) -> dict[str, Any]:
    """Tạo thống kê policy đơn giản."""
    policy_action_count = 0
    risk_flag_count = 0
    escalation_count = 0
    warnings: list[str] = []
    for review in dossier_reviews:
        for action in review.get("actions", []):
            action_type = str(action.get("action_type") or "").strip().lower()
            if action_type == "policy_checked":
                policy_action_count += 1
            elif action_type == "risk_flagged":
                risk_flag_count += 1
            elif action_type == "escalation_triggered":
                escalation_count += 1
            warnings.extend(
                extract_string_list(
                    (action.get("action_payload") or {}).get("warnings")
                )
            )
    return {
        "policy_checks_count": policy_action_count,
        "risk_flagged_count": risk_flag_count,
        "escalation_triggered_count": escalation_count,
        "warnings": warnings,
    }


def build_remediation_plan_summary(item: Any) -> dict[str, Any]:
    """Tóm tắt remediation plan."""
    readiness_summary = getattr(item, "readiness_summary", None)
    return {
        "project_code": getattr(item, "project_code", ""),
        "review_session_id": getattr(item, "review_session_id", ""),
        "finding_id": getattr(item, "finding_id", ""),
        "finding_code": getattr(item, "finding_code", None),
        "document_type": getattr(item, "document_type", ""),
        "dossier_stage": getattr(item, "dossier_stage", None),
        "priority": getattr(item, "priority", "medium"),
        "owner_department_code": getattr(item, "owner_department_code", None),
        "owner_employee_code": getattr(item, "owner_employee_code", None),
        "readiness_status": getattr(readiness_summary, "status", "blocked"),
        "blocking_reasons": list(
            getattr(readiness_summary, "blocking_reasons", []) or []
        ),
        "destination_folder": getattr(item, "destination_folder", None),
        "output_filename": getattr(item, "output_filename", None),
        "source": getattr(item, "source", "derived"),
        "used_fallback": getattr(item, "used_fallback", False),
        "message": getattr(item, "message", None),
    }


def attach_supported_optional_fields(
    response_payload: dict[str, Any], optional_payload: dict[str, Any]
) -> None:
    """Chỉ gắn field model hỗ trợ."""
    model_fields = getattr(CompanyOperationalStateResponse, "model_fields", {})
    for field_name, value in optional_payload.items():
        if field_name in model_fields:
            response_payload[field_name] = value
