"""Answer evaluation."""

from app.schemas.answers import (AnswerEvaluationRequest,AnswerEvaluationResponse,EvaluatedAnswer,
)
from app.schemas.common import JobStatus
from app.services.ai_generate import generate_json


class AnswerEvaluationService:
    async def evaluate(self, payload: AnswerEvaluationRequest) -> AnswerEvaluationResponse:
        system = (
            "Grade answers fairly. Return JSON: {\"results\":[{\"question_id\",\"score\","
            "\"max_score\",\"is_correct\",\"feedback\"}],\"total_score\",\"max_total_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,
            }
            for a in payload.answers
        ]
        user = f"mode={payload.mode.value}\nlanguage={payload.language}\nanswers={answers_blob}"

        def local() -> dict:
            results = []
            total = 0.0
            max_total = 0.0
            for a in payload.answers:
                max_total += a.max_score
                expected = (a.expected_answer or "").strip().lower()
                given = a.student_answer.strip().lower()
                correct = bool(expected) and expected == given
                score = a.max_score if correct else (a.max_score * 0.5 if given else 0.0)
                total += score
                results.append(
                    {
                        "question_id": a.question_id,
                        "score": score,
                        "max_score": a.max_score,
                        "is_correct": correct if expected else None,
                        "feedback": (
                            "Exact match."
                            if correct
                            else "Partial credit — expand with clearer evidence."
                        ),
                    }
                )
            return {
                "results": results,
                "total_score": total,
                "max_total_score": max_total,
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        results = [
            EvaluatedAnswer(
                question_id=str(r.get("question_id", "")),
                score=float(r.get("score", 0)),
                max_score=float(r.get("max_score", 1)),
                is_correct=r.get("is_correct"),
                feedback=r.get("feedback"),
                breakdown=[],
                metadata={},
            )
            for r in (data.get("results") or [])
            if isinstance(r, dict)
        ]
        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)
        )
        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,
            results=results,
        )
