#!/usr/bin/env python3
"""LA MATRIZ DE CONFUSIÓN del genotipado por cobertura — el formato de los rivales.

Lee el TSV de las llamadas congeladas (las columnas p3) y deriva el call
u>=3 con la semántica EXACTA de call_cobertura_v2 (CON el refinamiento
`ent`: en la celda HET, HOM-ALT si 3·r_pres <= a_pres — los pisos del
gate y el split están declarados en el paper, Section 3.6):
el homocigota exige la clase opuesta testeada (tot>0) y ausente (o al
nivel <= 1/3 del alt — la contaminación de parálogo).

Uso: python e10c_confusion.py <e10c_calls.tsv> [umbral=3]
Salida: la matriz call×truth + call-rate + concordancias + F1 (dos modos
de NO-CALL: excluido de la precisión / contado como error).
"""
import csv
import sys
from collections import Counter

def call_v2(a_pres, a_tot, r_pres, r_tot, u):
    alt_ok = a_pres >= u
    ref_ok = r_pres >= u
    if a_tot == 0 or r_tot == 0:
        return "NO-CALL"
    if alt_ok and not ref_ok: return "HOM-ALT"
    if alt_ok and ref_ok and 3 * r_pres <= a_pres: return "HOM-ALT"  # refinamiento ent
    if alt_ok and ref_ok:     return "HET"
    if ref_ok and not alt_ok: return "HOM-REF"
    return "NO-CALL"

def main(path, u=3):
    matriz = Counter()          # (call, truth) -> n
    n = 0
    with open(path, encoding="utf-8") as f:
        rd = csv.reader(f, delimiter="\t")
        header = next(rd)
        i_a3 = header.index("alt_p3"); i_r3 = header.index("ref_p3")
        i_at = header.index("alt_tot"); i_rt = header.index("ref_tot")
        i_b = header.index("bench")
        for row in rd:
            if not row: continue
            truth = row[i_b]
            call = call_v2(int(row[i_a3]), int(row[i_at]), int(row[i_r3]), int(row[i_rt]), u)
            matriz[(call, truth)] += 1
            n += 1
    # LA MATRIZ
    calls = ["HOM-ALT", "HET", "HOM-REF", "NO-CALL"]
    truths = ["HOM-ALT", "HET"]
    print(f"=== LA MATRIZ CALL×TRUTH u≥{u} (N={n:,}) ===")
    print("call\\truth\t" + "\t".join(truths) + "\ttotal")
    for c in calls:
        fila = [matriz[(c, t)] for t in truths]
        print(f"{c}\t" + "\t".join(f"{v:,}" for v in fila) + f"\t{sum(fila):,}")
    print("truth_total\t" + "\t".join(f"{sum(matriz[(c, t)] for c in calls):,}" for t in truths))
    hom_ok = matriz[("HOM-ALT", "HOM-ALT")]
    het_ok = matriz[("HET", "HET")]
    conc = hom_ok + het_ok
    called = n - matriz[("NO-CALL", "HOM-ALT")] - matriz[("NO-CALL", "HET")]
    disc = called - conc
    # LAS MÉTRICAS (el formato de los rivales)
    call_rate = called / n
    honesta = conc / called                      # la precisión (no-call excluido)
    total = conc / n                             # el recall (no-call = error)
    f1 = 2 * honesta * total / (honesta + total)
    f1_strict = 2 * total / (1 + total)          # la precisión estricta = total
    print(f"\n=== LAS MÉTRICAS u≥{u} ===")
    print(f"call_rate            : {call_rate:.4f}  ({called:,}/{n:,})")
    print(f"concordancia_called  : {honesta:.4f}  ({conc:,}/{called:,})  [la 'HONESTA' del servidor]")
    print(f"concordancia_total   : {total:.4f}  ({conc:,}/{n:,})")
    print(f"precision (nc excl)  : {honesta:.4f}")
    print(f"recall    (nc=error) : {total:.4f}")
    print(f"F1 (nc excl de P)    : {f1:.4f}")
    print(f"F1 (nc=error en P)   : {f1_strict:.4f}")
    print(f"DISC (llamado mal)   : {disc:,}")
    # el contraste por clase de verdad
    for t in truths:
        tot_t = sum(matriz[(c, t)] for c in calls)
        ok = matriz[(("HOM-ALT" if t == "HOM-ALT" else "HET"), t)]
        print(f"truth {t:7}: sensibilidad {ok/tot_t:.4f} ({ok:,}/{tot_t:,})")

if __name__ == "__main__":
    main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 3)
