"""Multi-language coding challenge AI judge + optional Python test exec."""

from typing import Any

from app.schemas.coding import CodingJudgeRequest, CodingJudgeResponse
from app.schemas.common import JobStatus
from app.schemas.scoring import SkillScoreItem, TestCaseResult
from app.services.assessments.code_exec import run_python_tests
from app.services.shared.ai_generate import generate_json


class CodingService:
    async def judge(self, payload: CodingJudgeRequest) -> CodingJudgeResponse:
        lang = (payload.language or "").strip().lower()
        execute = bool(payload.execute_tests)
        if "execute_tests" in payload.options:
            execute = bool(payload.options["execute_tests"])

        test_results: list[TestCaseResult] = []
        failing: list[str] = []
        tests_executed = False
        exec_ratio: float | None = None

        if execute and lang in {"python", "py"} and payload.test_cases:
            raw, exec_ratio, failing = run_python_tests(
                payload.candidate_code,
                payload.test_cases,
                timeout_seconds=float(payload.options.get("timeout_seconds") or 2.0),
            )
            tests_executed = True
            test_results = [TestCaseResult(**r) for r in raw]

        system = (
            "Judge coding submissions. Return JSON: "
            '{"total_score","max_total_score":100,"passed","correctness",'
            '"code_quality","efficiency","feedback_markdown","failing_tests":[]}'
        )
        user = (
            f"Lang: {payload.language}\nProblem: {payload.problem_statement}\n"
            f"Code:\n{payload.candidate_code}\nTests: {payload.test_cases}\n"
            f"Rubric: {payload.rubric}\n"
            f"Executed pass_ratio: {exec_ratio}\nFailing: {failing}"
        )

        def local() -> dict:
            code = payload.candidate_code.lower()
            has_logic = any(
                k in code for k in ("def ", "function", "class ", "return", "=>")
            )
            if exec_ratio is not None:
                correctness = float(exec_ratio)
            else:
                correctness = 0.75 if has_logic else 0.35
            quality = 0.7 if "test" in code or len(code) > 80 else 0.55
            efficiency = 0.65 if correctness >= 0.7 else 0.5
            total = round((correctness * 50) + (quality * 30) + (efficiency * 20), 1)
            return {
                "total_score": total,
                "max_total_score": 100.0,
                "passed": total >= 60 and (exec_ratio is None or exec_ratio >= 0.6),
                "correctness": correctness,
                "code_quality": quality,
                "efficiency": efficiency,
                "feedback_markdown": (
                    f"Judged as `{payload.language}` submission. "
                    + (
                        f"Tests: {sum(1 for t in test_results if t.passed)}/"
                        f"{len(test_results)} passed. "
                        if test_results
                        else ""
                    )
                    + "Strengthen edge cases and clarity of approach."
                ),
                "failing_tests": failing
                or ([] if correctness >= 0.7 else ["edge_case_empty_input"]),
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )

        def _unit(v: Any, default: float) -> float:
            try:
                x = float(v if v is not None else default)
            except (TypeError, ValueError):
                return default
            # Accept 0–1 or 0–100 scales from LLM
            if x > 1.0:
                x = x / 100.0
            return max(0.0, min(1.0, x))

        # Prefer executed correctness when tests ran
        correctness = data.get("correctness")
        if exec_ratio is not None:
            correctness = exec_ratio
            quality = _unit(data.get("code_quality"), 0.55)
            efficiency = _unit(data.get("efficiency"), 0.5)
            total = round((correctness * 50) + (quality * 30) + (efficiency * 20), 1)
            passed = total >= 60 and correctness >= 0.6
        else:
            total = float(data.get("total_score") or 0)
            # Clamp absurd LLM totals
            if total > 100:
                total = min(100.0, total / 100.0 if total <= 10000 else 100.0)
            passed = data.get("passed")
            correctness = _unit(correctness, 0.0) if correctness is not None else None

        fail_list = list(data.get("failing_tests") or [])
        if failing:
            fail_list = failing

        skills = list(payload.skills) or ["coding", lang or "programming"]
        max_total = float(data.get("max_total_score") or 100)
        skill_scores = [
            SkillScoreItem(
                skill=skills[0],
                score=round(float(total), 4),
                max_score=max_total,
                ratio=round(float(total) / max_total, 4) if max_total else 0.0,
                items=len(test_results) or 1,
                correct=sum(1 for t in test_results if t.passed)
                if test_results
                else (1 if passed else 0),
            )
        ]
        if len(skills) > 1:
            skill_scores.append(
                SkillScoreItem(
                    skill=skills[1],
                    score=round(float(correctness or 0) * 50, 4),
                    max_score=50.0,
                    ratio=round(float(correctness or 0), 4),
                    items=len(test_results) or 1,
                    correct=sum(1 for t in test_results if t.passed),
                )
            )

        return CodingJudgeResponse(
            correlation_id=payload.correlation_id,
            challenge_id=payload.challenge_id,
            status=JobStatus.SUCCEEDED,
            stub=stub and not tests_executed,
            message=(
                f"Coding judged via {provider}"
                + (" + python test exec" if tests_executed else "")
            ),
            total_score=float(total),
            max_total_score=max_total,
            passed=passed,
            correctness=float(correctness) if correctness is not None else None,
            code_quality=data.get("code_quality"),
            efficiency=data.get("efficiency"),
            feedback_markdown=data.get("feedback_markdown"),
            failing_tests=fail_list,
            test_results=test_results,
            tests_executed=tests_executed,
            skill_scores=skill_scores,
        )
