"""AI question generation — live LLM or local generator."""

from __future__ import annotations

from typing import Any
import json
import re
from app.prompts import render_role_question_prompts
from app.schemas.common import JobStatus
from app.schemas.questions import (
    Difficulty,
    GeneratedOption,
    GeneratedQuestion,
    QuestionGenRequest,
    QuestionGenResponse,
    QuestionType,
    RoleQuestionGenRequest,
    RoleQuestionGenResponse,
)
from app.services.shared.ai_generate import generate_json
from app.schemas.resume_input import has_resume_signal
from app.services.screening.resume_input import ResumeInputProcessor
from app.services.screening.resume_service import ResumeService


def _resume_provided(payload: RoleQuestionGenRequest) -> bool:
    text = (payload.resume_text or "").strip()
    return bool(text) or bool(payload.resume_structured) or bool(payload.candidate_id)


def _format_resume_context(payload: RoleQuestionGenRequest) -> str:
    """Build a prompt-safe resume block; never invents candidate facts."""
    if not _resume_provided(payload):
        return "none"

    parts: list[str] = []
    structured = dict(payload.resume_structured or {})
    text = (payload.resume_text or "").strip()

    # Prefer structured already resolved by ResumeService in generate_from_role.

    skills = structured.get("skills") or []
    if isinstance(skills, list) and skills:
        parts.append("Skills: " + ", ".join(str(s) for s in skills[:30]))

    experience = structured.get("experience") or []
    if isinstance(experience, list) and experience:
        bullets = []
        for item in experience[:8]:
            if isinstance(item, dict):
                bullets.append(str(item.get("raw") or item.get("title") or item))
            else:
                bullets.append(str(item))
        parts.append("Experience:\n- " + "\n- ".join(b.strip() for b in bullets if b.strip()))

    projects = structured.get("projects") or []
    if not projects and isinstance(structured.get("sections"), dict):
        proj_text = structured["sections"].get("projects") or ""
        if proj_text:
            projects = [{"raw": p.strip()} for p in proj_text.split("\n\n") if p.strip()]
    if isinstance(projects, list) and projects:
        bullets = []
        for item in projects[:6]:
            if isinstance(item, dict):
                bullets.append(str(item.get("raw") or item.get("name") or item))
            else:
                bullets.append(str(item))
        parts.append("Projects:\n- " + "\n- ".join(b.strip() for b in bullets if b.strip()))

    summary = structured.get("summary")
    if summary:
        parts.append(f"Summary: {str(summary)[:800]}")

    if text:
        parts.append("Resume text (excerpt):\n" + text[:6000])

    if not parts and structured:
        parts.append(str(structured)[:4000])

    return "\n\n".join(parts) if parts else "none"


def _resume_anchors(payload: RoleQuestionGenRequest) -> list[str]:
    """Extract concrete resume phrases for local claim-verification stems."""
    anchors: list[str] = []
    structured: dict[str, Any] = dict(payload.resume_structured or {})
    text = (payload.resume_text or "").strip()
    # Structured should already be normalized by ResumeService when available.

    for skill in structured.get("skills") or []:
        s = str(skill).strip()
        if s:
            anchors.append(s)

    for item in structured.get("experience") or []:
        if isinstance(item, dict):
            raw = str(item.get("raw") or item.get("title") or "").strip()
        else:
            raw = str(item).strip()
        if raw:
            anchors.append(raw[:160])

    projects = structured.get("projects") or []
    if not projects and isinstance(structured.get("sections"), dict):
        proj = structured["sections"].get("projects") or ""
        projects = [{"raw": p} for p in proj.split("\n\n") if p.strip()]
    for item in projects:
        if isinstance(item, dict):
            raw = str(item.get("raw") or item.get("name") or "").strip()
        else:
            raw = str(item).strip()
        if raw:
            anchors.append(raw[:160])

    # Dedupe preserving order
    seen: set[str] = set()
    out: list[str] = []
    for a in anchors:
        key = a.lower()
        if key in seen:
            continue
        seen.add(key)
        out.append(a)
    return out[:12]


def _local_resume_questions(
    *,
    count: int,
    qtype: QuestionType,
    difficulty: Difficulty,
    role_title: str,
    anchors: list[str],
    jd_skills: list[str],
) -> list[dict]:
    """Local fallback: JD-focused stems that probe only provided resume claims."""
    items: list[dict] = []
    for i in range(count):
        anchor = anchors[i % len(anchors)] if anchors else None
        focus = jd_skills[i % len(jd_skills)] if jd_skills else role_title
        if anchor:
            stem = (
                f"[{difficulty.value}] For the {role_title} role, your resume mentions "
                f"\"{anchor}\". How did that work map to {focus}, and what trade-offs "
                f"did you own? (Q{i + 1})"
            )
            explanation = "Local resume-grounded probe; claim taken only from provided resume."
            metadata = {"resume_anchor": anchor, "jd_focus": focus}
        else:
            stem = (
                f"[{difficulty.value}] What experience qualifies you for {focus} "
                f"in a {role_title} role? (Q{i + 1})"
            )
            explanation = f"Generated locally for {role_title}."
            metadata = {}

        options: list[dict] = []
        answer = f"Evidence-based answer tied to {focus}."
        if qtype == QuestionType.MCQ:
            options = [
                {"key": "A", "text": f"Direct ownership of {focus}", "is_correct": True},
                {"key": "B", "text": "Peripheral exposure only", "is_correct": False},
                {"key": "C", "text": "Unrelated experience", "is_correct": False},
                {"key": "D", "text": "No supporting evidence", "is_correct": False},
            ]
            answer = "A"
            stem = (
                f"Which best matches how \"{anchor}\" supports {focus} for {role_title}? "
                f"(Q{i + 1})"
                if anchor
                else f"Which best describes your readiness for {focus}? (Q{i + 1})"
            )
        elif qtype == QuestionType.TRUE_FALSE:
            options = [
                {"key": "T", "text": "True", "is_correct": True},
                {"key": "F", "text": "False", "is_correct": False},
            ]
            answer = "T"
            stem = (
                f"Your resume claim about \"{anchor}\" is relevant to {focus} for "
                f"{role_title}. True or False? (Q{i + 1})"
                if anchor
                else f"{focus} is critical for {role_title}. True or False? (Q{i + 1})"
            )
        elif qtype == QuestionType.CODING:
            stem = (
                f"Write a short solution reflecting the \"{anchor}\" work as it relates "
                f"to {focus} (Q{i + 1})."
                if anchor
                else f"Write a short solution related to {focus} (Q{i + 1})."
            )
            answer = "# sample solution\npass"

        items.append(
            {
                "id": f"q-{i + 1}",
                "question_type": qtype.value,
                "difficulty": difficulty.value,
                "stem": stem,
                "options": options,
                "answer": answer,
                "explanation": explanation,
                "metadata": metadata,
            }
        )
    return items


def _local_questions(
    *,
    count: int,
    qtype: QuestionType,
    difficulty: Difficulty,
    topic: str,
) -> list[dict]:
    items = []
    for i in range(count):
        stem = f"[{difficulty.value}] Explain a key concept about {topic} (Q{i + 1})."
        options: list[dict] = []
        answer = f"Sample answer covering {topic}."
        if qtype == QuestionType.MCQ:
            options = [
                {"key": "A", "text": f"Correct point about {topic}", "is_correct": True},
                {"key": "B", "text": "Plausible distractor", "is_correct": False},
                {"key": "C", "text": "Unrelated option", "is_correct": False},
                {"key": "D", "text": "Common misconception", "is_correct": False},
            ]
            answer = "A"
            stem = f"Which statement best describes {topic}? (Q{i + 1})"
        elif qtype == QuestionType.TRUE_FALSE:
            options = [
                {"key": "T", "text": "True", "is_correct": True},
                {"key": "F", "text": "False", "is_correct": False},
            ]
            answer = "T"
            stem = f"{topic} is an important topic for this role. True or False? (Q{i + 1})"
        elif qtype == QuestionType.CODING:
            stem = f"Write a short solution related to {topic} (Q{i + 1})."
            answer = "# sample solution\npass"
        items.append(
            {
                "id": f"q-{i + 1}",
                "question_type": qtype.value,
                "difficulty": difficulty.value,
                "stem": stem,
                "options": options,
                "answer": answer,
                "explanation": f"Generated locally for {topic}.",
                "metadata": {},
            }
        )
    return items


def _coerce_answer_text(raw: Any) -> str | None:
    """LLM sometimes returns answer as dict/list; schema expects a string."""
    if raw is None:
        return None
    if isinstance(raw, str):
        return raw
    if isinstance(raw, dict):
        for key in ("expected", "value", "text", "answer", "correct"):
            if key in raw and raw[key] is not None:
                val = raw[key]
                if isinstance(val, (dict, list)):
                    return json.dumps(val, ensure_ascii=False)
                return str(val)
        return json.dumps(raw, ensure_ascii=False)
    if isinstance(raw, (list, int, float, bool)):
        return json.dumps(raw, ensure_ascii=False) if isinstance(raw, list) else str(raw)
    return str(raw)


def _parse_questions(
    raw: list,
    fallback_type: QuestionType,
    fallback_diff: Difficulty,
) -> list[GeneratedQuestion]:
    out: list[GeneratedQuestion] = []

    for i, item in enumerate(raw or []):
        if not isinstance(item, dict):
            continue

        # Do not silently convert missing or placeholder stems
        # into apparently valid interview questions.
        stem = str(item.get("stem") or item.get("text") or "").strip()

        if not stem:
            continue

        if re.fullmatch(
            r"(?:question|q)\s*[-#:]?\s*\d+",
            stem,
            flags=re.IGNORECASE,
        ):
            continue

        try:
            qt = QuestionType(item.get("question_type", fallback_type.value))
        except (ValueError, TypeError):
            qt = fallback_type

        try:
            df = Difficulty(item.get("difficulty", fallback_diff.value))
        except (ValueError, TypeError):
            df = fallback_diff

        options = [
            GeneratedOption(
                key=str(o.get("key", chr(65 + j))),
                text=str(o.get("text", "")),
                is_correct=bool(o.get("is_correct", False)),
            )
            for j, o in enumerate(item.get("options") or [])
            if isinstance(o, dict)
        ]

        explanation = item.get("explanation")
        if explanation is not None and not isinstance(explanation, str):
            explanation = (
                json.dumps(explanation, ensure_ascii=False)
                if isinstance(explanation, (dict, list))
                else str(explanation)
            )

        out.append(
            GeneratedQuestion(
                id=str(item.get("id") or f"q-{len(out) + 1}"),
                question_type=qt,
                difficulty=df,
                stem=stem,
                options=options,
                answer=_coerce_answer_text(item.get("answer")),
                explanation=explanation,
                metadata=item.get("metadata") or {},
            )
        )

    return out


class QuestionsService:
    def __init__(
        self,
        *,
        resumes: ResumeService | None = None,
        resume_input: ResumeInputProcessor | None = None,
    ) -> None:
        self._resume_input = resume_input or ResumeInputProcessor(resumes=resumes)

    async def generate(self, payload: QuestionGenRequest) -> QuestionGenResponse:
        system = (
            "You are an assessment question generator. "
            "Return JSON: {\"questions\":[{\"id\",\"question_type\",\"difficulty\","
            "\"stem\",\"options\":[{\"key\",\"text\",\"is_correct\"}],\"answer\",\"explanation\"}]}"
        )
        user = (
            f"Subject: {payload.subject}\nTopic: {payload.topic}\n"
            f"Type: {payload.question_type.value}\nDifficulty: {payload.difficulty.value}\n"
            f"Count: {payload.count}\nLanguage: {payload.language}\n"
            f"Context: {payload.context or 'none'}\nConstraints: {payload.constraints}"
        )

        def local() -> dict:
            return {
                "questions": _local_questions(
                    count=payload.count,
                    qtype=payload.question_type,
                    difficulty=payload.difficulty,
                    topic=f"{payload.subject} / {payload.topic}",
                )
            }

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

        return QuestionGenResponse(
            correlation_id=payload.correlation_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Generated {len(questions)} question(s) via {provider}",
            questions=questions,
        )

    async def generate_from_role(
        self, payload: RoleQuestionGenRequest
    ) -> RoleQuestionGenResponse:
        if has_resume_signal(
            candidate_id=payload.candidate_id,
            resume_text=payload.resume_text,
            resume_structured=payload.resume_structured,
            content_base64=payload.content_base64,
            source_url=payload.source_url,
        ):
            profile = await self._resume_input.process(
                candidate_id=payload.candidate_id,
                company_id=payload.company_id,
                resume_text=payload.resume_text,
                resume_structured=payload.resume_structured,
                content_base64=payload.content_base64,
                source_url=payload.source_url,
                document_type=payload.document_type,
                filename=payload.filename,
                language=payload.language,
                persist=bool(payload.candidate_id),
                require_resume=True,
            )
            payload = payload.model_copy(
                update={
                    "resume_text": profile.raw_text or payload.resume_text,
                    "resume_structured": profile.structured
                    or payload.resume_structured,
                }
            )
        resume_grounded = _resume_provided(payload)
        resume_context = _format_resume_context(payload)

        system, user_prompt = render_role_question_prompts(
            persona=payload.persona,
            role_title=payload.role_title,
            seniority=payload.seniority or "",
            department=payload.department or "",
            job_description=payload.job_description,
            skills=payload.skills,
            question_types=[qt.value for qt in payload.question_types],
            difficulty=payload.difficulty.value,
            count=payload.count,
            language=payload.language,
            instructions=payload.instructions or "",
            resume_context=resume_context,
        )
        system = (
            system
            + "\nReturn JSON only: {\"questions\":[{\"id\",\"question_type\",\"difficulty\","
            "\"stem\",\"options\":[{\"key\",\"text\",\"is_correct\"}],\"answer\",\"explanation\","
            "\"metadata\":{}}]}"
        )
        primary_type = (
            payload.question_types[0]
            if payload.question_types
            else QuestionType.SHORT_ANSWER
        )

        def local() -> dict:
            if resume_grounded:
                return {
                    "questions": _local_resume_questions(
                        count=payload.count,
                        qtype=primary_type,
                        difficulty=payload.difficulty,
                        role_title=payload.role_title,
                        anchors=_resume_anchors(payload),
                        jd_skills=payload.skills,
                    )
                }
            topic = payload.role_title
            if payload.skills:
                topic = f"{payload.role_title} ({', '.join(payload.skills[:3])})"
            return {
                "questions": _local_questions(
                    count=payload.count,
                    qtype=primary_type,
                    difficulty=payload.difficulty,
                    topic=topic,
                )
            }

        try:
            data, stub, provider = await generate_json(
                system=system, user=user_prompt, local_factory=local
            )
        except Exception:  # noqa: BLE001 — never fail the endpoint hard
            data, stub, provider = local(), True, "local"

        questions = _parse_questions(
            data.get("questions", []), primary_type, payload.difficulty
        )
        if not questions:
            questions = _parse_questions(
                local()["questions"], primary_type, payload.difficulty
            )
            stub, provider = True, "local"

        grounded_msg = " (resume-grounded)" if resume_grounded else ""
        return RoleQuestionGenResponse(
            correlation_id=payload.correlation_id,
            role_title=payload.role_title,
            persona=payload.persona,
            resume_grounded=resume_grounded,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=(
                f"Generated {len(questions)} role question(s) via {provider}{grounded_msg}"
            ),
            prompt_preview={"system": system, "user": user_prompt},
            questions=questions,
        )
