"""
Labelling for `dry-lint bench --replay N --label K`: a gold set from the repository's own history, and what it says
the configured judging would have caught, missed and blocked wrongly.

The replay's distinct pairs are sampled by the configured judge's score, weighted toward the scores where presets
decide (the PRIVATE_REPOSITORY gold set's design, docs/benchmark.md), and each sampled pair carries its stratum's size over
its sample size, so estimates describe every pair the replay proposed. A panel of labellers labels each pair blind:
the benchmark guideline and the two functions, never a score or a judge's answer. The label is the panel's strict
majority; a split is borderline and left out of the numbers. Every answer is kept beside the gold file, so running
again asks only about pairs no labeller has answered.

A labeller is an OpenRouter model id (needs OPENROUTER_API_KEY), or `command:<cli>` for any command that reads the
prompt on stdin and prints a JSON answer: a subscription CLI, or a script that asks a person.
"""

import os
import random
import shlex
import subprocess
from collections import Counter
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Literal, Protocol

import httpx
from pydantic import BaseModel, Field

from dry_lint.bench import BANDS, GoldFunction, GoldPair, JudgeBench, judge_bench, resampled, spread
from dry_lint.judges.command import first_object
from dry_lint.models import Candidate
from dry_lint.report import Finding
from dry_lint.settings import Settings

OPENROUTER = "https://openrouter.ai/api/v1/chat/completions"
LABELS = ("CONSOLIDATE", "SEPARATE", "PATTERN")
GUIDELINE = """You label pairs of functions from one codebase for a benchmark of duplicated concepts (DRY).

The test: does reconciling the two reveal ONE real concept with legitimate variations (it should have one
implementation, parameterized where they differ), or TWO different concepts that happen to share structure or APIs?

- CONSOLIDATE: one concept. Includes identical copies, renamed copies, independent re-implementations of the same
  concept, and variants whose differences should be parameters, even when the details differ or have drifted.
- SEPARATE: two different concepts that coincidentally look alike; or one calls the other; or the client and server
  ends of one endpoint; or an interface or stub and its implementation.
- PATTERN: deliberate instances of one template (one router, handler, command, fixture per resource) where a shared
  helper would not clearly be simpler.

Answer with one JSON object and nothing else:
{"label": "CONSOLIDATE" | "SEPARATE" | "PATTERN", "concept": "at most six words",
 "variation": "identical" | "parameterizable" | "drifted" | "n/a", "owner": "A" | "B" | "new shared helper" | "n/a"}
"""
SHAPE = (2, 2, 2, 4, 5, 5, 5, 5)  # sampling weight per score band in bench.BANDS: most where presets decide
UNJUDGED = 4  # pairs the judge never answered (no judge, or the budget ran out) form a stratum of this weight


class Answer(BaseModel):
    """One labeller's answer about one pair, as kept in the answers file."""

    key: str
    labeller: str
    label: Literal["CONSOLIDATE", "SEPARATE", "PATTERN"] | None = Field(description="None: no usable answer.")
    variation: str = ""
    owner: str = ""
    concept: str = ""
    usd: float | None = Field(default=None, description="What the answer cost, when the labeller says.")


class Labeller(Protocol):
    name: str

    def ask(self, prompt: str) -> tuple[str, float | None]:
        """The labeller's text answer to the prompt, and its cost in USD when known."""
        ...


class OpenRouterLabeller:
    def __init__(self, model: str, api_key: str | None = None, transport: httpx.BaseTransport | None = None) -> None:
        self.name, self.api_key, self.transport = model, api_key or os.environ.get("OPENROUTER_API_KEY", ""), transport
        if not self.api_key:
            raise ValueError(f"The labeller {model} needs OPENROUTER_API_KEY, or use `command:<cli>` labellers")

    def ask(self, prompt: str) -> tuple[str, float | None]:
        body = {
            "model": self.name,
            "messages": [{"role": "user", "content": prompt}],
            "max_tokens": 6000,
            "usage": {"include": True},
        }
        with httpx.Client(timeout=300, transport=self.transport) as client:
            response = client.post(OPENROUTER, json=body, headers={"Authorization": f"Bearer {self.api_key}"})
        response.raise_for_status()
        data = response.json()
        cost = data.get("usage", {}).get("cost")
        return data["choices"][0]["message"].get("content") or "", None if cost is None else float(cost)


class CommandLabeller:
    def __init__(self, command: str, timeout: float = 600) -> None:
        self.name, self.command, self.timeout = f"command:{command}", command, timeout

    def ask(self, prompt: str) -> tuple[str, float | None]:
        done = subprocess.run(
            shlex.split(self.command), input=prompt, capture_output=True, text=True, timeout=self.timeout, check=True
        )
        return done.stdout, None


def labeller(spec: str, transport: httpx.BaseTransport | None = None) -> Labeller:
    return (
        CommandLabeller(spec.removeprefix("command:"))
        if spec.startswith("command:")
        else OpenRouterLabeller(spec, transport=transport)
    )


def prompt(candidate: Candidate) -> str:
    """The guideline and the two functions: no score, no verdict, nothing about how the pair was found."""
    sides = [
        f"Function {letter}: {side.qualname}\n```\n{side.code}\n```"
        for letter, side in (("A", candidate.new), ("B", candidate.existing))
    ]
    return GUIDELINE + "\n" + "\n\n".join(sides)


def parse(text: str) -> dict | None:
    """The first JSON object in the text with a known label."""
    found = first_object(text, lambda answer: str(answer.get("label", "")).upper() in LABELS)
    return {**found, "label": str(found["label"]).upper()} if found else None


class Sampled(BaseModel):
    finding: Finding
    stratum: str
    weight: float


def stratum(finding: Finding) -> str:
    if finding.verdict is None:
        return "unjudged"
    band = next(i for i, high in enumerate(BANDS[1:]) if finding.verdict.score < high)
    return f"{BANDS[band]:.1f}-{min(BANDS[band + 1], 1.0):.1f}"


def sample(findings: list[Finding], size: int, seed: int = 20261103) -> list[Sampled]:
    """
    `size` distinct pairs, the latest finding of each, spread over score bands in proportion to `SHAPE` and never
    more than a band holds. Each carries its band's size over its sample size, so weighted sums describe them all.
    """
    latest = {f.candidate.key: f for f in findings}
    strata: dict[str, list[Finding]] = {}
    for finding in latest.values():
        strata.setdefault(stratum(finding), []).append(finding)
    shapes = {f"{BANDS[i]:.1f}-{min(BANDS[i + 1], 1.0):.1f}": w for i, w in enumerate(SHAPE)} | {"unjudged": UNJUDGED}
    sizes = allocate({name: len(pool) for name, pool in strata.items()}, {name: shapes[name] for name in strata}, size)
    rng = random.Random(seed)
    chosen = []
    for name in sorted(strata):
        pool = sorted(strata[name], key=lambda f: f.candidate.key)
        picked = rng.sample(pool, sizes[name])
        chosen += [Sampled(finding=f, stratum=name, weight=len(pool) / len(picked)) for f in picked]
    return chosen


def allocate(available: dict[str, int], shapes: dict[str, int], size: int) -> dict[str, int]:
    """
    `size` draws spread over strata in proportion to their shapes, at least one each and never more than a stratum
    holds; what a small stratum cannot take goes to the others, so the sample reaches `size` when there are enough.
    """
    taken = {name: min(1, count) for name, count in available.items()}
    while (left := size - sum(taken.values())) > 0:
        open_ = sorted((n for n in available if taken[n] < available[n]), key=lambda n: (-shapes[n], n))
        if not open_:
            break
        total = sum(shapes[n] for n in open_)
        for name in open_:
            extra = min(
                available[name] - taken[name], max(1, round(left * shapes[name] / total)), size - sum(taken.values())
            )
            taken[name] += max(extra, 0)
    return taken


def read_answers(path: Path) -> list[Answer]:
    return [Answer.model_validate_json(line) for line in path.read_text().splitlines() if line] if path.exists() else []


def label(
    pairs: list[Sampled],
    labellers: list[Labeller],
    answers: Path,
    budget_usd: float,
    workers: int = 9,
    progress: Callable[[str], None] | None = None,
) -> list[Answer]:
    """Ask every labeller about every pair it has not answered, until this run's known cost reaches the budget."""
    answers.parent.mkdir(parents=True, exist_ok=True)
    known = read_answers(answers)
    done = {(a.key, a.labeller) for a in known if a.label}
    spent = 0.0
    jobs = [(p, who) for p in pairs for who in labellers if (p.finding.candidate.key, who.name) not in done]

    def ask(job: tuple[Sampled, Labeller]) -> Answer:
        pair, who = job
        key = pair.finding.candidate.key
        for _ in range(3):
            try:
                text, usd = who.ask(prompt(pair.finding.candidate))
            except (httpx.HTTPError, subprocess.SubprocessError, OSError, KeyError, IndexError, ValueError):
                continue
            found = parse(text)
            if found:
                return Answer(
                    key=key,
                    labeller=who.name,
                    label=found["label"],
                    usd=usd,
                    **{k: str(found.get(k, "")) for k in ("variation", "owner", "concept")},
                )
        return Answer(key=key, labeller=who.name, label=None)

    with ThreadPoolExecutor(workers) as pool:
        for start in range(0, len(jobs), workers):
            if spent >= budget_usd:
                break
            batch = list(pool.map(ask, jobs[start : start + workers]))
            spent += sum(a.usd or 0.0 for a in batch)
            with answers.open("a") as file:
                file.writelines(a.model_dump_json() + "\n" for a in batch)
            known += batch
            if progress:
                progress(f"label {min(start + workers, len(jobs))}/{len(jobs)} answers, est. ${spent:.2f}")
    return known


def majority(answers: list[Answer]) -> Literal["duplicate", "separate", "borderline"] | None:
    """A strict majority of the usable answers; a split is borderline; no answer at all is None."""
    votes = [a.label == "CONSOLIDATE" for a in answers if a.label]
    if not votes:
        return None
    if votes.count(True) * 2 > len(votes):
        return "duplicate"
    return "separate" if votes.count(False) * 2 > len(votes) else "borderline"


def gold(pairs: list[Sampled], answers: list[Answer]) -> list[tuple[Sampled, GoldPair]]:
    """The labelled pairs as `dry-lint bench` gold, with drifted and owner by plurality of those who said duplicate."""
    by_key: dict[str, list[Answer]] = {}
    for answer in answers:
        if answer.label:
            by_key.setdefault(answer.key, []).append(answer)
    labelled = []
    for pair in pairs:
        given = by_key.get(pair.finding.candidate.key, [])
        verdict = majority(given)
        if verdict is None:
            continue
        agreeing = [a for a in given if a.label == "CONSOLIDATE"]
        owner = Counter({"A": "new", "B": "existing"}.get(a.owner, "shared") for a in agreeing).most_common(1)
        candidate = pair.finding.candidate
        labelled.append(
            (
                pair,
                GoldPair(
                    new=GoldFunction(id=candidate.new.qualname, code=candidate.new.code),
                    existing=GoldFunction(id=candidate.existing.qualname, code=candidate.existing.code),
                    label=verdict,
                    drifted=(sum(a.variation == "drifted" for a in agreeing) * 2 > len(agreeing))
                    if verdict == "duplicate"
                    else None,
                    owner=owner[0][0] if verdict == "duplicate" and owner else None,
                    weight=pair.weight,
                    stratum=pair.stratum,
                ),
            )
        )
    return labelled


OUTCOMES = ("real", "reported_real", "reported_false", "blocking_real", "blocking_false", "missed")


def outcomes(rows: list[tuple[Sampled, GoldPair]]) -> dict[str, float]:
    """Weighted totals over labelled pairs: what the replay proposed, and what its judging made of it."""
    found = dict.fromkeys(OUTCOMES, 0.0)
    for pair, labelled in rows:
        if labelled.label == "borderline":
            continue
        real, shown, blocks = labelled.label == "duplicate", pair.finding.reported, pair.finding.blocking
        for name, counts in (
            ("real", real),
            ("reported_real", real and shown),
            ("reported_false", shown and not real),
            ("blocking_real", real and blocks),
            ("blocking_false", blocks and not real),
            ("missed", real and not shown),
        ):
            found[name] += pair.weight * counts
    return found


def outcome_intervals(
    rows: list[tuple[Sampled, GoldPair]], resamples: int = 1000, seed: int = 7
) -> dict[str, tuple[float, float]]:
    """90% intervals for each outcome total, from a stratified bootstrap of the labelled pairs."""
    if not rows:
        return dict.fromkeys(OUTCOMES, (0.0, 0.0))
    draws = resampled(rows, lambda row: row[0].stratum, outcomes, resamples, seed)
    return {name: spread([draw[name] for draw in draws]) for name in OUTCOMES}


class Labels(BaseModel):
    """The labelling step of a replay: the gold set written, and what it says about the configured judging."""

    gold: str = Field(description="The gold file written.")
    labellers: list[str]
    sampled: int
    labelled: int = Field(description="Pairs with a majority label, borderline included.")
    unanimous: int
    duplicates: int
    borderline: int
    usd: float | None = Field(description="Known labelling cost so far; None when a labeller does not report it.")
    commits: int
    outcomes: dict[str, float] = Field(description="Weighted totals over the replay, see OUTCOMES.")
    intervals: dict[str, tuple[float, float]]
    judge: JudgeBench | None = Field(default=None, description="The configured judging on the labelled pairs.")

    def as_text(self) -> str:
        per = 100 / self.commits if self.commits else 0.0

        def number(value: float) -> str:
            return f"{value:.0f}" if value >= 10 else f"{value:.1f}"

        def show(name: str) -> str:
            low, high = self.intervals[name]
            value = self.outcomes[name] * per
            spread = "a full count" if low == high else f"{number(low * per)}-{number(high * per)}"
            return f"{number(value)} ({spread})"

        cost = "cost unknown" if self.usd is None else f"est. ${self.usd:.2f} for all their answers"
        lines = [
            "",
            f"labels: {self.labelled} of {self.sampled} sampled pairs labelled by {len(self.labellers)} "
            f"labellers ({self.unanimous} unanimous, {self.borderline} split); {self.duplicates} duplicates; "
            f"{cost}",
            f"  gold: {self.gold} (measure another preset with `dry-lint bench --gold` on it)",
            "per 100 commits, as labelled (90% intervals; bands labelled in full have none):",
            f"  real duplicates proposed  {show('real')}",
            f"  reported                  {show('reported_real')} real, {show('reported_false')} not",
            f"  blocking                  {show('blocking_real')} real, {show('blocking_false')} not",
            f"  real but not reported     {show('missed')}",
        ]
        if self.judge:
            j = self.judge
            lines.append(
                f"judging on the labelled pairs: precision {j.precision:.0%} "
                f"({j.precision_interval[0]:.0%}-{j.precision_interval[1]:.0%}), recall {j.recall:.0%} "
                f"({j.recall_interval[0]:.0%}-{j.recall_interval[1]:.0%}) when reported; precision "
                f"{j.fail_precision:.0%}, recall {j.fail_recall:.0%} when blocking; AUC "
                + ("n/a" if j.auc is None else f"{j.auc:.2f}")
            )
        return "\n".join(lines)


def summarise(
    pairs: list[Sampled],
    answers: list[Answer],
    labellers: list[str],
    settings: Settings,
    gold_path: Path,
    commits: int,
    judge: str | None,
) -> Labels:
    """Write the gold file and the numbers it gives."""
    rows = gold(pairs, answers)
    gold_path.parent.mkdir(parents=True, exist_ok=True)
    gold_path.write_text("".join(g.model_dump_json() + "\n" for _, g in rows))
    keys = {p.finding.candidate.key for p in pairs}
    asked = [a for a in answers if a.key in keys and a.label]
    by_key = Counter(a.key for a in asked)
    agreed = Counter((a.key, a.label == "CONSOLIDATE") for a in asked)
    judged = [(p, g) for p, g in rows if g.label != "borderline" and p.finding.verdict is not None]
    bench = (
        judge_bench([g for _, g in judged], [p.finding.verdict for p, _ in judged], settings, judge)
        if judge and judged
        else None
    )
    usd = None if any(a.usd is None for a in asked) else sum(a.usd or 0.0 for a in asked)
    return Labels(
        gold=str(gold_path),
        labellers=labellers,
        sampled=len(pairs),
        labelled=len(rows),
        unanimous=sum(1 for key, n in by_key.items() if max(agreed[(key, True)], agreed[(key, False)]) == n),
        duplicates=sum(g.label == "duplicate" for _, g in rows),
        borderline=sum(g.label == "borderline" for _, g in rows),
        usd=usd,
        commits=commits,
        outcomes=outcomes(rows),
        intervals=outcome_intervals(rows),
        judge=bench,
    )
