"""Answer evaluation — auto / rubric / comparative."""

from app.schemas.answers import (
    AnswerEvaluationRequest,
    AnswerEvaluationResponse,
    EvaluatedAnswer,
    EvaluationMode,
    ScoreBreakdown,
)
from app.schemas.common import JobStatus
from app.schemas.scoring import SkillScoreItem
from app.services.assessments.grading import (
    SkillScore,
    auto_grade_answers,
    normalize_answer_key,
)
from app.services.shared.ai_generate import generate_json


def _normalize_breakdown(
    raw: object,
    *,
    answer_max_score: float,
) -> list[ScoreBreakdown]:
    """Coerce LLM breakdown rows into ScoreBreakdown (max_score often omitted)."""
    if not isinstance(raw, list):
        return []
    rows = [b for b in raw if isinstance(b, dict)]
    if not rows:
        return []
    n = len(rows)
    default_max = (answer_max_score / n) if n and answer_max_score else 1.0
    out: list[ScoreBreakdown] = []
    for b in rows:
        try:
            score = float(b.get("score", 0) or 0)
        except (TypeError, ValueError):
            score = 0.0
        try:
            max_score = float(
                b["max_score"]
                if b.get("max_score") is not None
                else default_max
            )
        except (TypeError, ValueError, KeyError):
            max_score = default_max
        if max_score <= 0:
            max_score = default_max if default_max > 0 else 1.0
        # Keep score within [0, max_score]
        if score > max_score:
            score = max_score
        if score < 0:
            score = 0.0
        out.append(
            ScoreBreakdown(
                criterion=str(b.get("criterion") or b.get("name") or "criterion"),
                score=score,
                max_score=max_score,
                comment=(
                    str(b["comment"])
                    if b.get("comment") is not None
                    else None
                ),
            )
        )
    return out


class AnswerEvaluationService:
    async def evaluate(self, payload: AnswerEvaluationRequest) -> AnswerEvaluationResponse:
        # Deterministic auto path when all items have expected_answer (AUTO mode)
        if payload.mode == EvaluationMode.AUTO and all(
            (a.expected_answer or "").strip() for a in payload.answers
        ):
            answer_dicts = [
                {
                    "question_id": a.question_id,
                    "selected": a.student_answer,
                    "max_score": a.max_score,
                    "skills": a.skills
                    or payload.options.get("skills")
                    or [],
                }
                for a in payload.answers
            ]
            key = normalize_answer_key(
                answer_key={
                    a.question_id: {
                        "answer": a.expected_answer,
                        "max_score": a.max_score,
                        "skills": a.skills
                        or payload.options.get("skills")
                        or [],
                    }
                    for a in payload.answers
                }
            )
            items, total, max_total, skill_scores, _passed = auto_grade_answers(
                answers=answer_dicts,
                answer_key=key,
                passing_ratio=float(payload.options.get("passing_ratio") or 0.6),
            )
            results = []
            for a, item in zip(payload.answers, items, strict=False):
                breakdown: list[ScoreBreakdown] = []
                if a.rubric:
                    # Split score evenly across rubric criteria for reporting
                    n = len(a.rubric)
                    per = (item.score / n) if n else item.score
                    per_max = (item.max_score / n) if n else item.max_score
                    for crit in a.rubric:
                        breakdown.append(
                            ScoreBreakdown(
                                criterion=crit,
                                score=round(per, 4),
                                max_score=round(per_max, 4),
                                comment=item.feedback,
                            )
                        )
                results.append(
                    EvaluatedAnswer(
                        question_id=a.question_id,
                        score=item.score,
                        max_score=item.max_score,
                        is_correct=item.is_correct,
                        feedback=item.feedback,
                        breakdown=breakdown,
                        metadata={"auto_scored": True, "skill": item.skill},
                    )
                )
            return AnswerEvaluationResponse(
                correlation_id=payload.correlation_id,
                assessment_id=payload.assessment_id,
                status=JobStatus.SUCCEEDED,
                stub=False,
                message="Answers auto-scored from expected_answer keys",
                total_score=total,
                max_total_score=max_total,
                auto_scored=True,
                results=results,
                skill_scores=[SkillScoreItem(**s.as_dict()) for s in skill_scores],
            )

        system = (
            "Grade answers fairly. Return JSON: {\"results\":[{\"question_id\",\"score\","
            "\"max_score\",\"is_correct\",\"feedback\",\"breakdown\":[{\"criterion\","
            "\"score\",\"max_score\",\"comment\"}]}],"
            "\"total_score\",\"max_total_score\",\"skill_scores\":[]}. "
            "Each breakdown item MUST include numeric score and max_score."
        )
        answers_blob = [
            {
                "question_id": a.question_id,
                "question_text": a.question_text,
                "expected_answer": a.expected_answer,
                "student_answer": a.student_answer,
                "max_score": a.max_score,
                "rubric": a.rubric,
                "skills": a.skills,
            }
            for a in payload.answers
        ]
        user = (
            f"mode={payload.mode.value}\nlanguage={payload.language}\n"
            f"answers={answers_blob}"
        )

        def local() -> dict:
            answer_dicts = [
                {
                    "question_id": a.question_id,
                    "selected": a.student_answer,
                    "max_score": a.max_score,
                    "skills": a.skills,
                    "expected_answer": a.expected_answer,
                }
                for a in payload.answers
            ]
            key = normalize_answer_key(
                answer_key={
                    a.question_id: {
                        "answer": a.expected_answer,
                        "max_score": a.max_score,
                        "skills": a.skills,
                    }
                    for a in payload.answers
                    if a.expected_answer
                }
            )
            items, total, max_total, skill_scores, _ = auto_grade_answers(
                answers=answer_dicts,
                answer_key=key or None,
            )
            # Rubric mode: soft partial credit when expected missing
            if payload.mode == EvaluationMode.RUBRIC:
                results = []
                total = 0.0
                max_total = 0.0
                skill_map: dict[str, SkillScore] = {}
                for a in payload.answers:
                    max_total += a.max_score
                    given = a.student_answer.strip()
                    expected = (a.expected_answer or "").strip().lower()
                    if expected and given.lower() == expected:
                        score = a.max_score
                        correct: bool | None = True
                        feedback = "Matches expected answer."
                    elif given:
                        # Partial: length / keyword overlap heuristic
                        score = round(a.max_score * 0.6, 4)
                        correct = None
                        feedback = "Partial credit against rubric — expand evidence."
                    else:
                        score = 0.0
                        correct = False
                        feedback = "Empty answer."
                    total += score
                    breakdown = [
                        ScoreBreakdown(
                            criterion=c,
                            score=round(score / len(a.rubric), 4) if a.rubric else score,
                            max_score=round(a.max_score / len(a.rubric), 4)
                            if a.rubric
                            else a.max_score,
                            comment=feedback,
                        )
                        for c in (a.rubric or ["overall"])
                    ]
                    results.append(
                        {
                            "question_id": a.question_id,
                            "score": score,
                            "max_score": a.max_score,
                            "is_correct": correct,
                            "feedback": feedback,
                            "breakdown": [b.model_dump() for b in breakdown],
                        }
                    )
                    for sk in a.skills or ["general"]:
                        ss = skill_map.setdefault(
                            sk, SkillScore(skill=sk, score=0.0, max_score=0.0)
                        )
                        ss.score += score
                        ss.max_score += a.max_score
                        ss.items += 1
                        if correct:
                            ss.correct += 1
                return {
                    "results": results,
                    "total_score": total,
                    "max_total_score": max_total,
                    "skill_scores": [s.as_dict() for s in skill_map.values()],
                }

            return {
                "results": [
                    {
                        "question_id": i.question_id,
                        "score": i.score,
                        "max_score": i.max_score,
                        "is_correct": i.is_correct,
                        "feedback": i.feedback,
                        "breakdown": [],
                    }
                    for i in items
                ],
                "total_score": total,
                "max_total_score": max_total,
                "skill_scores": [s.as_dict() for s in skill_scores],
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        # Map question_id → requested max_score for breakdown defaults
        max_by_qid = {a.question_id: float(a.max_score) for a in payload.answers}
        results = []
        for r in data.get("results") or []:
            if not isinstance(r, dict):
                continue
            qid = str(r.get("question_id", ""))
            try:
                ans_max = float(r.get("max_score", max_by_qid.get(qid, 1.0)))
            except (TypeError, ValueError):
                ans_max = max_by_qid.get(qid, 1.0)
            try:
                score = float(r.get("score", 0))
            except (TypeError, ValueError):
                score = 0.0
            results.append(
                EvaluatedAnswer(
                    question_id=qid,
                    score=score,
                    max_score=ans_max if ans_max > 0 else 1.0,
                    is_correct=r.get("is_correct"),
                    feedback=r.get("feedback"),
                    breakdown=_normalize_breakdown(
                        r.get("breakdown"),
                        answer_max_score=ans_max if ans_max > 0 else 1.0,
                    ),
                    metadata={},
                )
            )
        max_total = float(
            data.get("max_total_score")
            if data.get("max_total_score") is not None
            else sum(a.max_score for a in payload.answers)
        )
        total = float(
            data.get("total_score")
            if data.get("total_score") is not None
            else sum(r.score for r in results)
        )
        skill_raw = list(data.get("skill_scores") or [])
        return AnswerEvaluationResponse(
            correlation_id=payload.correlation_id,
            assessment_id=payload.assessment_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Evaluated answers via {provider}",
            total_score=total,
            max_total_score=max_total,
            auto_scored=False,
            results=results,
            skill_scores=[
                SkillScoreItem(**s) if isinstance(s, dict) else s for s in skill_raw
            ],
        )
