"""Candidate Performance scoring policy (0–100).

UI contract (Figma Candidate Matching):
- Overall Performance: weighted blend of mock interviews, recruiter interviews,
  and assessments (missing sources excluded; weights renormalized).
- AI Performance: overall + Technical / Confidence / Communication / Culture Fit.
- Assessment: percent score + status (In-Progress / Passed / Failed / …).

Retakes: same ``assessment_id`` increments ``attempt_number``; rollups use the
**latest** attempt per assessment_id (by recorded_at). Overall AI uses the
**latest** evaluation per source_type (mock vs recruiter).

GET endpoints never call LLMs — they only read persisted rows.
"""

from __future__ import annotations

from math import isfinite
from typing import Any, Iterable

# Weight policy for Overall Performance (renormalized when a source is missing).
OVERALL_WEIGHTS: dict[str, float] = {
    "mock_interview": 0.35,
    "recruiter_interview": 0.40,
    "assessment": 0.25,
}

RECOMMENDATION_DISPLAY: dict[str, str] = {
    "strong_hire": "Strong Hire",
    "hire": "Hire",
    "maybe": "Maybe",
    "no_hire": "No Hire",
    "strong_yes": "Strong Hire",
    "yes": "Hire",
    "no": "No Hire",
}


def clamp_score_100(value: object, default: float | None = None) -> float | None:
    """Coerce a value to 0–100. Accepts 0–1 fractions and 0–100 absolute scores."""
    if value is None or isinstance(value, bool):
        return default
    try:
        number = float(value)
    except (TypeError, ValueError, OverflowError):
        return default
    if not isfinite(number):
        return default
    if 0.0 <= number <= 1.0:
        number *= 100.0
    return round(max(0.0, min(100.0, number)), 1)


def ratio_to_score_100(total: object, maximum: object) -> float | None:
    """Convert total/max grading into a 0–100 score."""
    try:
        t = float(total)
        m = float(maximum)
    except (TypeError, ValueError, OverflowError):
        return None
    if not isfinite(t) or not isfinite(m) or m <= 0:
        return None
    return clamp_score_100((t / m) * 100.0)


def map_hiring_label(label: object) -> tuple[str | None, str | None]:
    """Normalize hiring-fit labels to UI recommendation keys + display."""
    if not isinstance(label, str) or not label.strip():
        return None, None
    key = label.strip().lower().replace("-", "_").replace(" ", "_")
    aliases = {
        "strong_yes": "strong_hire",
        "strong_hire": "strong_hire",
        "yes": "hire",
        "hire": "hire",
        "maybe": "maybe",
        "no": "no_hire",
        "no_hire": "no_hire",
        "reject": "no_hire",
    }
    normalized = aliases.get(key)
    if not normalized:
        return None, None
    return normalized, RECOMMENDATION_DISPLAY.get(normalized, normalized.replace("_", " ").title())


def mean_scores(values: Iterable[float | None]) -> float | None:
    nums = [v for v in values if v is not None and isfinite(float(v))]
    if not nums:
        return None
    return round(sum(float(v) for v in nums) / len(nums), 1)


def map_interview_dimensions(
    *,
    overall_01: float | None = None,
    category_scores: list[dict[str, Any]] | None = None,
    confidence_01: float | None = None,
    communication_01: float | None = None,
    culture_fit_01: float | None = None,
) -> dict[str, float | None]:
    """Map interview rubric categories → UI AI Performance bars (0–100).

    Defaults when only an overall interview score is available:
    Technical / Communication / Culture Fit inherit overall; Confidence uses
    dedicated confidence when present else overall.
    """
    by_key: dict[str, float] = {}
    for item in category_scores or []:
        if not isinstance(item, dict):
            continue
        key = str(item.get("key") or "").strip().lower()
        score = clamp_score_100(item.get("score"))
        if key and score is not None:
            by_key[key] = score

    overall = clamp_score_100(overall_01)

    technical = mean_scores(
        [
            by_key.get("correctness"),
            by_key.get("depth"),
            by_key.get("problem_solving"),
            by_key.get("technical"),
            by_key.get("technical_depth"),
        ]
    )
    communication = mean_scores(
        [
            by_key.get("relevance"),
            by_key.get("completeness"),
            by_key.get("communication"),
            clamp_score_100(communication_01),
        ]
    )
    culture = mean_scores(
        [
            by_key.get("culture_fit"),
            by_key.get("culture"),
            by_key.get("behavioral"),
            clamp_score_100(culture_fit_01),
        ]
    )
    confidence = clamp_score_100(confidence_01)
    if confidence is None:
        confidence = by_key.get("confidence")

    if technical is None:
        technical = overall
    if communication is None:
        communication = overall
    if culture is None:
        culture = overall
    if confidence is None:
        confidence = overall

    # Prefer explicit overall; else mean of available dimensions.
    if overall is None:
        overall = mean_scores([technical, confidence, communication, culture])

    return {
        "overall_score": overall,
        "technical_score": technical,
        "confidence_score": confidence,
        "communication_score": communication,
        "culture_fit_score": culture,
    }


def assessment_status(*, passed: bool | None, score_100: float | None, explicit: str | None = None) -> str:
    """Normalize assessment status for list cards."""
    if explicit:
        value = explicit.strip().lower().replace(" ", "_").replace("-", "_")
        allowed = {
            "not_started",
            "in_progress",
            "passed",
            "failed",
            "expired",
        }
        if value in allowed:
            return value
        if value in {"pass", "completed_pass"}:
            return "passed"
        if value in {"fail", "completed_fail"}:
            return "failed"
    if passed is True:
        return "passed"
    if passed is False:
        return "failed"
    if score_100 is None:
        return "not_started"
    return "in_progress"


def compute_overall_performance(
    *,
    mock_score: float | None,
    recruiter_score: float | None,
    assessment_score: float | None,
) -> tuple[float | None, dict[str, Any]]:
    """Weighted Overall Performance; renormalize when sources are missing."""
    parts: dict[str, float | None] = {
        "mock_interview": clamp_score_100(mock_score),
        "recruiter_interview": clamp_score_100(recruiter_score),
        "assessment": clamp_score_100(assessment_score),
    }
    active = {k: v for k, v in parts.items() if v is not None}
    if not active:
        return None, {
            "weights_used": {},
            "sources": parts,
            "policy": "missing_sources_excluded_weights_renormalized",
        }

    weight_sum = sum(OVERALL_WEIGHTS[k] for k in active)
    overall = round(
        sum(active[k] * (OVERALL_WEIGHTS[k] / weight_sum) for k in active),
        1,
    )
    return overall, {
        "weights_used": {k: round(OVERALL_WEIGHTS[k] / weight_sum, 4) for k in active},
        "sources": parts,
        "policy": "missing_sources_excluded_weights_renormalized",
    }
