"""Progress / improvement analytics — deterministic from stored performance."""

from __future__ import annotations

from typing import Any

from app.schemas.common import JobStatus
from app.schemas.progress_analytics import (
    AssessmentTypeScores,
    MockInterviewScores,
    ProgressAnalyticsRequest,
    ProgressAnalyticsResponse,
    ScorePoint,
    SkillGapSummary,
)
from app.services.talent import performance_store as store


def _avg(values: list[float]) -> float | None:
    if not values:
        return None
    return round(sum(values) / len(values), 2)


def _trend(scores: list[float]) -> tuple[str | None, str | None]:
    if len(scores) < 2:
        return ("flat", "flat") if scores else (None, None)
    # Compare early vs late half for steadiness
    mid = max(1, len(scores) // 2)
    early = _avg(scores[:mid]) or 0.0
    late = _avg(scores[mid:]) or 0.0
    delta = late - early
    if delta >= 3:
        return "improving", "improving steadily"
    if delta <= -3:
        return "declining", "declining"
    return "flat", "flat"


def _role_match(stored: str | None, job_title: str | None) -> bool:
    if not job_title or not str(job_title).strip():
        return True
    needle = str(job_title).strip().lower()
    hay = (stored or "").strip().lower()
    if not hay:
        return True  # keep rows with no role rather than dropping all history
    return needle in hay or hay in needle


def _normalize_assessment_type(kind: str | None, meta: dict[str, Any] | None) -> str | None:
    meta = meta or {}
    raw = meta.get("assessment_type") or kind or ""
    key = str(raw).strip().lower().replace("-", "_").replace(" ", "_")
    mapping = {
        "coding_challenge": "coding_challenge",
        "coding": "coding_challenge",
        "aptitude_and_reasoning": "aptitude_and_reasoning",
        "aptitude": "aptitude_and_reasoning",
        "personality_eval": "personality_eval",
        "personality": "personality_eval",
        "custom": "personality_eval",
        "role_case_play": "role_case_play",
        "case_study": "role_case_play",
        "scenario": "role_case_play",
    }
    return mapping.get(key)


def _skill_gap_from_rows(
    *,
    ai_rows: list[Any],
    assessment_rows: list[Any],
) -> SkillGapSummary:
    assessed: set[str] = set()
    missing: set[str] = set()
    for row in ai_rows:
        for s in list(row.verified_skills or []):
            if s and str(s).strip():
                assessed.add(str(s).strip())
        for s in list(row.growth_areas or []):
            if s and str(s).strip():
                missing.add(str(s).strip())
    for row in assessment_rows:
        for item in list(row.skill_scores or []):
            if not isinstance(item, dict):
                continue
            name = item.get("skill") or item.get("name")
            if not name:
                continue
            name_s = str(name).strip()
            if not name_s:
                continue
            score = item.get("score")
            correct = item.get("correct")
            total = item.get("total") or item.get("max_score")
            weak = False
            try:
                if score is not None and float(score) < 70:
                    weak = True
                elif correct is not None and total:
                    weak = float(correct) / float(total) < 0.7
            except (TypeError, ValueError):
                weak = False
            if weak:
                missing.add(name_s)
            else:
                assessed.add(name_s)

    # Gaps that are also assessed stay in missing for "needs work"
    missing_list = sorted(missing)
    assessed_list = sorted(assessed)
    total = len(set(assessed_list) | set(missing_list))
    miss_n = len(missing_list)
    if total == 0:
        return SkillGapSummary(label="0 out of 0")
    return SkillGapSummary(
        missing=miss_n,
        total=total,
        label=f"{miss_n} out of {total}",
        missing_skills=missing_list,
        assessed_skills=assessed_list,
    )


class ProgressAnalyticsService:
    async def analyze(
        self, payload: ProgressAnalyticsRequest
    ) -> ProgressAnalyticsResponse:
        cid = payload.candidate_id.strip()
        job_title = (payload.job_title or "").strip() or None

        ai_all = store.list_ai_evaluations(candidate_id=cid)
        asmt_all = store.list_assessment_attempts(candidate_id=cid)

        ai_rows = [
            r for r in ai_all if _role_match(r.role_title, job_title)
        ]
        asmt_rows = [
            r for r in asmt_all if _role_match(r.role_title, job_title)
        ]
        # Chronological ascending for history charts
        ai_chrono = list(reversed(ai_rows))
        asmt_chrono = list(reversed(asmt_rows))

        interview_history = [
            ScorePoint(
                recorded_at=r.recorded_at,
                score=float(r.overall_score)
                if r.overall_score is not None
                else None,
                label=r.source_type or "interview",
                source_id=r.interview_id or r.evaluation_id,
            )
            for r in ai_chrono
            if r.overall_score is not None
        ]
        assessment_history = [
            ScorePoint(
                recorded_at=r.recorded_at,
                score=float(r.score) if r.score is not None else None,
                label=_normalize_assessment_type(r.kind, r.meta) or r.kind or "assessment",
                source_id=r.assessment_id,
            )
            for r in asmt_chrono
            if r.score is not None
        ]

        interview_scores = [
            float(p.score) for p in interview_history if p.score is not None
        ]
        assessment_scores_list = [
            float(p.score) for p in assessment_history if p.score is not None
        ]

        avg_interview = _avg(interview_scores)
        avg_assessment = _avg(assessment_scores_list)
        asmt_trend, asmt_trend_label = _trend(assessment_scores_list)

        readiness_parts = [s for s in [avg_interview, avg_assessment] if s is not None]
        readiness = _avg(readiness_parts)

        # Latest mock-style AI row for dimension breakdown
        latest_ai = ai_rows[0] if ai_rows else None
        behavioral = None
        if latest_ai is not None:
            behavioral = (
                latest_ai.culture_fit_score
                if latest_ai.culture_fit_score is not None
                else latest_ai.confidence_score
            )
        mock_scores = MockInterviewScores(
            technical_score=latest_ai.technical_score if latest_ai else None,
            behavioral_score=behavioral,
            communication_score=(
                latest_ai.communication_score if latest_ai else None
            ),
        )

        # Latest score per assessment type
        latest_by_type: dict[str, float] = {}
        for r in asmt_rows:  # already newest-first
            atype = _normalize_assessment_type(r.kind, r.meta)
            if not atype or r.score is None:
                continue
            if atype not in latest_by_type:
                latest_by_type[atype] = float(r.score)
        assessment_type_scores = AssessmentTypeScores(
            coding_challenge_score=latest_by_type.get("coding_challenge"),
            aptitude_and_reasoning_score=latest_by_type.get(
                "aptitude_and_reasoning"
            ),
            role_case_play_score=latest_by_type.get("role_case_play"),
            personality_eval_score=latest_by_type.get("personality_eval"),
        )

        skill_gap = _skill_gap_from_rows(ai_rows=ai_rows, assessment_rows=asmt_rows)

        available = bool(interview_history or assessment_history)

        return ProgressAnalyticsResponse(
            correlation_id=payload.correlation_id,
            candidate_id=cid,
            job_title=job_title,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message=(
                "Progress analytics from stored performance"
                if available
                else "No stored performance data for this candidate"
            ),
            interview_readiness_percent=readiness,
            avg_interview_score_percent=avg_interview,
            avg_assessment_score_percent=avg_assessment,
            assessment_trend=asmt_trend,  # type: ignore[arg-type]
            assessment_trend_label=asmt_trend_label,
            skill_gap=skill_gap,
            interview_score_history=interview_history,
            assessment_score_history=assessment_history,
            mock_interview_scores=mock_scores,
            assessment_scores=assessment_type_scores,
        )
