#!/usr/bin/env python3
"""
THE METRICS SCRIPT — protein-read identification benchmark v1.

Recomputes every threshold table of the benchmark paper from a verdict file:
both precision conventions, the frozen operating-point rule, coverage, and
(the kit's addition) recall and F1. The verdict semantics are the ones frozen
before any evaluation run, pinned here by self-tests over the same counts
the paper's tables were computed from.

THE FROZEN SEMANTICS (declared before any run):
  · THE VERDICT — a read is called when its containment for a candidate
    reaches threshold τ; below threshold: no-call — never an error, always
    counted.
  · THE GRID — eleven thresholds, 0.30 → 1.00, identical for every track.
  · THE OPERATING POINT — τ_fp0 = min{τ ∈ grid : FP(τ) = 0} over members
    AND decoys jointly (the highest-coverage zero-FP point). If no τ
    achieves it, the track's frontier is declared — never forced.
  · THE TWINS — a call that lands on a ≥0.999-identical sequence under a
    different accession is a correct identification of a real homolog, not
    an error: strict precision excludes twins from numerator AND
    denominator (isolating single-source discrimination); per-sequence
    precision credits them. Decoys are false positives under both.

THE VERDICT FILE (what submit.py writes, one row per read):
  id <TAB> acceso <TAB> contencion
  acceso     the top candidate's accession ("-" when no candidate exists)
  contencion the raw containment of that candidate (0.0 when none)
  The threshold grid is applied HERE, over the raw pairs — exactly as the
  frozen runs did.

USAGE
  python metrics.py --truth fixtures/truth.tsv \
      --miembros verdicts/qsi_v3.tsv --decoys verdicts/decoy_qsi_v3.tsv \
      [--titulo "qsi-v3 (hoy)"] [--prefijo nano_d1] [--extendido]
  python metrics.py --auto-test      # the frozen semantics, pinned

The default output is the frozen console format (the same blocks the paper
quotes): diff it against expected/tau-tables-corrected-run.txt. The
--extendido section (recall, F1) is the kit's addition, not the frozen
format.
"""

import sys
from pathlib import Path

AQUI = Path(__file__).parent

# ── THE FROZEN BENCHMARK CONSTANTS ──

TAU_GRILLA = [0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.70, 0.80, 0.90, 1.00]
GEMELO_UMBRAL = 0.999          # the twin threshold (frozen)


# ── THE EVALUATION LAYER (the frozen semantics) ──

def metricas(filas):
    """Per τ: TP, FP, twins, no-calls, called, both precisions.

    `filas`: list of (cont, llamado, verdad, decoy) — one per read.
    """
    salida = []
    for tau in TAU_GRILLA:
        tp = fp = twins = nc = 0
        for cont, llamado, verdad, decoy in filas:
            if cont < tau or not llamado:
                nc += 1                      # the no-call (coverage measures it)
                continue
            if decoy:
                fp += 1                      # a called decoy: FP under both
            elif llamado == verdad:
                tp += 1                      # the exact hit
            elif cont >= GEMELO_UMBRAL:
                twins += 1                   # the twin: correct per-sequence
            else:
                fp += 1                      # the genuine mismatch
        llamados = len(filas) - nc
        # strict precision without strict calls (all twins) is the vacuous
        # 1.0 — the twins column explains it.
        prec_e = tp / (tp + fp) if (tp + fp) > 0 else (1.0 if llamados > 0 else 0.0)
        prec_s = (tp + twins) / (tp + twins + fp) if llamados > 0 else 0.0
        salida.append({"tau": tau, "tp": tp, "fp": fp, "twins": twins,
                       "nc": nc, "llamados": llamados, "prec_e": prec_e, "prec_s": prec_s})
    return salida


def punto_fp0(miembros, decoys):
    """THE FROZEN RULE: min{τ : FP(τ)=0} over members + decoys jointly.

    The coverage returned is the MEMBERS' at that τ (the decoys are the FP
    probe: at a zero-FP point they are all no-calls). None = the honest
    frontier (no τ achieves zero — never forced).
    """
    unidos = metricas(miembros + decoys)
    tau = next((f["tau"] for f in unidos if f["fp"] == 0), None)
    if tau is None:
        return None
    fila = next(f for f in metricas(miembros) if f["tau"] == tau)
    return (tau, fila["llamados"])


def punto_fp0_bloque(filas):
    """The block-only zero-FP point (the informative reading of a decoy
    block, or the members-only point a track must NOT be headline'd on)."""
    f = next((f for f in metricas(filas) if f["fp"] == 0), None)
    return None if f is None else (f["tau"], f["llamados"])


def tabla_tau(filas):
    """The frozen console format — the exact format of the paper's blocks."""
    out = "  τ      TP    FP   gemelos  no-call  llamados  prec_est  prec_seq\n"
    for f in metricas(filas):
        out += (f"  {f['tau']:.2f}  {f['tp']:5d} {f['fp']:5d}  {f['twins']:6d}"
                f"  {f['nc']:7d}  {f['llamados']:8d}  {f['prec_e']:8.4f}"
                f"  {f['prec_s']:8.4f}\n")
    return out


def bloque(titulo, filas, decoys=None, extendido=False):
    """A full console block: header + τ table + the operating-point line(s)."""
    out = f"── {titulo}: {len(filas)} reads ──\n"
    out += tabla_tau(filas)
    if decoys is not None:
        p = punto_fp0(filas, decoys)
        if p is not None:
            tau, llamados = p
            out += (f"  ⟹ EL PUNTO FP=0 (miembros+decoys — la regla congelada): "
                    f"τ={tau:.2f} · la cobertura {llamados}/{len(filas)} = "
                    f"{llamados / max(len(filas), 1) * 100:.1f}%\n")
        else:
            out += ("  ⟹ SIN punto FP=0 sobre miembros+decoys "
                    "(la frontera honesta del track — la regla congelada)")
            pb = punto_fp0_bloque(filas)
            if pb is not None:
                tau, llamados = pb
                out += (f" — el punto SOLO-MIEMBROS τ={tau:.2f} ({llamados}/"
                        f"{len(filas)}) NO cumple la regla: los decoys infiltran la grilla")
            out += "\n"
    else:
        p = punto_fp0_bloque(filas)
        if p is not None:
            out += (f"  ⟹ el punto del bloque decoy: τ={p[0]:.2f} "
                    "(el control — el headline vive en la unión miembros+decoys)\n")
        else:
            out += "  ⟹ el bloque decoy SIN punto FP=0 — el track completo NO tiene punto\n"
    if extendido:
        out += seccion_extendida(filas)
    return out


def seccion_extendida(filas):
    """The kit's addition: recall and F1 per τ (not part of the frozen format)."""
    out = ("  ── extendido (recall/F1 — adición del kit, NO el formato congelado) ──\n"
           "  τ      recall_est  recall_seq  F1_est   F1_seq\n")
    n = len(filas)
    for f in metricas(filas):
        r_e = f["tp"] / n if n else 0.0
        r_s = (f["tp"] + f["twins"]) / n if n else 0.0
        f1_e = (2 * f["prec_e"] * r_e / (f["prec_e"] + r_e)) if (f["prec_e"] + r_e) > 0 else 0.0
        f1_s = (2 * f["prec_s"] * r_s / (f["prec_s"] + r_s)) if (f["prec_s"] + r_s) > 0 else 0.0
        out += (f"  {f['tau']:.2f}  {r_e:10.4f}  {r_s:10.4f}  {f1_e:7.4f}  {f1_s:7.4f}\n")
    return out


# ── INPUT: the truth table and the verdict files ──

def lee_truth(ruta: Path):
    """id -> (accession, is_decoy). Fails closed on malformed rows."""
    verdad = {}
    for num, linea in enumerate(ruta.read_text(encoding="utf-8").splitlines()[1:], start=2):
        if not linea.strip():
            continue
        p = linea.split("\t")
        if len(p) < 3:
            raise SystemExit(f"truth.tsv línea {num}: malformed — {linea!r}")
        verdad[p[0]] = (p[2], p[1] == "1")
    return verdad


def lee_veredictos(ruta: Path, verdad, prefijo=None):
    """The verdict file -> filas. A verdict id missing from truth.tsv is a
    misaligned input: rejected out loud (never silently absorbed as a member
    with empty truth)."""
    filas = []
    for num, linea in enumerate(ruta.read_text(encoding="utf-8").splitlines(), start=1):
        if not linea.strip() or linea.startswith("id\t"):
            continue
        p = linea.split("\t")
        if len(p) < 3:
            raise SystemExit(f"{ruta.name} línea {num}: malformed — {linea!r}")
        rid, acceso, cont = p[0], p[1].strip(), p[2].strip()
        if prefijo and not rid.startswith(prefijo):
            continue
        if rid not in verdad:
            raise SystemExit(f"el read '{rid}' NO está en truth.tsv — el input está desalineado")
        acc_verdad, decoy = verdad[rid]
        cont = float(cont) if cont not in ("-", "") else 0.0
        llamado = "" if acceso in ("-", "") else acceso
        filas.append((cont, llamado, acc_verdad, decoy))
    return filas


# ── THE v4 MODE (the paper v4's tables: the calibrated gate, out-of-fold) ──
#
# The corpus of record: 983 members + 979 decoys. The gate is calibrated on
# one half of the corpus (by record parity) and judged on the other: the
# threshold is the one that maximizes correct band calls subject to at most
# three decoy calls, and the lowest such threshold when several qualify.
# Each read is judged once, by the threshold calibrated on the half that did
# not contain it. The pooled record is the concatenation.

BANDA = ("[0.6,0.7)", "[0.7,0.8)")
PRESUPUESTO = 3


def _v4_carga():
    verdad = lee_truth(AQUI / "fixtures" / "truth.tsv")
    ident = {}
    for linea in (AQUI / "fixtures" / "identidad.tsv").read_text(encoding="utf-8").splitlines():
        if not linea.strip() or linea.startswith("#") or linea.startswith("read_id"):
            continue
        rid, b = linea.split("\t")
        ident[rid] = b
    filas = []
    for linea in (AQUI / "expected" / "v4-verdicts.tsv").read_text(encoding="utf-8").splitlines():
        if not linea.strip() or linea.startswith("#"):
            continue
        rid, acceso, cont = linea.split("\t")
        if rid not in verdad:
            raise SystemExit(f"el read '{rid}' NO está en truth.tsv — el input está desalineado")
        acc_verdad, decoy = verdad[rid]
        filas.append({"id": rid, "cont": float(cont),
                      "llamado": "" if acceso in ("-", "") else acceso,
                      "verdad": acc_verdad, "decoy": decoy, "bin": ident.get(rid, "")})
    return filas


def _v4_par(f):
    return int(f["id"].rsplit("_", 1)[-1]) % 2 == 0


def _v4_calibra(filas, es_cal):
    banda = [f for f in filas if not f["decoy"] and f["bin"] in BANDA and es_cal(f)]
    dec = [f for f in filas if f["decoy"] and es_cal(f) and f["llamado"]]
    valores = sorted({f["cont"] for f in banda if f["llamado"]})
    mejor = None
    for tau in valores:
        c = sum(1 for f in banda if f["llamado"] and f["llamado"] == f["verdad"] and f["cont"] >= tau)
        d = sum(1 for f in dec if f["cont"] >= tau)
        if d <= PRESUPUESTO and (mejor is None or c > mejor[0]):
            mejor = (c, tau)
    if mejor is None:
        return None
    for tau in valores:
        c = sum(1 for f in banda if f["llamado"] and f["llamado"] == f["verdad"] and f["cont"] >= tau)
        d = sum(1 for f in dec if f["cont"] >= tau)
        if d <= PRESUPUESTO and c == mejor[0]:
            return tau
    return mejor[1]


def _v4_pasa(f, tau):
    return bool(f["llamado"]) and f["cont"] >= tau


def v4():
    """The band table of the paper v4 §4.1, recomputed from the shipped
    verdicts — the calibrated gate, out-of-fold."""
    filas = _v4_carga()
    tau_par = _v4_calibra(filas, lambda f: not _v4_par(f))   # TRAIN=impar → TEST=par
    tau_impar = _v4_calibra(filas, _v4_par)                  # TRAIN=par → TEST=impar
    if tau_par is None or tau_impar is None:
        raise SystemExit("sin τ admisible en un pliegue — el corpus no es el de registro")

    def tau_de(f):
        return tau_par if _v4_par(f) else tau_impar

    out = ("# the band table of the paper v4 §4.1 — the calibrated gate, out-of-fold\n"
           "band\treads\tcalls\tcorrect\tcoverage_pct\tprecision_pct\n")
    for b in ("[0.4,0.5)", "[0.5,0.6)", "[0.6,0.7)", "[0.7,0.8)", "[0.8,0.9)", "[0.9,1.0]"):
        sub = [f for f in filas if not f["decoy"] and f["bin"] == b]
        ll = [f for f in sub if _v4_pasa(f, tau_de(f))]
        cc = [f for f in ll if f["llamado"] == f["verdad"]]
        out += (f"{b}\t{len(sub)}\t{len(ll)}\t{len(cc)}\t"
                f"{100 * len(cc) / max(1, len(sub)):.1f}\t{100 * len(cc) / max(1, len(ll)):.1f}\n")
    banda = [f for f in filas if not f["decoy"] and f["bin"] in BANDA]
    bll = [f for f in banda if _v4_pasa(f, tau_de(f))]
    bcc = [f for f in bll if f["llamado"] == f["verdad"]]
    out += (f"pooled [0.6,0.8)\t{len(banda)}\t{len(bll)}\t{len(bcc)}\t"
            f"{100 * len(bcc) / max(1, len(banda)):.1f}\t{100 * len(bcc) / max(1, len(bll)):.1f}\n")
    dc = [f for f in filas if f["decoy"] and _v4_pasa(f, tau_de(f))]
    out += f"# the decoy block at the same out-of-fold points: {len(dc)} calls in {sum(1 for f in filas if f['decoy'])}\n"
    out += (f"# the pooled precision with the decoys in the denominator: "
            f"{len(bcc)}/{len(bll) + len(dc)} = {100 * len(bcc) / max(1, len(bll) + len(dc)):.1f}%\n")
    out += (f"# the folds: the held-out odd half τ={tau_impar:.6f} · the held-out even half "
            f"τ={tau_par:.6f} (each calibrated on the other half)\n")
    sys.stdout.write(out)


# ── THE SELF-TESTS (the frozen semantics, pinned) ──

def _test_la_semantica_del_veredicto():
    filas = [
        (0.90, "P1", "P1", False),   # the clean TP
        (1.00, "P2", "P1", False),   # THE TWIN: cont 1.0, other accession
        (0.70, "P9", "P1", False),   # the real FP (cont below the twin bar)
        (0.80, "P3", "P3", True),    # the called DECOY: FP
        (0.10, "",   "P4", False),   # the no-call (no candidate)
    ]
    m = metricas(filas)
    f30 = m[0]
    assert (f30["tp"], f30["fp"], f30["twins"], f30["nc"], f30["llamados"]) == (1, 2, 1, 1, 4)
    assert abs(f30["prec_e"] - 1 / 3) < 1e-9
    assert abs(f30["prec_s"] - 0.5) < 1e-9
    # τ=0.90: the twin (1.0) stays · the real FP (0.70) and the decoy (0.80)
    # leave → FP=0, coverage 2/5 — THE TWIN IS NOT AN FP.
    f90 = next(f for f in m if f["tau"] == 0.90)
    assert (f90["fp"], f90["llamados"]) == (0, 2), "el gemelo NO es FP"


def _test_el_umbral_del_gemelo():
    assert abs(GEMELO_UMBRAL - 0.999) < 1e-12
    gemelo = [
        (0.999, "P2", "P1", False),   # exactly at the bar: a twin
        (0.998, "P3", "P1", False),   # below the bar: a strict FP
    ]
    f = next(x for x in metricas(gemelo) if x["tau"] == 0.90)
    assert (f["tp"], f["fp"], f["twins"]) == (0, 1, 1)
    assert abs(f["prec_s"] - 0.5) < 1e-9


def _test_la_regla_congelada_es_la_union():
    # (a) members bind: the union does not move the point.
    miembros = [(1.00, "P1", "P1", False), (0.90, "P9", "P2", False)]
    decoys = [(0.60, "X1", "X1", True)]
    tau, llamados = punto_fp0(miembros, decoys)
    assert tau == 1.00 and llamados == 1
    # (b) DECOYS bind: the union RAISES the point 0.35 → 0.40 (the case the
    # first-pass headline got wrong — the correction of the paper's §4.1).
    miembros5 = [(0.30, "P9", "P2", False)]
    decoys5 = [(0.35, "X1", "X1", True)]
    tau, _ = punto_fp0(miembros5, decoys5)
    assert tau == 0.40, "los DECOYS atan: 0.35 → 0.40"
    assert punto_fp0_bloque(miembros5)[0] == 0.35   # the members-only divergence
    # (c) decoys infiltrate the whole grid: NO point — the honest frontier.
    miembros_f = [(1.00, "P1", "P1", False), (0.90, "P9", "P2", False)]
    decoys_f = [(1.00, "X1", "X1", True)]
    assert punto_fp0(miembros_f, decoys_f) is None
    assert punto_fp0_bloque(miembros_f)[0] == 1.00  # the false members-only headline
    assert len(TAU_GRILLA) == 11


def _test_el_formato_de_la_tabla():
    filas = [(1.00, "P1", "P1", False), (0.10, "", "P2", False)]
    t = tabla_tau(filas)
    assert t.startswith("  τ      TP    FP   gemelos  no-call  llamados  prec_est  prec_seq\n")
    assert any(l.startswith("  1.00      1     0") for l in t.splitlines())
    assert len(t.splitlines()) == 12, "la cabecera + las 11 τ de la grilla"


def _test_la_fila_congelada_del_working_point():
    """The frozen row of the paper's §4.3, recomputed from the same counts:
    112 TP · 76 FP · 11 twins · 784 no-calls at τ=0.30 → the exact printed row."""
    filas = (
        [(0.30, f"V{i}", f"V{i}", False) for i in range(112)] +      # TP
        [(0.30, f"W{i}", f"V{i}", False) for i in range(76)] +       # genuine FP
        [(1.00, f"T{i}", f"V{i}", False) for i in range(11)] +       # the twins
        [(0.10, "",     f"V{i}", False) for i in range(784)]         # no-calls
    )
    fila = f"  0.30    112    76      11      784       199    0.5957    0.6181"
    assert fila in tabla_tau(filas).splitlines(), "la fila τ=0.30 del working point"


def auto_test():
    _test_la_semantica_del_veredicto()
    _test_el_umbral_del_gemelo()
    _test_la_regla_congelada_es_la_union()
    _test_el_formato_de_la_tabla()
    _test_la_fila_congelada_del_working_point()
    print("LOS AUTO-TESTS: 5/5 — la semántica del veredicto está pineada "
          "(el gemelo NO es FP · el decoy ES FP en ambas · la regla del punto es la UNIÓN "
          "miembros+decoys · la grilla son 11 τ · el formato es el congelado).")


# ── CLI ──

def main():
    # LF en todas las plataformas: el diff de la verificación de determinismo
    # debe ser limpio contra expected/ (normalizado a LF) en cualquier SO.
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(newline="\n")
    args = sys.argv[1:]
    if "--auto-test" in args:
        auto_test()
        return
    if "--v4" in args:
        v4()
        return
    def opt(nombre, defecto=None):
        if nombre in args:
            return args[args.index(nombre) + 1]
        return defecto
    truth = Path(opt("--truth", AQUI / "fixtures" / "truth.tsv"))
    miembros_ruta = opt("--miembros")
    decoys_ruta = opt("--decoys")
    if not miembros_ruta:
        raise SystemExit(__doc__)
    verdad = lee_truth(truth)
    filas = lee_veredictos(Path(miembros_ruta), verdad, prefijo=opt("--prefijo"))
    decoys = lee_veredictos(Path(decoys_ruta), verdad) if decoys_ruta else None
    titulo = opt("--titulo") or Path(miembros_ruta).stem
    sys.stdout.write(bloque(titulo, filas, decoys, extendido="--extendido" in args))


if __name__ == "__main__":
    main()
