"""Lessons 5 and 6: LLM-as-judge with prompts, robust parsing and bias controls."""
from __future__ import annotations

import json
import os
import re
import urllib.request
from typing import Callable

from .metrics import extract_json

POINTWISE_PROMPT = """You are grading an AI assistant's answer.

Question:
<question>
{question}
</question>

Reference answer (may be incomplete; use it as guidance, not as the only correct wording):
<reference>
{reference}
</reference>

Assistant's answer:
<answer>
{answer}
</answer>

Grade with this rubric:
5 = fully correct and complete, no unsupported claims
4 = correct, minor omissions
3 = partially correct or missing important details
2 = mostly incorrect or misleading
1 = wrong, irrelevant, or harmful

First write one or two sentences of reasoning, then output JSON on the last line:
{{"reasoning": "...", "score": <1-5>}}"""

PAIRWISE_PROMPT = """Two AI assistants answered the same question. Decide which answer is better
for the user: more correct, more complete, and clearer. Length alone is not a reason to prefer an answer.

Question:
<question>
{question}
</question>

Answer A:
<answer_a>
{a}
</answer_a>

Answer B:
<answer_b>
{b}
</answer_b>

Output JSON only: {{"winner": "A" | "B" | "tie", "reason": "..."}}"""

Judge = Callable[[str], str]   # prompt in, raw judge text out


class JudgeParseError(ValueError):
    pass


def parse_score(raw: str, low: int = 1, high: int = 5) -> int:
    """Read {"score": n} from the judge's reply; fall back to a 'score: n' pattern."""
    try:
        obj = extract_json(raw)
        if isinstance(obj, dict) and "score" in obj:
            score = int(obj["score"])
        else:
            raise ValueError
    except (ValueError, TypeError):
        m = re.search(r"score\W{0,3}(\d)", raw, re.I)
        if not m:
            raise JudgeParseError(f"no score in judge output: {raw[:120]!r}") from None
        score = int(m.group(1))
    if not low <= score <= high:
        raise JudgeParseError(f"score {score} outside {low}-{high}")
    return score


def parse_winner(raw: str) -> str:
    try:
        obj = extract_json(raw)
        winner = str(obj.get("winner", "")).strip().upper() if isinstance(obj, dict) else ""
    except ValueError:
        m = re.search(r'winner\W{0,4}(A|B|tie)\b', raw, re.I)
        winner = m.group(1).upper() if m else ""
    if winner not in {"A", "B", "TIE"}:
        raise JudgeParseError(f"no winner in judge output: {raw[:120]!r}")
    return "tie" if winner == "TIE" else winner


def grade(judge: Judge, question: str, answer: str, reference: str = "", samples: int = 1) -> float:
    """Pointwise grade normalized to [0, 1]. samples > 1 averages several judge calls."""
    prompt = POINTWISE_PROMPT.format(question=question, reference=reference or "(none)", answer=answer)
    scores = [parse_score(judge(prompt)) for _ in range(samples)]
    return (sum(scores) / len(scores) - 1) / 4


def compare(judge: Judge, question: str, answer_1: str, answer_2: str) -> str:
    """Pairwise comparison run twice with positions swapped to cancel position bias.

    Returns "1", "2" or "tie". If the two orders disagree, the result is a tie.
    """
    first = parse_winner(judge(PAIRWISE_PROMPT.format(question=question, a=answer_1, b=answer_2)))
    second = parse_winner(judge(PAIRWISE_PROMPT.format(question=question, a=answer_2, b=answer_1)))
    v1 = {"A": "1", "B": "2", "tie": "tie"}[first]
    v2 = {"A": "2", "B": "1", "tie": "tie"}[second]
    return v1 if v1 == v2 else "tie"


def openai_compatible_judge(model: str | None = None, base_url: str | None = None, api_key: str | None = None,
                            timeout: float = 120) -> Judge:
    """A judge backed by any OpenAI-compatible chat endpoint (Ollama, vLLM, hosted APIs). Temperature 0."""
    base = (base_url or os.environ.get("JUDGE_BASE_URL", "http://localhost:11434/v1")).rstrip("/")
    model = model or os.environ.get("JUDGE_MODEL", "llama3.2")
    key = api_key if api_key is not None else os.environ.get("JUDGE_API_KEY", "")

    def call(prompt: str) -> str:
        body = json.dumps({"model": model, "temperature": 0,
                           "messages": [{"role": "user", "content": prompt}]}).encode()
        headers = {"Content-Type": "application/json", **({"Authorization": f"Bearer {key}"} if key else {})}
        req = urllib.request.Request(f"{base}/chat/completions", data=body, headers=headers, method="POST")
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.load(resp)["choices"][0]["message"]["content"]

    return call
