"""Case study simulator generate / grade."""

from __future__ import annotations

from typing import Any
from uuid import uuid4

from app.schemas.case_studies import (
    CaseStudyGenerateRequest,
    CaseStudyGenerateResponse,
    CaseStudyGradeRequest,
    CaseStudyGradeResponse,
)
from app.schemas.common import JobStatus
from app.services.shared.ai_generate import generate_json


def _local_case(payload: CaseStudyGenerateRequest) -> dict[str, Any]:
    jd = (payload.job_description or "").strip()
    jd_blurb = jd[:400] if jd else "the role responsibilities"
    return {
        "title": f"{payload.role_title} decision case",
        "scenario_markdown": (
            f"## Scenario\nYou are a {payload.role_title}. Use this job "
            f"context:\n\n{jd_blurb}\n\nLeadership asks you to diagnose a "
            "delivery risk and propose a 30-day action plan aligned to the JD."
        ),
        "tasks": [
            "Identify root causes tied to the JD responsibilities",
            "Propose prioritized actions matching required skills",
            "Define success metrics for this role",
            "Call out risks and trade-offs",
        ],
        "rubric": {
            "structure": 25,
            "insight": 25,
            "feasibility": 25,
            "communication": 25,
            "passing_score": 70,
        },
    }


def _normalize_tasks(value: Any) -> list[str]:
    if not isinstance(value, (list, tuple)):
        return []
    return [str(t).strip() for t in value if t is not None and str(t).strip()]


def _normalize_rubric(value: Any, *, fallback: dict[str, Any]) -> dict[str, Any]:
    if isinstance(value, dict) and value:
        return dict(value)
    return dict(fallback)


class CaseStudiesService:
    async def generate(
        self, payload: CaseStudyGenerateRequest
    ) -> CaseStudyGenerateResponse:
        system = (
            "Create a hiring case study for open-ended evaluation. "
            "Return only valid JSON: "
            '{"title":"","scenario_markdown":"","tasks":[],"rubric":{}}\n'
            "Rules:\n"
            "- Ground the scenario and tasks in the provided job description.\n"
            "- scenario_markdown must be markdown with a clear business situation.\n"
            "- tasks: 3-6 concrete deliverables for the candidate.\n"
            "- rubric: dimension weights (numbers) plus optional passing_score.\n"
            "- Match the role, JD skills/responsibilities, difficulty, and time limit.\n"
            "- Do not invent company secrets; keep the scenario fictional and generic.\n"
        )
        user = (
            f"Role: {payload.role_title}\nIndustry: {payload.industry}\n"
            f"Difficulty: {payload.difficulty.value}\n"
            f"Time: {payload.time_limit_minutes} minutes\nLanguage: {payload.language}\n"
            f"Job description (REQUIRED — build case from this):\n"
            f"{payload.job_description}"
        )

        def local() -> dict[str, Any]:
            return _local_case(payload)

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        if not isinstance(data, dict):
            data = local()
            stub, provider = True, "local"

        title = data.get("title")
        scenario = data.get("scenario_markdown")
        tasks = _normalize_tasks(data.get("tasks"))
        fallback = local()
        if not (isinstance(title, str) and title.strip()) or not (
            isinstance(scenario, str) and scenario.strip()
        ):
            title = fallback["title"]
            scenario = fallback["scenario_markdown"]
            tasks = tasks or list(fallback["tasks"])
            stub, provider = True, "local"

        return CaseStudyGenerateResponse(
            correlation_id=payload.correlation_id,
            case_id=str(uuid4()),
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Case study generated via {provider}",
            title=str(title).strip() if title else None,
            scenario_markdown=str(scenario).strip() if scenario else None,
            tasks=tasks or list(fallback["tasks"]),
            rubric=_normalize_rubric(data.get("rubric"), fallback=fallback["rubric"]),
        )

    async def grade(self, payload: CaseStudyGradeRequest) -> CaseStudyGradeResponse:
        system = (
            "Grade a case-study submission. Return only valid JSON: "
            '{"total_score":0,"max_total_score":100,"passed":false,'
            '"feedback_markdown":"","rubric_scores":{}}\n'
            "Rules:\n"
            "- Scores are numeric; max_total_score defaults to 100.\n"
            "- Apply the supplied rubric dimensions when present.\n"
            "- passed should reflect the rubric passing_score when provided "
            "(default 70).\n"
            "- feedback_markdown: concise recruiter-facing notes.\n"
        )
        user = (
            f"Case: {payload.case_id}\nRole: {payload.role_title}\n"
            f"Rubric: {payload.rubric}\nSubmission:\n{payload.candidate_submission}\n"
            f"Language: {payload.language}"
        )

        def local() -> dict[str, Any]:
            length = len(payload.candidate_submission.strip())
            score = 55.0 if length < 200 else 72.0 if length < 800 else 84.0
            passing = float((payload.rubric or {}).get("passing_score") or 70.0)
            return {
                "total_score": score,
                "max_total_score": 100.0,
                "passed": score >= passing,
                "feedback_markdown": (
                    "Solid structure. Strengthen quantified impact and risk mitigation."
                ),
                "rubric_scores": {
                    "structure": score * 0.25,
                    "insight": score * 0.25,
                    "feasibility": score * 0.25,
                    "communication": score * 0.25,
                },
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        if not isinstance(data, dict):
            data = local()
            stub, provider = True, "local"

        total = float(data.get("total_score") or 0)
        max_total = float(data.get("max_total_score") or 100)
        passed = data.get("passed")
        if passed is None:
            passing = float((payload.rubric or {}).get("passing_score") or 70.0)
            passed = total >= passing

        return CaseStudyGradeResponse(
            correlation_id=payload.correlation_id,
            case_id=payload.case_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Case study graded via {provider}",
            total_score=total,
            max_total_score=max_total,
            passed=bool(passed),
            feedback_markdown=data.get("feedback_markdown"),
            rubric_scores=data.get("rubric_scores")
            if isinstance(data.get("rubric_scores"), dict)
            else {},
        )
