"""Timed puzzle challenges — SOW Assessment Types."""

from uuid import uuid4

from app.schemas.common import JobStatus
from app.schemas.puzzles import (
    PuzzleGenerateRequest,
    PuzzleGenerateResponse,
    PuzzleGradeRequest,
    PuzzleGradeResponse,
)
from app.schemas.questions import QuestionType
from app.schemas.scoring import SkillScoreItem, TimingReport
from app.services.assessments.grading import (
    apply_timing_to_result,
    auto_grade_answers,
    evaluate_timing,
    export_answer_key,
    feedback_from_items,
    normalize_answer_key,
    resolve_time_limit,
    resolve_time_taken,
    tag_questions_with_skills,
)
from app.services.shared.ai_generate import generate_json
from app.services.screening.questions import _local_questions, _parse_questions


class PuzzlesService:
    async def generate(self, payload: PuzzleGenerateRequest) -> PuzzleGenerateResponse:
        skills = list(payload.skills) or [payload.puzzle_type, "logical_reasoning"]
        system = (
            "Generate timed puzzle / brain-teaser challenges as MCQs with a single "
            "correct answer. Return JSON: "
            '{"puzzles":[{"id","stem","answer","explanation",'
            '"options":[{"key","text","is_correct"}],"metadata":{"skills":[]}}]}'
        )
        user = (
            f"Type: {payload.puzzle_type}\nRole: {payload.role_title}\n"
            f"Difficulty: {payload.difficulty.value}\nCount: {payload.count}\n"
            f"Time limit minutes: {payload.time_limit_minutes}\n"
            f"Skills to tag: {skills}\nLanguage: {payload.language}"
        )

        def local() -> dict:
            return {
                "puzzles": _local_questions(
                    count=payload.count,
                    qtype=QuestionType.MCQ,
                    difficulty=payload.difficulty,
                    topic=f"puzzle / {payload.puzzle_type}",
                )
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        puzzles = _parse_questions(
            data.get("puzzles") or data.get("questions") or [],
            QuestionType.MCQ,
            payload.difficulty,
        )
        puzzles = tag_questions_with_skills(puzzles, skills)
        answer_key = export_answer_key(puzzles)
        return PuzzleGenerateResponse(
            correlation_id=payload.correlation_id,
            puzzle_set_id=str(uuid4()),
            puzzle_type=payload.puzzle_type,
            time_limit_minutes=payload.time_limit_minutes,
            skills=skills,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Puzzles via {provider}",
            puzzles=puzzles,
            answer_key=answer_key,
        )

    async def grade(self, payload: PuzzleGradeRequest) -> PuzzleGradeResponse:
        answer_key = normalize_answer_key(
            answer_key=payload.answer_key or payload.options.get("answer_key"),
            questions=payload.questions or payload.options.get("questions"),
        )
        has_key = bool(answer_key) and any(
            (row.get("answer") is not None and str(row.get("answer")).strip() != "")
            for row in answer_key.values()
        )
        time_limit = resolve_time_limit(
            payload.time_limit_minutes,
            payload.options,
            questions=payload.questions,
            answer_key=answer_key,
            default=20,
        )
        timing = evaluate_timing(
            time_limit_minutes=time_limit,
            time_taken_seconds=resolve_time_taken(
                payload.time_taken_seconds, payload.options
            ),
            overtime_fail=bool(payload.options.get("fail_on_overtime", True)),
            overtime_penalty_ratio=float(
                payload.options.get("overtime_penalty_ratio") or 0.0
            ),
        )
        passing_ratio = float(payload.options.get("passing_ratio") or 0.6)

        if has_key:
            items, total, max_total, skill_scores, passed = auto_grade_answers(
                answers=payload.answers,
                answer_key=answer_key,
                default_skill="logical_reasoning",
                passing_ratio=passing_ratio,
            )
            total, passed, timing = apply_timing_to_result(
                total=total,
                max_total=max_total,
                passed=passed,
                timing=timing,
                fail_on_overtime=bool(payload.options.get("fail_on_overtime", True)),
            )
            feedback = feedback_from_items(
                items=items,
                total=total,
                max_total=max_total,
                timing=timing,
                label="Puzzle",
            )
            return PuzzleGradeResponse(
                correlation_id=payload.correlation_id,
                puzzle_set_id=payload.puzzle_set_id,
                status=JobStatus.SUCCEEDED,
                stub=False,
                message="Puzzles auto-scored from answer key",
                total_score=total,
                max_total_score=max_total,
                passed=passed,
                auto_scored=True,
                feedback_markdown=feedback,
                item_results=[i.as_dict() for i in items],
                skill_scores=[SkillScoreItem(**s.as_dict()) for s in skill_scores],
                timing=TimingReport(**timing.as_dict()),
            )

        # No key — LLM / local heuristic (legacy)
        system = (
            "Grade puzzle answers. Return JSON: "
            '{"total_score","max_total_score","passed","feedback_markdown",'
            '"item_results":[],"skill_scores":[]}'
        )
        user = (
            f"set={payload.puzzle_set_id}\nanswers={payload.answers}\n"
            f"time={payload.time_taken_seconds}\ntime_limit={time_limit}"
        )

        def local() -> dict:
            items, total, max_total, skill_scores, passed = auto_grade_answers(
                answers=payload.answers,
                answer_key=None,
                default_skill="logical_reasoning",
                passing_ratio=passing_ratio,
            )
            total, passed, _ = apply_timing_to_result(
                total=total,
                max_total=max_total,
                passed=passed,
                timing=timing,
            )
            return {
                "total_score": total,
                "max_total_score": max_total,
                "passed": passed,
                "feedback_markdown": feedback_from_items(
                    items=items,
                    total=total,
                    max_total=max_total,
                    timing=timing,
                    label="Puzzle",
                ),
                "item_results": [i.as_dict() for i in items],
                "skill_scores": [s.as_dict() for s in skill_scores],
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        skill_raw = list(data.get("skill_scores") or [])
        return PuzzleGradeResponse(
            correlation_id=payload.correlation_id,
            puzzle_set_id=payload.puzzle_set_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Puzzles graded via {provider}",
            total_score=float(data.get("total_score") or 0),
            max_total_score=float(data.get("max_total_score") or 0),
            passed=data.get("passed"),
            auto_scored=False,
            feedback_markdown=data.get("feedback_markdown"),
            item_results=list(data.get("item_results") or []),
            skill_scores=[
                SkillScoreItem(**s) if isinstance(s, dict) else s for s in skill_raw
            ],
            timing=TimingReport(**timing.as_dict()),
        )
