"""Resume vs JD screening match — LLM scoring with deterministic local fallback."""

from __future__ import annotations

import re
from typing import Any

from app.errors import GatewayError
from app.schemas.common import JobStatus
from app.schemas.resume_match import ResumeMatchRequest, ResumeMatchResponse
from app.services.shared.ai_generate import generate_json
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

_TECH = [
    "python",
    "java",
    "javascript",
    "typescript",
    "react",
    "node.js",
    "nodejs",
    "fastapi",
    "django",
    "flask",
    "sql",
    "postgresql",
    "postgres",
    "mysql",
    "mongodb",
    "aws",
    "gcp",
    "azure",
    "docker",
    "kubernetes",
    "k8s",
    "redis",
    "graphql",
    "rest",
    "go",
    "golang",
    "rust",
    "c++",
    "kotlin",
    "swift",
    "ci/cd",
    "terraform",
    "kafka",
]

_SCREEN_PASS_THRESHOLD = 0.6


def _resume_blob(payload: ResumeMatchRequest) -> str:
    parts: list[str] = []
    if payload.resume_text:
        parts.append(payload.resume_text)
    if payload.resume_structured:
        parts.append(str(payload.resume_structured))
    return "\n".join(parts).strip()


def _normalize_skill(skill: str) -> str:
    s = skill.strip().lower()
    aliases = {
        "postgres": "postgresql",
        "nodejs": "node.js",
        "k8s": "kubernetes",
        "golang": "go",
        "js": "javascript",
        "ts": "typescript",
    }
    return aliases.get(s, s)


def _extract_skills_from_text(text: str) -> list[str]:
    low = text.lower()
    found = [t for t in _TECH if t in low]
    # Also pull short tokens from comma lists after "skills"
    m = re.search(
        r"(?:skills?|tech(?:nical)?\s*skills?)\s*[:\-]?\s*(.+?)(?:\n\n|\Z)",
        text,
        flags=re.I | re.S,
    )
    extra: list[str] = []
    if m:
        for part in re.split(r"[,|/•;]+", m.group(1)):
            token = part.strip(" -\t\n")
            if 1 < len(token) <= 40:
                extra.append(token)
    # preserve display casing from required/extra where possible
    out: list[str] = []
    seen: set[str] = set()
    for s in found + extra:
        key = _normalize_skill(s)
        if key in seen:
            continue
        seen.add(key)
        out.append(s)
    return out


def _skills_from_structured(structured: dict[str, Any]) -> list[str]:
    skills = structured.get("skills") or []
    if isinstance(skills, list):
        return [str(s) for s in skills if str(s).strip()]
    return []


def _clamp01(value: Any, default: float = 0.0) -> float:
    try:
        return max(0.0, min(1.0, float(value)))
    except (TypeError, ValueError):
        return max(0.0, min(1.0, default))


def _normalize_skill_list(value: Any) -> list[str]:
    if not isinstance(value, (list, tuple)):
        return []
    out: list[str] = []
    seen: set[str] = set()
    for item in value:
        if item is None:
            continue
        text = str(item).strip()
        if not text:
            continue
        key = _normalize_skill(text)
        if key in seen:
            continue
        seen.add(key)
        out.append(text)
    return out


def _local_score(
    payload: ResumeMatchRequest,
    *,
    resume_text: str,
    resume_struct: dict[str, Any],
) -> dict[str, Any]:
    if not resume_text and not resume_struct:
        raise GatewayError(
            "Provide resume_text or resume_structured",
            code="invalid_resume_match",
            status_code=400,
        )

    jd_struct = structure_job_description(payload.job_description)

    required = list(payload.required_skills or [])
    if not required:
        required = _skills_from_structured(jd_struct) or _extract_skills_from_text(
            payload.job_description
        )
    if not required:
        required = ["communication"]

    resume_skills = {
        _normalize_skill(s)
        for s in (
            _skills_from_structured(resume_struct)
            + _extract_skills_from_text(resume_text)
        )
    }
    resume_low = resume_text.lower()

    matched: list[str] = []
    missing: list[str] = []
    for skill in required:
        key = _normalize_skill(skill)
        if key in resume_skills or key in resume_low or skill.lower() in resume_low:
            matched.append(skill)
        else:
            missing.append(skill)

    score = (len(matched) / len(required)) if required else 0.0
    # Slight boost when structured resume skills overlap JD skills beyond required list
    jd_skills = {_normalize_skill(s) for s in _skills_from_structured(jd_struct)}
    if jd_skills:
        overlap = len(resume_skills & jd_skills) / max(len(jd_skills), 1)
        score = min(1.0, round(0.7 * score + 0.3 * overlap, 2))
    else:
        score = round(score, 2)

    return {
        "match_score": score,
        "matched_skills": matched,
        "missing_skills": missing,
        "summary": (
            f"Resume match {round(score * 100)}% for {payload.role_title}: "
            f"{len(matched)}/{len(required)} required skills matched."
        ),
    }


def _normalize_match_result(
    data: dict[str, Any],
    *,
    fallback: dict[str, Any],
) -> dict[str, Any]:
    """Clamp / coerce LLM JSON; fill gaps from deterministic local score."""
    score_raw = data.get("match_score", data.get("score"))
    if score_raw is None:
        score = _clamp01(fallback.get("match_score"), 0.0)
    else:
        score = _clamp01(score_raw, _clamp01(fallback.get("match_score"), 0.0))

    matched = _normalize_skill_list(data.get("matched_skills"))
    missing = _normalize_skill_list(data.get("missing_skills"))
    if not matched and not missing:
        matched = list(fallback.get("matched_skills") or [])
        missing = list(fallback.get("missing_skills") or [])

    summary = data.get("summary")
    if not isinstance(summary, str) or not summary.strip():
        summary = fallback.get("summary")
    else:
        summary = summary.strip()

    return {
        "match_score": round(score, 4),
        "matched_skills": matched,
        "missing_skills": missing,
        "summary": summary,
    }


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

    async def score(self, payload: ResumeMatchRequest) -> ResumeMatchResponse:
        profile = await self._resume_input.process(
            candidate_id=payload.candidate_id,
            company_id=payload.company_id,
            content_base64=payload.content_base64,
            source_url=payload.source_url,
            resume_text=payload.resume_text,
            resume_structured=payload.resume_structured,
            document_type=payload.document_type,
            filename=payload.filename,
            language=payload.language,
            force_reparse=bool((payload.options or {}).get("force_reparse")),
            persist=bool(payload.candidate_id),
            require_resume=True,
        )
        resume_text = profile.raw_text or _resume_blob(payload)
        resume_struct = dict(profile.structured or payload.resume_structured or {})

        def local() -> dict[str, Any]:
            return _local_score(
                payload, resume_text=resume_text, resume_struct=resume_struct
            )

        system = (
            "You are a resume screening engine for recruitment.\n"
            "Compare the candidate resume against the job description and required skills.\n"
            "Return only valid JSON with this structure:\n"
            '{"match_score": 0.0, "matched_skills": [], "missing_skills": [], "summary": ""}\n'
            "Rules:\n"
            "- match_score must be a number between 0 and 1 (overall fit).\n"
            "- matched_skills: skills from required_skills (or critical JD skills) "
            "with clear evidence in the resume.\n"
            "- missing_skills: required or critical JD skills without clear evidence.\n"
            "- Prefer the provided required_skills list when present; "
            "otherwise infer skills from the job description.\n"
            "- Do not invent experience, titles, or skills absent from the resume.\n"
            "- Keep summary concise (1-3 sentences) for recruiters.\n"
        )
        user = (
            f"Role: {payload.role_title}\n"
            f"Job description:\n{payload.job_description}\n"
            f"Required skills: {payload.required_skills}\n"
            f"Resume text:\n{resume_text}\n"
            f"Structured resume: {resume_struct}\n"
            f"Language: {payload.language}"
        )

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        fallback = local() if not stub else data
        if not isinstance(data, dict):
            data = fallback
        result = _normalize_match_result(data, fallback=fallback)

        score = float(result["match_score"])
        msg = f"Resume match via {provider}"
        if profile.reused:
            msg += f" (resume profile v{profile.resume_version} reused)"
        return ResumeMatchResponse(
            correlation_id=payload.correlation_id,
            candidate_id=payload.candidate_id or profile.candidate_id,
            role_title=payload.role_title,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=msg,
            match_score=score,
            screen_passed=score >= _SCREEN_PASS_THRESHOLD,
            matched_skills=list(result["matched_skills"]),
            missing_skills=list(result["missing_skills"]),
            summary=result.get("summary"),
        )
