"""Personalized interview prep plans with interview-focused learning modules."""

from __future__ import annotations

import re
from typing import Any
from uuid import uuid4

from app.schemas.common import JobStatus
from app.schemas.prep_plans import (
    PREP_TOPIC_CHAR_LIMIT,
    PREP_TOPIC_ENRICH_BELOW,
    PREP_TOPIC_QUESTION_COUNT,
    PREP_TOPIC_TARGET_MAX,
    PREP_TOPIC_TARGET_MIN,
    PrepPlanLearningModule,
    PrepPlanRequest,
    PrepPlanResponse,
    PrepPlanSection,
    PrepPlanTopic,
)
from app.services.screening.document_extract import structure_job_description
from app.services.screening.resume_input import ResumeInputProcessor
from app.services.screening.resume_service import ResumeService
from app.services.shared.ai_generate import generate_json
from app.schemas.resume_input import has_resume_signal

_SKILL_SPLIT = re.compile(r"[,;/|]+")
_FILLER_WORDS = re.compile(
    r"\b(really|very|basically|just|simply|actually|essentially|in order to|"
    r"kind of|sort of|quite|rather|literally|overall|generally speaking)\b",
    re.IGNORECASE,
)
_MULTI_SPACE = re.compile(r"\s{2,}")


def topic_content_char_count(
    topic: str,
    definition: str,
    real_world_example: str,
    questions: list[str],
) -> int:
    """Combined character count for the 500-limit rule (no separators added)."""
    return (
        len(topic)
        + len(definition)
        + len(real_world_example)
        + sum(len(q) for q in questions)
    )


def _refine_text(text: str) -> str:
    """Tighten wording without cutting mid-sentence fields; strip filler only."""
    cleaned = _FILLER_WORDS.sub("", text or "")
    cleaned = _MULTI_SPACE.sub(" ", cleaned).strip()
    cleaned = cleaned.replace(" ,", ",").replace(" .", ".")
    return cleaned


def _refine_fields(
    topic: str, definition: str, example: str, questions: list[str]
) -> tuple[str, str, str, list[str]]:
    return (
        _refine_text(topic),
        _refine_text(definition),
        _refine_text(example),
        [_refine_text(q) for q in questions],
    )


def _enrich_fields(
    topic: str, definition: str, example: str, questions: list[str]
) -> tuple[str, str, str, list[str]]:
    """Add concise technical detail when under the 450–490 target band."""
    count = topic_content_char_count(topic, definition, example, questions)
    if count >= PREP_TOPIC_TARGET_MIN:
        return topic, definition, example, questions

    skill = topic.strip() or "this skill"
    enrichments = [
        (
            "definition",
            f" Cover complexity, edge cases, and failure modes interviewers probe for {skill}.",
        ),
        (
            "example",
            f" Cite metrics (p95, error rate) and the rollback/monitoring choice you used for {skill}.",
        ),
        (
            "definition",
            f" Contrast common anti-patterns and when not to use {skill} in production.",
        ),
        (
            "example",
            f" Explain ownership: who reviewed the change and how you validated {skill} under load.",
        ),
    ]

    for target, extra in enrichments:
        count = topic_content_char_count(topic, definition, example, questions)
        if count >= PREP_TOPIC_TARGET_MIN:
            break
        room = PREP_TOPIC_TARGET_MAX - count
        if room <= 8:
            break
        piece = extra if len(extra) <= room else ""
        if not piece:
            # Prefer a shorter technical clause that still fits the target band.
            short = f" Note tradeoffs and SLOs for {skill}."
            if len(short) <= room:
                piece = short
            else:
                continue
        if target == "definition":
            candidate_def = definition + piece
            n = topic_content_char_count(topic, candidate_def, example, questions)
            if n <= PREP_TOPIC_CHAR_LIMIT:
                definition = candidate_def
        else:
            candidate_ex = example + piece
            n = topic_content_char_count(topic, definition, candidate_ex, questions)
            if n <= PREP_TOPIC_CHAR_LIMIT:
                example = candidate_ex

    return topic, definition, example, questions


def _default_answers(
    topic: str, definition: str, example: str, questions: list[str]
) -> list[str]:
    """Concise model answers when the model omits them (outside char budget)."""
    skill = topic.strip() or "this topic"
    base = [
        (
            f"Frame a concrete {skill} story: context, your decision, metrics, and "
            f"tradeoffs. Tie to: {definition[:120]}"
        ),
        (
            f"Explain failure modes and validation for {skill}, using a production "
            f"example like: {example[:120]}"
        ),
    ]
    out: list[str] = []
    for i, q in enumerate(questions[:PREP_TOPIC_QUESTION_COUNT]):
        ans = base[i] if i < len(base) else base[-1]
        # Lightly bind answer to the question wording for interview practice.
        out.append(_refine_text(f"For “{q}”: {ans}"))
    return out


def normalize_topic(raw: Any) -> PrepPlanTopic | None:
    """Validate 2 questions + 2 answers; target 450–490 chars, hard max 500.

    Char budget excludes answers. Flow: parse → refine if >500 → skip if still
    >500 → enrich if ~≤400/<450 → refine again if over 500 → skip if still over.
    Never truncates budgeted fields.
    """
    if not isinstance(raw, dict):
        return None
    topic = str(raw.get("topic") or "").strip()
    definition = str(raw.get("definition") or "").strip()
    example = str(
        raw.get("real_world_example")
        or raw.get("realWorldExample")
        or raw.get("example")
        or ""
    ).strip()
    questions_raw = raw.get("questions")
    if not isinstance(questions_raw, list):
        return None
    # Exactly two questions; if more were generated, keep the first two only.
    questions = [str(q).strip() for q in questions_raw if str(q).strip()]
    if len(questions) < PREP_TOPIC_QUESTION_COUNT:
        return None
    questions = questions[:PREP_TOPIC_QUESTION_COUNT]
    if not topic or not definition or not example:
        return None

    answers_raw = raw.get("answers")
    answers: list[str] = []
    if isinstance(answers_raw, list):
        answers = [str(a).strip() for a in answers_raw if str(a).strip()]
        answers = answers[:PREP_TOPIC_QUESTION_COUNT]
    if len(answers) < PREP_TOPIC_QUESTION_COUNT:
        answers = _default_answers(topic, definition, example, questions)
    else:
        answers = [_refine_text(a) for a in answers]

    count = topic_content_char_count(topic, definition, example, questions)
    if count > PREP_TOPIC_CHAR_LIMIT:
        topic, definition, example, questions = _refine_fields(
            topic, definition, example, questions
        )
        if not topic or not definition or not example or any(not q for q in questions):
            return None
        count = topic_content_char_count(topic, definition, example, questions)
        if count > PREP_TOPIC_CHAR_LIMIT:
            return None

    # Enrich thin topics (~400 or below target band) with useful technical detail.
    if count <= PREP_TOPIC_ENRICH_BELOW or count < PREP_TOPIC_TARGET_MIN:
        topic, definition, example, questions = _enrich_fields(
            topic, definition, example, questions
        )
        count = topic_content_char_count(topic, definition, example, questions)
        if count > PREP_TOPIC_CHAR_LIMIT:
            topic, definition, example, questions = _refine_fields(
                topic, definition, example, questions
            )
            count = topic_content_char_count(topic, definition, example, questions)
            if count > PREP_TOPIC_CHAR_LIMIT:
                return None

    # Re-bind default answers if definition/example changed via enrich/refine
    # and originals were synthesized.
    if not isinstance(answers_raw, list) or len(
        [str(a).strip() for a in (answers_raw or []) if str(a).strip()]
    ) < PREP_TOPIC_QUESTION_COUNT:
        answers = _default_answers(topic, definition, example, questions)

    if len(answers) != PREP_TOPIC_QUESTION_COUNT or any(not a for a in answers):
        return None

    try:
        return PrepPlanTopic(
            topic=topic,
            definition=definition,
            real_world_example=example,
            questions=questions,
            answers=answers,
        )
    except Exception:  # noqa: BLE001 — schema validation → skip topic
        return None


def normalize_learning_modules(raw_modules: Any) -> list[PrepPlanLearningModule]:
    """Parse AI/local modules; drop empty modules and invalid topics."""
    if not isinstance(raw_modules, list):
        return []
    out: list[PrepPlanLearningModule] = []
    seen_topics: set[str] = set()
    for mod in raw_modules:
        if not isinstance(mod, dict):
            continue
        title = str(mod.get("title") or "").strip()
        if not title:
            continue
        topics: list[PrepPlanTopic] = []
        for item in mod.get("topics") or []:
            normalized = normalize_topic(item)
            if normalized is None:
                continue
            key = normalized.topic.casefold()
            if key in seen_topics:
                continue
            seen_topics.add(key)
            topics.append(normalized)
        if topics:
            out.append(PrepPlanLearningModule(title=title, topics=topics))
    return out


def _skill_tokens(*blobs: str) -> list[str]:
    out: list[str] = []
    seen: set[str] = set()
    for blob in blobs:
        for part in _SKILL_SPLIT.split(blob or ""):
            text = part.strip()
            if len(text) < 2 or len(text) > 48:
                continue
            key = text.casefold()
            if key in seen:
                continue
            seen.add(key)
            out.append(text)
    return out


def _list_skills(value: Any) -> list[str]:
    if isinstance(value, list):
        return [str(s).strip() for s in value if str(s).strip()]
    if isinstance(value, str):
        return _skill_tokens(value)
    return []


def infer_skill_gaps(payload: PrepPlanRequest) -> list[str]:
    """Prioritize interview prep gaps from JD, resume, focus skills, and level.

    Expects resume_structured already normalized via ResumeService when available.
    """
    jd_struct = structure_job_description(payload.job_description)
    resume_struct = dict(payload.resume_structured or {})

    jd_skills = _list_skills(jd_struct.get("skills")) or _skill_tokens(
        payload.job_description
    )
    resume_skills = _list_skills(resume_struct.get("skills")) or _skill_tokens(
        payload.resume_text or ""
    )
    resume_keys = {s.casefold() for s in resume_skills}

    prioritized: list[str] = []
    seen: set[str] = set()

    def _add(skill: str) -> None:
        key = skill.casefold()
        if not key or key in seen:
            return
        seen.add(key)
        prioritized.append(skill)

    for skill in payload.focus_skills:
        _add(str(skill).strip())
    for skill in jd_skills:
        if skill.casefold() not in resume_keys:
            _add(skill)
    for skill in jd_skills:
        _add(skill)

    level = (payload.target_level or "intermediate").strip().lower()
    if level in {"beginner", "junior"}:
        _add("fundamentals")
        _add("communication")
    elif level in {"advanced", "senior", "staff"}:
        _add("system design")
        _add("ownership")
    else:
        _add("problem solving")

    return prioritized[:12] or ["role fundamentals", "communication", "problem solving"]


def _compact_topic(
    *,
    topic: str,
    definition: str,
    example: str,
    questions: list[str],
    answers: list[str] | None = None,
) -> PrepPlanTopic | None:
    """Build a topic through normalize (enrich/refine/skip)."""
    payload: dict[str, Any] = {
        "topic": topic,
        "definition": definition,
        "real_world_example": example,
        "questions": questions,
    }
    if answers is not None:
        payload["answers"] = answers
    return normalize_topic(payload)


def _local_learning_modules(
    payload: PrepPlanRequest, gaps: list[str]
) -> list[dict[str, Any]]:
    """Deterministic modules aimed at the 450–490 band (hard max 500)."""
    level = (payload.target_level or "intermediate").strip()
    role = payload.role_title.strip()
    seeds = gaps[:6] or ["core skills"]
    modules: list[dict[str, Any]] = []

    gap_topics: list[dict[str, Any]] = []
    for skill in seeds:
        label = skill[:40]
        topic = _compact_topic(
            topic=label,
            definition=(
                f"{label} for {level} {role} interviews: know core APIs, "
                f"complexity, and when {label} is the wrong tool."
            ),
            example=(
                f"Ship a {label} change with baseline metrics, review, canary, "
                f"and a clear rollback path; explain the tradeoff you accepted."
            ),
            questions=[
                f"How have you applied {label} in production, including metrics?",
                f"What {label} tradeoffs and failure modes do you watch for?",
            ],
            answers=[
                (
                    f"Describe a shipped {label} change: baseline metric, design choice, "
                    f"result (e.g. p95/error rate), and what you would improve next."
                ),
                (
                    f"Call out {label} costs (latency, consistency, ops), a failure you "
                    "saw or expect, and the alert/rollback that contains blast radius."
                ),
            ],
        )
        if topic is not None:
            gap_topics.append(topic.model_dump())
    if gap_topics:
        modules.append({"title": "Skill gap deep-dives", "topics": gap_topics})

    practice = _compact_topic(
        topic="Mock interview loops",
        definition=(
            f"Timed practice matching {level} {role} interviews: structure answers, "
            "clarify requirements, and narrate tradeoffs under time pressure."
        ),
        example=(
            "Run a 30-min mock, mark weak answers with evidence gaps, then retry "
            "the same prompt once with tighter STAR and metrics."
        ),
        questions=[
            "How do you structure a 2-minute intro with impact?",
            "What do you clarify before coding or designing?",
        ],
        answers=[
            (
                "Role → strongest domain → one quantified win → what you want in this "
                "role; keep under two minutes and invite a follow-up."
            ),
            (
                "Restate the goal, inputs/outputs, constraints (scale, latency, "
                "consistency), and success metrics before writing code or a diagram."
            ),
        ],
    )
    star = _compact_topic(
        topic="STAR evidence",
        definition=(
            "Turn project work into Situation-Task-Action-Result stories with "
            "ownership, constraints, and measurable outcomes interviewers expect."
        ),
        example=(
            "Latency incident: measured p95, chose Redis cache-aside, shipped with "
            "feature flag, cut p95 ~30%, monitored error budget for a week."
        ),
        questions=[
            "Tell me about a production incident you owned end-to-end.",
            "Describe a design choice you later changed and why.",
        ],
        answers=[
            (
                "Situation/impact → your task → actions (diagnosis, fix, comms) → "
                "result with metric and prevention follow-up you owned."
            ),
            (
                "State the first choice and constraint, what new evidence appeared, "
                "the change you made, and the measured improvement or lesson."
            ),
        ],
    )
    practice_topics = [t.model_dump() for t in (practice, star) if t is not None]
    if practice_topics:
        modules.append({"title": "Interview practice", "topics": practice_topics})

    return modules


def _modules_to_sections(
    modules: list[PrepPlanLearningModule],
) -> list[PrepPlanSection]:
    """Backward-compatible sections derived from learning modules."""
    sections: list[PrepPlanSection] = []
    for mod in modules:
        items: list[str] = []
        for topic in mod.topics:
            items.append(topic.topic)
            items.extend(topic.questions[:1])
        sections.append(
            PrepPlanSection(
                title=mod.title,
                items=items,
                estimated_hours=max(1.0, round(len(mod.topics) * 1.5, 1)),
            )
        )
    return sections


class PrepPlansService:
    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: PrepPlanRequest) -> PrepPlanResponse:
        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,
                }
            )
        inferred_gaps = infer_skill_gaps(payload)
        system = (
            "You create interview-focused learning modules for candidates. "
            "Analyze the JD and resume for skill gaps. Prioritize high-value "
            "interview topics for the role, target level, and focus skills. "
            "Avoid filler, generic, duplicate, or irrelevant topics. "
            "Return ONLY valid JSON with keys: "
            "summary (string), skill_gaps (string[]), suggested_tracks (string[]), "
            "sections ([{title, items[], estimated_hours}]), "
            "learning_modules ([{title, topics:[{topic, definition, "
            f"real_world_example, questions:[exactly {PREP_TOPIC_QUESTION_COUNT} strings], "
            f"answers:[exactly {PREP_TOPIC_QUESTION_COUNT} model answers paired 1:1]"
            "}]}]). "
            "Each answer must be a strong interview-style response (STAR/metrics/"
            "tradeoffs) for the matching question; answers are NOT in the char budget. "
            "CRITICAL content rules per topic: "
            f"combined length of topic + definition + real_world_example + "
            f"{PREP_TOPIC_QUESTION_COUNT} questions should be {PREP_TOPIC_TARGET_MIN}-"
            f"{PREP_TOPIC_TARGET_MAX} characters (hard max {PREP_TOPIC_CHAR_LIMIT}). "
            "If around 400 characters, enrich definition or real_world_example with "
            "useful technical detail (tradeoffs, metrics, failure modes)—no filler. "
            f"If over {PREP_TOPIC_CHAR_LIMIT}, refine wording; if still over, omit the "
            "entire topic (never truncate fields)."
        )
        user = (
            f"Role: {payload.role_title}\nLevel: {payload.target_level}\n"
            f"JD:\n{payload.job_description}\n"
            f"Resume:\n{payload.resume_text or payload.resume_structured}\n"
            f"Focus skills: {payload.focus_skills}\n"
            f"Inferred gaps (hint): {inferred_gaps}\n"
            f"Language: {payload.language}"
        )

        def local() -> dict:
            modules = _local_learning_modules(payload, inferred_gaps)
            return {
                "summary": (
                    f"A {payload.target_level} interview prep plan for "
                    f"{payload.role_title} focused on skill gaps and practice."
                ),
                "skill_gaps": inferred_gaps,
                "learning_modules": modules,
                "sections": [
                    {
                        "title": m["title"],
                        "items": [t["topic"] for t in m["topics"]],
                        "estimated_hours": max(1.0, len(m["topics"]) * 1.5),
                    }
                    for m in modules
                ],
                "suggested_tracks": [
                    f"{payload.target_level}-{payload.role_title.lower().replace(' ', '-')}"
                ],
            }

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

        modules = normalize_learning_modules(data.get("learning_modules"))
        if not modules:
            modules = normalize_learning_modules(
                _local_learning_modules(payload, inferred_gaps)
            )

        skill_gaps = [
            str(g).strip()
            for g in (data.get("skill_gaps") or inferred_gaps)
            if str(g).strip()
        ] or inferred_gaps

        sections = [
            PrepPlanSection(
                title=str(s.get("title", "Section")),
                items=[str(i) for i in (s.get("items") or []) if str(i).strip()],
                estimated_hours=s.get("estimated_hours"),
            )
            for s in (data.get("sections") or [])
            if isinstance(s, dict) and str(s.get("title") or "").strip()
        ]
        if not sections and modules:
            sections = _modules_to_sections(modules)

        return PrepPlanResponse(
            correlation_id=payload.correlation_id,
            candidate_id=payload.candidate_id,
            role_title=payload.role_title,
            plan_id=str(uuid4()),
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Generated prep plan via {provider}",
            summary=str(data.get("summary") or "").strip() or None,
            skill_gaps=skill_gaps,
            sections=sections,
            suggested_tracks=[
                str(t).strip()
                for t in (data.get("suggested_tracks") or [])
                if str(t).strip()
            ],
            learning_modules=modules,
        )
