"""One offline production comparison; immutable caches supply exact backgrounds/source.

No experiment implementation imports and no provider construction or execution.
Unavailable source rows remain token-only IDF competitors, explicitly ineligible for blocks.
"""

import gzip
import hashlib
import json
import time
from collections import Counter, defaultdict
from pathlib import Path
from types import SimpleNamespace

from dry_lint.bench_background import BenchBackground
from dry_lint.costs import Ledger
from dry_lint.detector import Detector, why_skipped
from dry_lint.extractors import PythonExtractor
from dry_lint.functions import behaviour_tokens
from dry_lint.models import Candidate, Function, evidence
from dry_lint.operation_blocks import OperationBlocksComparer
from dry_lint.settings import Settings

LAB = Path(__file__).resolve().parents[1]
OUT = Path(__file__).resolve().parent
OLD = LAB / "full-corpus-followup/span-v2-migration"
REQUESTS = OUT / "review-requests-v1"


def sha(raw):
    return hashlib.sha256(raw).hexdigest()


def read(path):
    with path.open() as handle:
        for line in handle:
            if line.strip():
                yield json.loads(line)


def sealed(path, value, lines=False):
    raw = ("".join(json.dumps(row, sort_keys=True) + "\n" for row in value)
           if lines else json.dumps(value, indent=2, sort_keys=True) + "\n").encode()
    if path.exists():
        assert path.read_bytes() == raw, f"Frozen output differs: {path}; use another version"
    else:
        path.write_bytes(raw)


def block_signature(block):
    return (block.line, block.end_line, block.kind, dict(Counter(block.tokens)), sorted(block.operations), sorted(block.calls))


def old_block_signature(block):
    return (block["start_line"], block["end_line"], block["kind"], block["counts"], block["ops"], block["calls"])


def main():
    summary = json.loads((OLD / "paired-summary.json").read_text())
    special = {pair for group in summary["summaries"]
               if group.get("cohort_id") == "ALL_COHORTS_SEPARATE_FITS" and group.get("label") in {"duplicate", "separate"}
               for pair in group["profiles"]["default_plus_current20"]["funded"]["gained_pairs"]}
    all_rows = list(read(OLD / "paired-rows.jsonl"))
    cases = {row["pair_id"]: row for row in all_rows if row.get("pair_id") in special}
    assert len(cases) == 5
    cohorts = {row["cohort_id"] for row in cases.values()}
    coverage = json.loads((OLD / "coverage.json").read_text())
    bindings = {row["cohort"]["cohort_id"]: row["cohort"] for row in coverage["per_cohort"]}
    batch_sidecars = list(read(LAB / "full-corpus-followup/review-batches/v1/review-private-sidecar.jsonl"))
    prior_packets = list(read(LAB / "novel-review-queue.jsonl"))
    prior_observations = list(read(LAB / "central-observation-receipts.jsonl"))
    requested_judging = next(read(LAB / "full-corpus-followup/review-batches/v1/novel-review-queue.jsonl"))["requested_judging"]
    settings = Settings(budget={"usd": 0.04})
    judge = SimpleNamespace(name="anthropic", model="claude-sonnet-5-5", prompt_policy="concept")
    outputs, query_checks, packets, private, blind = [], [], [], [], []
    old_inputs = {}
    for cohort_id in sorted(cohorts):
        started = time.monotonic()
        binding = bindings[cohort_id]
        cohort_dir = OLD / "cohorts" / cohort_id
        cache_path = cohort_dir / "candidate-index.json.gz"
        cache_raw = cache_path.read_bytes()
        cache = json.loads(gzip.decompress(cache_raw))
        raw = Path(binding["background_path"]).read_bytes()
        assert sha(raw) == binding["background_sha256"] == cache["binding"]["background_sha256"]
        bg = BenchBackground.decode(raw)
        native = {int(k): Function.model_validate(v) for k, v in cache["functions"].items()}
        functions, token_mismatches = [], 0
        for position, doc in enumerate(bg.documents):
            if position in native:
                function = native[position]
                assert sha(function.code.encode()) == doc.source_sha256
                token_mismatches += Counter(behaviour_tokens(function)) != doc.counts
            else:
                path, _, qualified = doc.id.partition("::")
                owner, _, name = qualified.rpartition(".")
                function = Function(path=path, name=name or qualified, owner=owner or None,
                                    line=0, end_line=0, code="")
            function.tokens = doc.tokens()
            assert function.qualname == doc.id
            functions.append(function)
        comparer = OperationBlocksComparer()
        detector = Detector(functions, settings, comparer, [PythonExtractor()])  # one real index fit
        positions = {id(f): i for i, f in enumerate(functions)}
        blocks_by_parent = defaultdict(list)
        for block in cache["blocks"]:
            blocks_by_parent[block["parent"]].append(block)
        block_discrepancies = []
        for i, blocks in enumerate(comparer._parents):
            if [block_signature(b) for b in blocks] != [old_block_signature(b) for b in blocks_by_parent[i]]:
                block_discrepancies.append(i)
        selected = {d["query"] for row in all_rows if row.get("cohort_id") == cohort_id
                    for d in row.get("directions", []) if d.get("status") == "evaluated"}
        selected |= {s["query"] for s in batch_sidecars if s["cohort_id"] == cohort_id}
        queries = {q["query"]: q for q in read(cohort_dir / "per-query.jsonl") if q["query"] in selected}
        max_error, compared = 0.0, 0
        local_checks = []
        for qi, old in queries.items():
            query = functions[qi]
            assert qi in native and query.line >= 1 and query.end_line >= query.line
            pool = comparer._pool(query, comparer._query_blocks(query))
            expected = [(b["target"], b["score"]) for b in old["block_candidates"]
                        if b["block_floor_pass"] and b["full_floor_pass"] and not b["filter"]]
            actual = [(positions[id(f)], score) for f, score in comparer.neighbours(
                query, 64, allowed=lambda f: not why_skipped(query, f, settings))]
            exact_ids = [i for i, _ in expected] == [i for i, _ in actual]
            errors = [abs(a[1] - b[1]) for a, b in zip(expected, actual, strict=False) if a[0] == b[0]]
            max_error = max([max_error, *errors])
            compared += len(errors)
            profiles = {}
            for name, policy in old.get("profiles", {}).items():
                baseline = policy["baseline"]
                found = comparer.neighbours(query, 1, allowed=lambda f: (
                    positions[id(f)] not in baseline and not why_skipped(query, f, settings)
                    and (name != "default3" or f.path != query.path)))
                target = positions[id(found[0][0])] if found else None
                expected_target = policy["extra"]["target"] if policy["extra"] else None
                before = [Candidate(new=query, existing=functions[t], similarity=0,
                                    comparer="tfidf:2", lane="exploration") for t in baseline]
                after = before + ([detector.pair(query, found[0][0], found[0][1])] if found else [])
                funded_before = [baseline[i] for i in Ledger(settings).select(judge, before)]
                augmented = baseline + ([target] if target is not None else [])
                funded_after = [augmented[i] for i in Ledger(settings).select(judge, after)]
                profiles[name] = dict(old_extra=expected_target, production_extra=target,
                    exact_extra=target == expected_target,
                    baseline_funding_matches=funded_before == policy["baseline_funded"],
                    augmented_funding_matches=funded_after == policy["augmented_funded"])
            check = dict(cohort_id=cohort_id, query=qi, exact_pool=pool == old["block_work"]["pool"],
                         exact_candidate_ids=exact_ids, maximum_score_error=max(errors, default=0), profiles=profiles)
            query_checks.append(check)
            local_checks.append(check)
        for pair_id, row in cases.items():
            if row["cohort_id"] != cohort_id:
                continue
            gained = next(d for d in row["directions"] if d["default_plus_current20"]["variant_funded"]
                          and not d["default_plus_current20"]["baseline_funded"])
            qi, ti = gained["query"], gained["target"]
            query, target = functions[qi], functions[ti]
            score = comparer.similarity(query, target)
            candidate = detector.pair(query, target, score).model_copy(update={"lane": "exploration"})
            assert candidate.new.code == query.code and candidate.existing.code == target.code
            proofs = []
            for function in (query, target):
                source = cache["sources"][function.path]
                proofs.append(dict(source_id=function.qualname, path=function.path, line=function.line,
                    end_line=function.end_line, body_sha256=sha(function.code.encode()),
                    file_sha256=source["sha256"], git_blob_sha1=source["git_blob"], snapshot=source["snapshot"],
                    blob_url=f"https://github.com/{bg.repository}/blob/{bg.revision}/{function.path}#L{function.line}-L{function.end_line}"))
            packet_id = "OBP-" + pair_id[:16]
            packet = dict(format="dry-lint/lab-review-packet", schema=1, id=packet_id, status="unknown",
                truth="Source decision belongs to root; provider agreement is not gold.",
                repository=bg.repository, revision=bg.revision,
                background_proof=dict(path=binding["background_path"], sha256=binding["background_sha256"]),
                candidate=candidate.model_dump(mode="json"), evidence=evidence(candidate), source_proofs=proofs,
                requested_judging=requested_judging)
            packets.append(packet)
            body_pair = sorted(proof["body_sha256"] for proof in proofs)
            prior = [p for p in prior_packets if p["repository"] == bg.repository and p["revision"] == bg.revision
                     and sorted(sha(p["candidate"][side]["code"].encode()) for side in ("new", "existing")) == body_pair]
            prior_ids = {p["id"] for p in prior}
            observations = [{k: o.get(k) for k in ("id", "kind", "model", "version", "verdict", "error", "canonical_request_key")}
                            for o in prior_observations if o["id"] in prior_ids]
            private.append(dict(id=packet_id, pair_id=pair_id, row_id=row.get("row_id"), cohort_id=cohort_id,
                accepted_label=row["label"], role="funded_gain" if row["label"] == "duplicate" else "negative_exposure",
                query=qi, target=ti, original_frozen_directions=row["directions"], production_score=score,
                frozen_block_score=gained["block_score"], production_comparer="operation-blocks:1",
                original_candidate_comparer="tfidf:2", native_source_preserved=True,
                prior_same_body_packets=sorted(prior_ids), prior_observations=observations,
                exact_new_request_cache_status="unknown; root must canonical-match rendered input and options",
                missing_request_kinds=[request["kind"] for request in requested_judging], worker_provider_calls=0))
            blind.append(dict(id=packet_id, repository=bg.repository, revision=bg.revision,
                              source_proofs=proofs, functions=[candidate.new.model_dump(mode="json"),
                                                            candidate.existing.model_dump(mode="json")]))
        old_inputs[str(cache_path)] = sha(cache_raw)
        old_inputs[str(cohort_dir / "per-query.jsonl")] = sha((cohort_dir / "per-query.jsonl").read_bytes())
        outputs.append(dict(cohort_id=cohort_id, repository=bg.repository, revision=bg.revision,
            background_sha256=binding["background_sha256"], full_background_documents=len(functions),
            native_functions=len(native), missing_or_ambiguous_token_only_competitors=len(functions)-len(native),
            blocks=sum(len(b) for b in comparer._parents), block_discrepancy_parents=block_discrepancies,
            current_tokenizer_mismatches=token_mismatches, selected_queries=len(queries), compared_candidate_scores=compared,
            maximum_score_error=max_error, elapsed_seconds=time.monotonic()-started))
        print(json.dumps(outputs[-1], sort_keys=True), flush=True)
    sealed(OUT / "comparison-queries.jsonl", query_checks, lines=True)
    sealed(REQUESTS / "gains-and-negatives.jsonl", packets, lines=True)
    sealed(REQUESTS / "gains-and-negatives-private.jsonl", private, lines=True)
    sealed(REQUESTS / "gains-and-negatives-blind.jsonl", blind, lines=True)
    failures = [q for q in query_checks if not q["exact_pool"] or not q["exact_candidate_ids"]
                or q["maximum_score_error"] > 1e-12 or any(not p["exact_extra"] or not p["baseline_funding_matches"]
                    or not p["augmented_funding_matches"] for p in q["profiles"].values())]
    result = dict(status="pass" if not failures and all(not c["block_discrepancy_parents"] for c in outputs) else "discrepancies",
        implementation_sha256=sha((OUT.parents[1] / "src/dry_lint/operation_blocks.py").read_bytes()),
        cohorts=outputs, query_checks=len(query_checks), discrepant_queries=failures,
        tested_special_pairs={label:sum(c["label"] == label for c in cases.values()) for label in ("duplicate","separate")},
        old_input_sha256=old_inputs, provider_calls=0,
        production_score_identity_change="intentional: operation-blocks:1 region cosine instead of unrelated tfidf:2 raw cosine",
        baseline_policy="original cached baseline3 then TF-IDF .35 raw20 order/caps; unchanged .04 synthetic concept ledger",
        geography="default3 comparison explicitly excludes same-file extras; documented production profile is default_plus_current20",
        scope="all native block extraction in the two special-case backgrounds; all saved evaluated labelled queries plus batch queries in those backgrounds",
        remaining_source_exceptions="token-only missing/ambiguous rows retain IDF competition, cannot become native block candidates")
    # Timings are observational; this comparison is run once and outputs are sealed.
    sealed(OUT / "comparison.json", result)
    print(json.dumps({k:result[k] for k in ("status","query_checks","tested_special_pairs","provider_calls")}), flush=True)


if __name__ == "__main__":
    main()
