"""Builder cho payload persistence phụ trợ."""

from __future__ import annotations

from typing import Any

from app.models.schemas import WorkflowReviewStartRequest
from app.modules.core.application.workflow_persistence.helpers import merge_string_lists


def build_employee_log_session_payload(
    *,
    request: WorkflowReviewStartRequest,
    employee_code: str,
    review_id: str,
    review_code: str,
    shift_date: str,
    actions: list[dict[str, Any]],
    persona: dict[str, Any] | None,
    normalize_work_log_status: Any,
) -> dict[str, Any]:
    """Gộp action thành session log."""
    latest_action = actions[-1]
    findings = merge_string_lists(*(item.get("findings") or [] for item in actions))
    missing_items = merge_string_lists(
        *(item.get("missing_items") or [] for item in actions)
    )
    notes = merge_string_lists(*(item.get("notes") or [] for item in actions))
    ai_results = merge_string_lists(*(item.get("ai_result") or [] for item in actions))
    progress_percent = max(int(item.get("progress_percent") or 0) for item in actions)
    completed_count = sum(int(item.get("completed_count") or 0) for item in actions)
    missing_count = max(
        [int(item.get("missing_count") or 0) for item in actions] + [len(missing_items)]
    )

    return {
        "employee_code": employee_code,
        "project_code": request.project_code,
        "shift_date": shift_date,
        "shift_code": "day",
        "role_title": latest_action.get("role_title")
        or (persona["role_title"] if persona else None),
        "agent_role": latest_action.get("agent_role")
        or latest_action.get("department_code")
        or request.lead_agent_code,
        "status": normalize_work_log_status(latest_action.get("status")),
        "summary": latest_action.get("summary")
        or f"Tham gia workflow rà soát hồ sơ {review_code}.",
        "priority": latest_action.get("priority") or "Trung bình",
        "role_group": latest_action.get("role_group")
        or latest_action.get("department_code"),
        "next_priority": latest_action.get("next_priority")
        or "Tiếp tục xử lý các đầu mục hồ sơ còn thiếu.",
        "progress_percent": progress_percent,
        "completed_count": completed_count,
        "missing_count": missing_count,
        "findings": findings,
        "missing_items": missing_items,
        "notes": notes + ai_results,
        "metadata": {
            "review_id": review_id,
            "review_code": review_code,
            "lead_agent_code": request.lead_agent_code,
            "workflow_type": "proactive_dossier_review",
        },
    }
