"""Multi-language coding challenge AI judge."""

from app.schemas.coding import CodingJudgeRequest, CodingJudgeResponse
from app.schemas.common import JobStatus
from app.services.ai_generate import generate_json


class CodingService:
    async def judge(self, payload: CodingJudgeRequest) -> CodingJudgeResponse:
        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}"
        )

        def local() -> dict:
            code = payload.candidate_code.lower()
            has_logic = any(k in code for k in ("def ", "function", "class ", "return", "=>"))
            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
            total = round((correctness * 50) + (quality * 30) + (efficiency * 20), 1)
            return {
                "total_score": total,
                "max_total_score": 100.0,
                "passed": total >= 60,
                "correctness": correctness,
                "code_quality": quality,
                "efficiency": efficiency,
                "feedback_markdown": (
                    f"Judged as `{payload.language}` submission. "
                    "Strengthen edge cases and clarity of approach."
                ),
                "failing_tests": [] if correctness >= 0.7 else ["edge_case_empty_input"],
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        return CodingJudgeResponse(
            correlation_id=payload.correlation_id,
            challenge_id=payload.challenge_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Coding judged via {provider}",
            total_score=float(data.get("total_score") or 0),
            max_total_score=float(data.get("max_total_score") or 100),
            passed=data.get("passed"),
            correctness=data.get("correctness"),
            code_quality=data.get("code_quality"),
            efficiency=data.get("efficiency"),
            feedback_markdown=data.get("feedback_markdown"),
            failing_tests=list(data.get("failing_tests") or []),
        )
