
"""Skill-gap analysis service."""

from typing import Any

from app.schemas.common import JobStatus
from app.schemas.skill_gap import (
    SkillGapAnalyzeRequest,
    SkillGapAnalyzeResponse,
    SkillGapItem,
)
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
from app.services.shared.ai_generate import generate_json


# Normalize common proficiency labels to a 0–1 scale.
_PROFICIENCY_LEVELS = {
    "none": 0.0,
    "no experience": 0.0,
    "not demonstrated": 0.0,
    "beginner": 0.2,
    "basic": 0.4,
    "foundation": 0.4,
    "foundational": 0.4,
    "novice": 0.2,
    "working proficiency": 0.8,
    "working knowledge": 0.6,
    "intermediate": 0.6,
    "proficient": 0.8,
    "advanced": 0.9,
    "expert": 1.0,
}


def _normalize_level(value: Any, default: float = 0.0) -> float:
    """Convert numeric levels or proficiency labels to a 0–1 score."""
    if isinstance(value, bool):
        return float(value)

    if isinstance(value, (int, float)):
        return max(0.0, min(1.0, float(value)))

    if isinstance(value, str):
        normalized = value.strip().lower()

        if normalized in _PROFICIENCY_LEVELS:
            return _PROFICIENCY_LEVELS[normalized]

        try:
            return max(0.0, min(1.0, float(normalized)))
        except ValueError:
            pass

    return max(0.0, min(1.0, default))


def _normalize_text_list(value: Any) -> list[str]:
    """Return a clean list of non-empty strings."""
    if not isinstance(value, (list, tuple)):
        return []

    return [
        item.strip()
        for item in value
        if isinstance(item, str) and item.strip()
    ]


def _normalize_gap(gap_data: dict[str, Any]) -> dict[str, Any]:
    """Normalize one AI-generated skill-gap entry."""
    required_level = _normalize_level(
        gap_data.get("required_level"),
        default=0.8,
    )
    demonstrated_level = _normalize_level(
        gap_data.get("demonstrated_level"),
        default=0.0,
    )

    # Always calculate the numeric gap from the normalized levels.
    numeric_gap = round(
        max(0.0, required_level - demonstrated_level),
        4,
    )

    evidence = gap_data.get("evidence")
    if evidence is not None and not isinstance(evidence, str):
        evidence = str(evidence)

    return {
        "skill": str(gap_data.get("skill") or "Unspecified skill"),
        "required_level": required_level,
        "demonstrated_level": demonstrated_level,
        "gap": numeric_gap,
        "priority": str(gap_data.get("priority") or "medium").lower(),
        "learning_suggestions": _normalize_text_list(
            gap_data.get("learning_suggestions")
        ),
        "evidence": evidence,
    }


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

    async def analyze(
        self,
        payload: SkillGapAnalyzeRequest,
    ) -> SkillGapAnalyzeResponse:
        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,
                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,
                }
            )
        system = """
You are a skill-gap analysis engine for recruitment.

Compare a candidate's demonstrated skills with the requirements of
the target role. Consider the job description, required skills, resume,
structured resume data, and interview answers.

Return only valid JSON with this structure:
{
  "overall_readiness": 0.0,
  "strengths": [],
  "recommended_prep_focus": [],
  "gaps": [
    {
      "skill": "Python",
      "required_level": 0.8,
      "demonstrated_level": 0.4,
      "gap": 0.4,
      "priority": "high",
      "learning_suggestions": ["Practice role-based Python exercises"],
      "evidence": "Evidence found in the candidate's materials"
    }
  ]
}

Rules:
- overall_readiness must be a number between 0 and 1.
- required_level, demonstrated_level, and gap must be numbers between 0 and 1.
- Calculate gap as max(0, required_level - demonstrated_level).
- Use 0 for no demonstrated proficiency, 0.2 for beginner,
  0.4 for basic, 0.6 for intermediate, 0.8 for proficient,
  and 1.0 for expert-level proficiency.
- Include only evidence supported by the supplied materials.
- A skill missing from the demonstrated_skills list is not automatically
  absent if the resume or interview answers provide relevant evidence.
- Do not invent experience, certifications, or achievements.
- Keep evidence concise and recommendations actionable.
- Prioritize gaps according to their importance to the role.
"""

        user = (
            f"Role: {payload.role_title}\n"
            f"Job description:\n{payload.job_description}\n"
            f"Required skills: {payload.required_skills}\n"
            f"Demonstrated skills: {payload.demonstrated_skills}\n"
            f"Resume text: {payload.resume_text or ''}\n"
            f"Structured resume: {payload.resume_structured or {}}\n"
            f"Interview answers: {payload.interview_answers}\n"
            f"Language: {payload.language}"
        )

        def local() -> dict[str, Any]:
            """Deterministic fallback if AI generation is unavailable."""
            required_skills = payload.required_skills or [
                "role fundamentals",
                "communication",
            ]

            demonstrated_names = {
                skill.strip().casefold()
                for skill in payload.demonstrated_skills
                if isinstance(skill, str) and skill.strip()
            }

            resume_text = (payload.resume_text or "").casefold()
            if payload.resume_structured:
                resume_text += " " + str(payload.resume_structured).casefold()

            answers_text = str(payload.interview_answers).casefold()
            available_evidence = f"{resume_text} {answers_text}"

            gaps: list[dict[str, Any]] = []
            strengths: list[str] = []

            for skill in required_skills:
                skill_name = str(skill).strip()
                if not skill_name:
                    continue

                normalized_skill = skill_name.casefold()

                if normalized_skill in demonstrated_names:
                    strengths.append(skill_name)
                    continue

                # Fallback evidence check: do not treat a skill as absent
                # if its name appears in the resume or interview material.
                if normalized_skill in available_evidence:
                    gaps.append(
                        {
                            "skill": skill_name,
                            "required_level": 0.8,
                            "demonstrated_level": 0.4,
                            "gap": 0.4,
                            "priority": "medium",
                            "learning_suggestions": [
                                f"Practice {skill_name} with role-based exercises"
                            ],
                            "evidence": (
                                "Skill is mentioned in the supplied materials, "
                                "but proficiency has not been verified."
                            ),
                        }
                    )
                else:
                    gaps.append(
                        {
                            "skill": skill_name,
                            "required_level": 0.8,
                            "demonstrated_level": 0.0,
                            "gap": 0.8,
                            "priority": "high",
                            "learning_suggestions": [
                                f"Learn {skill_name} fundamentals",
                                f"Build a practical project using {skill_name}",
                            ],
                            "evidence": (
                                "No clear evidence was found in the supplied "
                                "materials; this does not prove the candidate "
                                "lacks the skill."
                            ),
                        }
                    )

            readiness = (
                sum(
                    item["demonstrated_level"]
                    for item in gaps
                )
                / (len(gaps) * 0.8)
                if gaps
                else 0.8
            )

            return {
                "overall_readiness": max(0.0, min(1.0, readiness)),
                "strengths": strengths,
                "recommended_prep_focus": [
                    item["skill"] for item in gaps[:3]
                ],
                "gaps": gaps,
            }

        data, stub, provider = await generate_json(
            system=system,
            user=user,
            local_factory=local,
        )

        if not isinstance(data, dict):
            data = local()
            stub = True
            provider = "local-fallback"

        normalized_gaps = [
            _normalize_gap(item)
            for item in (data.get("gaps") or [])
            if isinstance(item, dict)
        ]

        overall_readiness = _normalize_level(
            data.get("overall_readiness"),
            default=0.0,
        )

        strengths = _normalize_text_list(data.get("strengths"))
        recommended_prep_focus = _normalize_text_list(
            data.get("recommended_prep_focus")
        )

        gaps = [
            SkillGapItem(**item)
            for item in normalized_gaps
        ]

        return SkillGapAnalyzeResponse(
            correlation_id=payload.correlation_id,
            candidate_id=payload.candidate_id,
            role_title=payload.role_title,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Skill-gap analysis via {provider}",
            overall_readiness=overall_readiness,
            gaps=gaps,
            strengths=strengths,
            recommended_prep_focus=recommended_prep_focus,
        )
