"""AI-assisted reference checks — questionnaire, responses, consolidated report."""

from __future__ import annotations

from copy import deepcopy
from typing import Any
from uuid import uuid4

from fastapi import HTTPException, status

from app.schemas.common import JobStatus
from app.schemas.reference_checks import (
    ReferenceCheckAction,
    ReferenceCheckRequest,
    ReferenceCheckResponse,
    ReferenceCheckStatus,
    ReferenceQuestion,
    ReferenceQuestionnaireRequest,
    ReferenceQuestionnaireResponse,
    ReferenceReportRequest,
    ReferenceReportResponse,
    RefereeInfo,
    RefereeResponseIn,
)
from app.services.reports.reference_check_store import (
    ReferenceCheckRecord,
    get_reference_check_store,
)
from app.services.shared.ai_generate import generate_json


def _parse_questions(raw: Any) -> list[ReferenceQuestion]:
    out: list[ReferenceQuestion] = []
    for i, q in enumerate(raw or []):
        if not isinstance(q, dict) or not q.get("text"):
            continue
        out.append(
            ReferenceQuestion(
                id=str(q.get("id") or f"rq-{i + 1}"),
                text=str(q.get("text")),
                category=q.get("category"),
            )
        )
    return out


def _question_ids(questions: list[dict[str, Any]] | list[ReferenceQuestion]) -> list[str]:
    ids: list[str] = []
    for q in questions:
        if isinstance(q, ReferenceQuestion):
            ids.append(q.id)
        elif isinstance(q, dict) and q.get("id"):
            ids.append(str(q["id"]))
    return ids


def _incomplete_ids(
    question_ids: list[str], answers: dict[str, Any]
) -> list[str]:
    missing: list[str] = []
    for qid in question_ids:
        val = answers.get(qid)
        if val is None:
            missing.append(qid)
            continue
        if isinstance(val, str) and not val.strip():
            missing.append(qid)
    return missing


def _normalize_referee_row(
    *,
    referee: RefereeInfo | None,
    response: RefereeResponseIn | None,
    fallback: dict[str, Any] | None = None,
) -> dict[str, Any]:
    fb = fallback or {}
    name = (
        (referee.name if referee else None)
        or (response.referee_name if response else None)
        or fb.get("referee_name")
        or fb.get("name")
        or "Referee"
    )
    rid = (
        (referee.referee_id if referee else None)
        or (response.referee_id if response else None)
        or fb.get("referee_id")
        or str(uuid4())
    )
    return {
        "referee_id": str(rid).strip(),
        "name": str(name).strip(),
        "email": (referee.email if referee else None)
        or (response.email if response else None)
        or fb.get("email"),
        "relationship": (referee.relationship if referee else None)
        or (response.relationship if response else None)
        or fb.get("relationship"),
    }


def _recompute_status(rec: ReferenceCheckRecord) -> str:
    expected = len(rec.referees) if rec.referees else None
    received = len(rec.responses)
    complete_n = sum(1 for r in rec.responses if r.get("complete"))
    if rec.report:
        return ReferenceCheckStatus.REPORT_READY.value
    if expected and complete_n >= expected:
        return ReferenceCheckStatus.COMPLETED.value
    if received > 0:
        if expected and complete_n < expected:
            return ReferenceCheckStatus.PARTIAL.value
        if any(not r.get("complete") for r in rec.responses):
            return ReferenceCheckStatus.PARTIAL.value
        return ReferenceCheckStatus.COMPLETED.value
    if rec.referees:
        return ReferenceCheckStatus.AWAITING_RESPONSES.value
    return ReferenceCheckStatus.QUESTIONNAIRE_READY.value


class ReferenceChecksService:
    """Internal questionnaire + report services with unified dispatch."""

    def __init__(self) -> None:
        self._store = get_reference_check_store()

    async def dispatch(self, payload: ReferenceCheckRequest) -> ReferenceCheckResponse:
        action = payload.action
        if action is None:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="action is required (query ?action= or body.action)",
            )
        if action == ReferenceCheckAction.GENERATE_QUESTIONNAIRE:
            return await self.generate_questionnaire(payload)
        if action == ReferenceCheckAction.SUBMIT_RESPONSE:
            return await self.submit_response(payload)
        if action == ReferenceCheckAction.GENERATE_REPORT:
            return await self.generate_report(payload)
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"Unsupported action: {action}",
        )

    # --- Internal: questionnaire generation ---

    async def questionnaire(
        self, payload: ReferenceQuestionnaireRequest
    ) -> ReferenceQuestionnaireResponse:
        unified = await self.generate_questionnaire(
            ReferenceCheckRequest(
                action=ReferenceCheckAction.GENERATE_QUESTIONNAIRE,
                correlation_id=payload.correlation_id,
                candidate_id=payload.candidate_id,
                candidate_name=payload.candidate_name,
                role_title=payload.role_title,
                job_description=payload.job_description,
                referee_relationship=payload.referee_relationship,
                referees=list(payload.referees or []),
                count=payload.count,
                language=payload.language,
                options=dict(payload.options or {}),
            )
        )
        return ReferenceQuestionnaireResponse(
            correlation_id=unified.correlation_id,
            candidate_id=unified.candidate_id,
            questionnaire_id=unified.questionnaire_id,
            status=unified.status,
            stub=unified.stub,
            message=unified.message,
            questions=unified.questions,
        )

    async def generate_questionnaire(
        self, payload: ReferenceCheckRequest
    ) -> ReferenceCheckResponse:
        errors: list[str] = []
        if not (payload.candidate_id or "").strip():
            errors.append("candidate_id is required")
        if not (payload.role_title or "").strip():
            errors.append("role_title is required for generate_questionnaire")
        if errors:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail={"errors": errors},
            )

        system = (
            "Create a referee questionnaire for a shortlisted candidate. "
            "Return JSON only: {\"questions\":[{\"id\",\"text\",\"category\"}]}. "
            "Questions must be role-relevant, concise, and suitable for a professional referee."
        )
        user = (
            f"Candidate: {payload.candidate_id} ({payload.candidate_name or 'n/a'})\n"
            f"Role: {payload.role_title}\nJD: {payload.job_description or 'n/a'}\n"
            f"Relationship hint: {payload.referee_relationship or 'n/a'}\n"
            f"Count: {payload.count}\nLanguage: {payload.language}"
        )

        def local() -> dict:
            label = payload.candidate_name or payload.candidate_id
            base = [
                ("performance", f"How would you rate {label}'s performance in their role?"),
                ("strengths", "What are this person's greatest professional strengths?"),
                ("growth", "Where should they focus for growth?"),
                ("collaboration", "How effectively do they collaborate with others?"),
                ("reliability", "Can you describe their reliability under deadlines?"),
                ("leadership", "Have they demonstrated ownership or leadership?"),
                ("rehire", "Would you rehire or work with them again? Why?"),
                ("role_fit", f"How well would they fit a {payload.role_title} role?"),
            ]
            return {
                "questions": [
                    {"id": f"rq-{i + 1}", "text": text, "category": cat}
                    for i, (cat, text) in enumerate(base[: payload.count])
                ]
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        if not isinstance(data, dict):
            data = local()
            stub = True
        questions = _parse_questions(data.get("questions"))
        if not questions:
            questions = _parse_questions(local()["questions"])
            stub = True

        referees_out: list[dict[str, Any]] = []
        for ref in payload.referees or []:
            rid = (ref.referee_id or str(uuid4())).strip()
            if not (ref.name or "").strip():
                errors.append("Each referee must include a non-empty name")
                continue
            referees_out.append(
                {
                    "referee_id": rid,
                    "name": ref.name.strip(),
                    "email": ref.email,
                    "relationship": ref.relationship or payload.referee_relationship,
                    "status": "invited",
                }
            )
        if errors:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail={"errors": errors},
            )

        status_val = (
            ReferenceCheckStatus.AWAITING_RESPONSES.value
            if referees_out
            else ReferenceCheckStatus.QUESTIONNAIRE_READY.value
        )
        rec = self._store.create(
            candidate_id=payload.candidate_id.strip(),
            candidate_name=payload.candidate_name,
            role_title=payload.role_title.strip(),
            job_description=payload.job_description,
            language=payload.language,
            questions=[q.model_dump() for q in questions],
            referees=referees_out,
            status=status_val,
        )

        return ReferenceCheckResponse(
            correlation_id=payload.correlation_id,
            action=ReferenceCheckAction.GENERATE_QUESTIONNAIRE,
            candidate_id=rec.candidate_id,
            candidate_name=rec.candidate_name,
            role_title=rec.role_title,
            reference_check_id=rec.reference_check_id,
            questionnaire_id=rec.reference_check_id,
            check_status=ReferenceCheckStatus(rec.status),
            questions=questions,
            referees=referees_out,
            responses_received=0,
            responses_expected=len(referees_out) or None,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Reference questionnaire via {provider}",
        )

    # --- Collect referee responses ---

    async def submit_response(
        self, payload: ReferenceCheckRequest
    ) -> ReferenceCheckResponse:
        errors: list[str] = []
        check_id = payload.resolved_check_id()
        if not check_id:
            errors.append("reference_check_id (or questionnaire_id) is required")
        if payload.referee is None and payload.response is None:
            errors.append("referee and/or response is required")
        if errors:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail={"errors": errors},
            )

        rec = self._store.get(check_id)  # type: ignore[arg-type]
        if rec is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail={
                    "errors": [
                        f"reference_check_id not found: {check_id}"
                    ]
                },
            )
        if rec.candidate_id != payload.candidate_id.strip():
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail={
                    "errors": [
                        "candidate_id does not match this reference_check_id"
                    ]
                },
            )

        response = payload.response or RefereeResponseIn()
        ref_row = _normalize_referee_row(
            referee=payload.referee,
            response=response,
        )
        if not ref_row["name"] or ref_row["name"] == "Referee":
            # Prefer named referee from tracked list
            if payload.referee and not (payload.referee.name or "").strip():
                raise HTTPException(
                    status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                    detail={"errors": ["referee.name is required"]},
                )

        qids = _question_ids(rec.questions)
        answers = dict(response.answers or {})
        incomplete = _incomplete_ids(qids, answers)
        is_complete = (
            bool(response.complete)
            if response.complete is not None
            else (len(incomplete) == 0 and bool(answers))
        )
        if not answers:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail={
                    "errors": ["response.answers must include at least one answer"]
                },
            )

        response_id = str(uuid4())
        entry = {
            "response_id": response_id,
            "referee_id": ref_row["referee_id"],
            "referee_name": ref_row["name"],
            "email": ref_row["email"],
            "relationship": ref_row["relationship"],
            "answers": answers,
            "complete": is_complete,
            "incomplete_question_ids": incomplete,
        }

        # Upsert by referee_id — avoid duplicate processing
        replaced = False
        new_responses: list[dict[str, Any]] = []
        for existing in rec.responses:
            if existing.get("referee_id") == ref_row["referee_id"]:
                new_responses.append(entry)
                replaced = True
            else:
                new_responses.append(existing)
        if not replaced:
            new_responses.append(entry)
        rec.responses = new_responses

        # Track referee on the check
        ref_ids = {r.get("referee_id") for r in rec.referees}
        if ref_row["referee_id"] not in ref_ids:
            rec.referees.append(
                {
                    **ref_row,
                    "status": "responded" if is_complete else "partial",
                }
            )
        else:
            for r in rec.referees:
                if r.get("referee_id") == ref_row["referee_id"]:
                    r["status"] = "responded" if is_complete else "partial"
                    r["name"] = ref_row["name"]
                    if ref_row["email"]:
                        r["email"] = ref_row["email"]
                    if ref_row["relationship"]:
                        r["relationship"] = ref_row["relationship"]

        # New response invalidates prior report (reuse fresh data on next generate)
        if rec.report is not None:
            rec.report = None

        rec.status = _recompute_status(rec)
        rec = self._store.update(rec)

        return ReferenceCheckResponse(
            correlation_id=payload.correlation_id,
            action=ReferenceCheckAction.SUBMIT_RESPONSE,
            candidate_id=rec.candidate_id,
            candidate_name=rec.candidate_name,
            role_title=rec.role_title,
            reference_check_id=rec.reference_check_id,
            questionnaire_id=rec.reference_check_id,
            check_status=ReferenceCheckStatus(rec.status),
            questions=_parse_questions(rec.questions),
            referees=list(rec.referees),
            response_id=response_id,
            incomplete_question_ids=incomplete,
            responses_received=len(rec.responses),
            responses_expected=len(rec.referees) or None,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message=(
                "Referee response recorded"
                + (" (incomplete)" if incomplete else "")
                + (" — replaced prior response for referee" if replaced else "")
            ),
            errors=(
                [f"Incomplete answers for: {', '.join(incomplete)}"]
                if incomplete
                else []
            ),
        )

    # --- Internal: report generation ---

    async def report(self, payload: ReferenceReportRequest) -> ReferenceReportResponse:
        unified = await self.generate_report(
            ReferenceCheckRequest(
                action=ReferenceCheckAction.GENERATE_REPORT,
                correlation_id=payload.correlation_id,
                candidate_id=payload.candidate_id,
                role_title=payload.role_title or "Role",
                reference_check_id=payload.reference_check_id,
                referee_responses=list(payload.referee_responses or []),
                language=payload.language,
                options=dict(payload.options or {}),
            )
        )
        return ReferenceReportResponse(
            correlation_id=unified.correlation_id,
            candidate_id=unified.candidate_id,
            report_id=unified.report_id,
            status=unified.status,
            stub=unified.stub,
            message=unified.message,
            sentiment_summary=unified.sentiment_summary,
            strengths=unified.strengths,
            concerns=unified.concerns,
            recommendation=unified.recommendation,
            report_markdown=unified.report_markdown,
        )

    async def generate_report(
        self, payload: ReferenceCheckRequest
    ) -> ReferenceCheckResponse:
        errors: list[str] = []
        if not (payload.candidate_id or "").strip():
            errors.append("candidate_id is required")

        rec: ReferenceCheckRecord | None = None
        check_id = payload.resolved_check_id()
        if check_id:
            rec = self._store.get(check_id)
            if rec is None:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail={"errors": [f"reference_check_id not found: {check_id}"]},
                )
            if rec.candidate_id != payload.candidate_id.strip():
                errors.append("candidate_id does not match this reference_check_id")
        elif not payload.referee_responses:
            # Reuse latest stored check for candidate when possible
            rec = self._store.find_latest_for_candidate(payload.candidate_id)

        # Prefer stored responses; fall back to inline (BC)
        responses: list[dict[str, Any]] = []
        if rec and rec.responses:
            responses = deepcopy(rec.responses)
        if payload.referee_responses:
            # Merge inline without duplicating same referee_id/name
            existing_keys = {
                (
                    str(r.get("referee_id") or ""),
                    str(r.get("referee_name") or r.get("name") or ""),
                )
                for r in responses
            }
            for row in payload.referee_responses:
                if not isinstance(row, dict):
                    continue
                key = (
                    str(row.get("referee_id") or ""),
                    str(row.get("referee_name") or row.get("name") or ""),
                )
                if key in existing_keys and key != ("", ""):
                    continue
                responses.append(row)
                existing_keys.add(key)

        if not responses:
            errors.append(
                "No referee responses available — submit_response first or "
                "provide referee_responses"
            )
        role_title = (
            (payload.role_title or "").strip()
            or (rec.role_title if rec else "")
            or "Role"
        )
        if errors:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail={"errors": errors},
            )

        # Reuse cached report when responses unchanged
        if rec and rec.report and rec.report.get("response_fingerprint") == _fingerprint(
            responses
        ):
            cached = rec.report
            return ReferenceCheckResponse(
                correlation_id=payload.correlation_id,
                action=ReferenceCheckAction.GENERATE_REPORT,
                candidate_id=payload.candidate_id,
                candidate_name=rec.candidate_name,
                role_title=role_title,
                reference_check_id=rec.reference_check_id,
                questionnaire_id=rec.reference_check_id,
                check_status=ReferenceCheckStatus.REPORT_READY,
                questions=_parse_questions(rec.questions),
                referees=list(rec.referees),
                responses_received=len(rec.responses),
                responses_expected=len(rec.referees) or None,
                report_id=cached.get("report_id"),
                sentiment_summary=cached.get("sentiment_summary"),
                strengths=list(cached.get("strengths") or []),
                concerns=list(cached.get("concerns") or []),
                recommendation=cached.get("recommendation"),
                report_markdown=cached.get("report_markdown"),
                status=JobStatus.SUCCEEDED,
                stub=bool(cached.get("stub")),
                message="Reference report reused (unchanged responses)",
            )

        incomplete_notes = []
        for r in responses:
            if isinstance(r, dict) and r.get("incomplete_question_ids"):
                incomplete_notes.append(
                    f"{r.get('referee_name') or r.get('name')}: "
                    f"incomplete {r.get('incomplete_question_ids')}"
                )

        system = (
            "Consolidate referee responses into a hiring reference report. "
            "Return JSON only: {\"sentiment_summary\",\"strengths\":[],\"concerns\":[],"
            "\"recommendation\",\"report_markdown\"}. "
            "Note incomplete responses as limitations; do not invent referee quotes."
        )
        user = (
            f"Candidate: {payload.candidate_id} "
            f"({(rec.candidate_name if rec else payload.candidate_name) or 'n/a'})\n"
            f"Role: {role_title}\n"
            f"Responses: {responses}\n"
            f"Incomplete notes: {incomplete_notes or 'none'}"
        )

        def local() -> dict:
            n = len(responses)
            return {
                "sentiment_summary": (
                    f"Overall constructive feedback from {n} referee response(s), "
                    "with normal growth areas noted."
                    + (
                        f" Incomplete: {'; '.join(incomplete_notes)}."
                        if incomplete_notes
                        else ""
                    )
                ),
                "strengths": ["Reliability", "Collaboration"],
                "concerns": (
                    ["Some referee responses were incomplete"]
                    if incomplete_notes
                    else ["Limited examples of senior-scope ownership"]
                ),
                "recommendation": "proceed_with_interview",
                "report_markdown": (
                    f"# Reference report — {payload.candidate_id}\n\n"
                    f"Role context: {role_title}\n\n"
                    f"Summary: {n} referee response(s) reviewed. "
                    "Solid performance signals with room to grow on ownership."
                ),
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        if not isinstance(data, dict):
            data = local()
            stub = True

        report_id = str(uuid4())
        strengths = [str(s) for s in (data.get("strengths") or [])][:8]
        concerns = [str(c) for c in (data.get("concerns") or [])][:8]
        report_blob = {
            "report_id": report_id,
            "sentiment_summary": data.get("sentiment_summary"),
            "strengths": strengths,
            "concerns": concerns,
            "recommendation": data.get("recommendation"),
            "report_markdown": data.get("report_markdown"),
            "response_fingerprint": _fingerprint(responses),
            "stub": stub,
        }

        if rec is not None:
            # Persist inline responses onto the check when provided
            if payload.referee_responses and not rec.responses:
                rec.responses = [
                    r for r in payload.referee_responses if isinstance(r, dict)
                ]
            rec.report = report_blob
            rec.status = ReferenceCheckStatus.REPORT_READY.value
            rec = self._store.update(rec)

        return ReferenceCheckResponse(
            correlation_id=payload.correlation_id,
            action=ReferenceCheckAction.GENERATE_REPORT,
            candidate_id=payload.candidate_id,
            candidate_name=(rec.candidate_name if rec else payload.candidate_name),
            role_title=role_title,
            reference_check_id=(rec.reference_check_id if rec else check_id),
            questionnaire_id=(rec.reference_check_id if rec else check_id),
            check_status=(
                ReferenceCheckStatus.REPORT_READY
                if rec
                else None
            ),
            questions=_parse_questions(rec.questions) if rec else [],
            referees=list(rec.referees) if rec else [],
            responses_received=len(responses),
            responses_expected=(len(rec.referees) if rec and rec.referees else None),
            report_id=report_id,
            sentiment_summary=report_blob["sentiment_summary"],
            strengths=strengths,
            concerns=concerns,
            recommendation=report_blob["recommendation"],
            report_markdown=report_blob["report_markdown"],
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Reference report via {provider}",
            errors=incomplete_notes,
        )


def _fingerprint(responses: list[dict[str, Any]]) -> str:
    import json

    try:
        return json.dumps(responses, sort_keys=True, default=str)
    except TypeError:
        return str(len(responses))
