"""Step 23 — Interview analytics across sessions."""

from __future__ import annotations

import json
from collections import defaultdict
from pathlib import Path
from typing import Any

from app.config import get_settings
from app.schemas.common import JobStatus
from app.schemas.interview_analytics import (
    InterviewAnalyticsRequest,
    InterviewAnalyticsResponse,
    InterviewAnalyticsSessionInput,
    QuestionEffectiveness,
    ScoreDistribution,
)
from app.services.interviews.session_store import session_from_dict


def _percentile(sorted_vals: list[float], p: float) -> float | None:
    if not sorted_vals:
        return None
    if len(sorted_vals) == 1:
        return sorted_vals[0]
    k = (len(sorted_vals) - 1) * p
    f = int(k)
    c = min(f + 1, len(sorted_vals) - 1)
    if f == c:
        return sorted_vals[f]
    return sorted_vals[f] + (sorted_vals[c] - sorted_vals[f]) * (k - f)


def _distribution(scores: list[float]) -> ScoreDistribution:
    if not scores:
        return ScoreDistribution()
    s = sorted(scores)
    hist = {"0-0.25": 0, "0.25-0.5": 0, "0.5-0.75": 0, "0.75-1": 0}
    for v in scores:
        if v < 0.25:
            hist["0-0.25"] += 1
        elif v < 0.5:
            hist["0.25-0.5"] += 1
        elif v < 0.75:
            hist["0.5-0.75"] += 1
        else:
            hist["0.75-1"] += 1
    return ScoreDistribution(
        count=len(scores),
        mean=round(sum(scores) / len(scores), 3),
        min=round(s[0], 3),
        max=round(s[-1], 3),
        p25=round(_percentile(s, 0.25) or 0, 3),
        p50=round(_percentile(s, 0.5) or 0, 3),
        p75=round(_percentile(s, 0.75) or 0, 3),
        histogram=hist,
    )


def _session_from_checkpoint(data: dict[str, Any]) -> InterviewAnalyticsSessionInput:
    session = session_from_dict(data)
    scores = []
    degraded = 0
    qstats: list[dict[str, Any]] = []
    for i, ev in enumerate(session.evaluations or []):
        if not isinstance(ev, dict):
            continue
        if ev.get("score") is not None:
            try:
                scores.append(float(ev["score"]))
            except (TypeError, ValueError):
                pass
        if ev.get("degraded"):
            degraded += 1
        qid = (
            session.asked_question_ids[i]
            if i < len(session.asked_question_ids)
            else None
        )
        qstats.append(
            {
                "question_id": qid,
                "score": ev.get("score"),
                "kind": "follow_up"
                if (qid or "").startswith("fu-")
                else "planned",
                "degraded": bool(ev.get("degraded")),
            }
        )
    return InterviewAnalyticsSessionInput(
        interview_id=session.interview_id,
        role_title=session.role_title,
        status=session.status,
        turn_count=session.turn_count,
        planned_question_count=len(session.planned_questions),
        asked_question_count=len(session.asked_question_ids),
        scores=scores,
        question_stats=qstats,
        evaluation_degraded_count=degraded,
    )


def _load_persisted(role_title: str | None) -> list[InterviewAnalyticsSessionInput]:
    try:
        settings = get_settings()
        persist = Path(
            getattr(settings, "interview_session_persist_dir", None)
            or ".data/interview_sessions"
        )
    except Exception:  # noqa: BLE001
        persist = Path(".data/interview_sessions")
    if not persist.exists():
        return []
    out: list[InterviewAnalyticsSessionInput] = []
    for path in persist.glob("*.json"):
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            if not isinstance(data, dict):
                continue
            item = _session_from_checkpoint(data)
            if role_title and item.role_title and item.role_title != role_title:
                continue
            out.append(item)
        except Exception:  # noqa: BLE001
            continue
    return out


class InterviewAnalyticsService:
    async def analyze(
        self, payload: InterviewAnalyticsRequest
    ) -> InterviewAnalyticsResponse:
        sessions = list(payload.sessions)
        if payload.include_persisted_sessions:
            sessions.extend(_load_persisted(payload.role_title))

        # Dedupe by interview_id (inline overrides persisted)
        by_id: dict[str, InterviewAnalyticsSessionInput] = {}
        for s in sessions:
            by_id[s.interview_id] = s
        sessions = list(by_id.values())

        all_scores: list[float] = []
        completed = 0
        turns = 0
        degraded_total = 0
        eval_total = 0
        q_scores: dict[str, list[float]] = defaultdict(list)
        q_follow: dict[str, int] = defaultdict(int)
        q_asked: dict[str, int] = defaultdict(int)
        q_text: dict[str, str] = {}

        for s in sessions:
            if (s.status or "").lower() == "completed":
                completed += 1
            turns += s.turn_count
            all_scores.extend(s.scores)
            degraded_total += s.evaluation_degraded_count
            eval_total += max(len(s.scores), s.evaluation_degraded_count)
            for qs in s.question_stats:
                qid = str(qs.get("question_id") or "unknown")
                q_asked[qid] += 1
                if qs.get("score") is not None:
                    try:
                        q_scores[qid].append(float(qs["score"]))
                    except (TypeError, ValueError):
                        pass
                if qs.get("kind") == "follow_up":
                    q_follow[qid] += 1
                if qs.get("question_text"):
                    q_text[qid] = str(qs["question_text"])

        n = len(sessions)
        completion_rate = (completed / n) if n else 0.0
        avg_turns = (turns / n) if n else 0.0
        dist = _distribution(all_scores)

        effectiveness: list[QuestionEffectiveness] = []
        for qid, asked in sorted(q_asked.items(), key=lambda x: -x[1]):
            scores = q_scores.get(qid) or []
            avg = (sum(scores) / len(scores)) if scores else None
            fu_rate = (q_follow.get(qid, 0) / asked) if asked else 0.0
            if avg is None:
                label = "weak_signal"
            elif avg >= 0.75 and fu_rate <= 0.35:
                label = "strong_separator"
            elif avg < 0.45:
                label = "weak_signal"
            else:
                label = "average"
            effectiveness.append(
                QuestionEffectiveness(
                    question_id=qid,
                    question_text=q_text.get(qid),
                    times_asked=asked,
                    avg_score=round(avg, 3) if avg is not None else None,
                    follow_up_rate=round(fu_rate, 3),
                    effectiveness=label,
                )
            )

        quality = {
            "evaluations_scored": len(all_scores),
            "degraded_evaluations": degraded_total,
            "degraded_rate": round(degraded_total / max(1, len(all_scores)), 3)
            if all_scores
            else None,
            "sessions_with_scores": sum(1 for s in sessions if s.scores),
            "quality_band": (
                "high"
                if all_scores and (degraded_total / max(1, len(all_scores))) < 0.2
                else "medium"
                if all_scores
                else "low"
            ),
        }

        summary = (
            f"{n} session(s); completion_rate={completion_rate:.2f}; "
            f"mean_score={dist.mean}; eval_quality={quality['quality_band']}."
        )

        return InterviewAnalyticsResponse(
            correlation_id=payload.correlation_id,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message="Interview analytics computed",
            session_count=n,
            completion_rate=round(completion_rate, 3),
            avg_turns=round(avg_turns, 3),
            score_distribution=dist,
            question_effectiveness=effectiveness[:50],
            evaluation_quality=quality,
            summary=summary,
        )
