#!/usr/bin/env python3
"""
THE TRUTH-SET SAMPLING DRIVER — protein-read identification benchmark v2.

This script documents and re-derives the SAMPLING DESIGN of the benchmark's
truth set: how the 983 member sources and the 983 target-decoy negatives were
drawn, deterministically, from the public Swiss-Prot release. It is the
truth-set generation script of the simulator, stripped of the noise-model
internals: the read noise models are NOT redistributed — the nanopore and
fluorosequencing models belong to their published papers (Motone et al.,
Nature 2024; Smith et al., PLOS Comput Biol 2024) and the recognizer-class
model is the benchmark paper's declared approximation (its two constants are
printed in the paper's Section 3.3). The frozen, checksummed reads shipped in
fixtures/ are the artifacts of record.

THE DESIGN IT RE-DERIVES (frozen, master seed 0x20261022):
  1. SAMPLING — a uniform stride over the library's release order: every
     575,748 // 1000 = 575-th protein is a candidate.
  2. THE CLEAN WINDOW — for each candidate, up to 12 attempts to draw a
     window of 25-40 residues (canonical amino acids only, protein at least
     45 residues long); the first clean window wins, candidates without one
     are skipped. 983 sources result.
  3. THE DECOYS — the same windows, sequence-inverted, at every consensus
     depth (1x/5x/30x) plus the recognizer-class block (the target-decoy
     construction of mass spectrometry, carried to read level: identical
     composition, destroyed identity). THE EXCLUSION (pre-registered
     2026-11-19): a source whose window is dominated by one recognizer class
     (dominant >= 0.70 in the seven-class alphabet) emits NO decoy — the
     inversion of a near-constant class string is the same string, not a
     negative. Four of the 983 sources are excluded; the corpus of record is
     983 members + 979 decoys.
  4. THE PER-READ SEEDS — every emitted read carries its frozen generator
     seed, derived from the master seed, the candidate's library index and
     the source's ordinal: the reproducibility unit of the truth set.

THE RANDOMNESS — splitmix64, the public-domain generator (the same algorithm
the frozen simulator uses; the stream IS the protocol: the same seed produces
the same draws, never a clock).

USAGE
  python genera_truthset.py verificar <uniprot_sprot.fasta>
      Verifies the shipped truth set against the public library: re-derives
      the complete sampling design and checks it, column by column (every
      column except `longitud`, the noise-emitted read length), against
      fixtures/truth.tsv. Also verifies every fixture checksum against
      fixtures/truthset.manifiesto.
"""

import sys
from pathlib import Path

AQUI = Path(__file__).parent

# ── THE FROZEN BENCHMARK CONSTANTS (public in the paper's Section 3) ──

SEMILLA_MAESTRA = 0x20261022
N_SOLICITADO = 1000          # slots requested; 983 sources result
N_DECOYS = 1000              # decoy slots requested; one per source results
DOMINANTE_MAX = 0.70         # the exclusion: a window this dominated emits no decoy
READ_MIN = 25
READ_MAX = 40
PROFUNDIDADES = [1, 5, 30]
CANONICOS = set("ACDEFGHIKLMNPQRSTVWY")   # the twenty canonical amino acids

# THE SEVEN-CLASS RECOGNIZER ALPHABET (the paper's Section 3.3 model): the
# six published recognizer classes plus the unrecognized dark class.
QSI_V3 = [
    set("LIV"), set("FYW"), set("R"), set("AS"), set("NQ"), set("DE"),
    set("CGHKMPT"),
]


def dominante_qsi(ventana: str) -> float:
    """The dominant class fraction of a window (fail-closed: 1.0 if it does
    not project — a window that does not project is not a valid negative)."""
    counts = [0] * 7
    n = 0
    for c in ventana:
        for k, clase in enumerate(QSI_V3):
            if c in clase:
                counts[k] += 1
                n += 1
                break
        else:
            return 1.0
    return max(counts) / n if n else 0.0


# ── SPLITMIX64 — the public-domain deterministic generator ──
# (Reference implementation: Melissa O'Neill / the usual public sources:
#  state += 0x9E37..., the two avalanche mixes, the final xor-shift.)

_M64 = (1 << 64) - 1


class Rng:
    """splitmix64 — the public-domain generator, same sequence for same seed."""

    def __init__(self, semilla: int):
        self.st = semilla & _M64

    def u64(self) -> int:
        self.st = (self.st + 0x9E3779B97F4A7C15) & _M64
        z = self.st
        z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & _M64
        z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & _M64
        return z ^ (z >> 31)

    def f01(self) -> float:
        return (self.u64() >> 11) / float(1 << 53)

    def rango(self, n: int) -> int:
        if n <= 0:
            return 0
        return (int(self.f01() * n) % n)


# ── THE SAMPLING DESIGN (the frozen protocol, in code) ──

def ventana_limpia(seq: str, rng: Rng):
    """The [ini, ini+len) window of CANONICAL residues only — 12 attempts."""
    if len(seq) < READ_MAX + 5:
        return None
    for _ in range(12):
        largo = READ_MIN + rng.rango(READ_MAX - READ_MIN + 1)
        ini = rng.rango(len(seq) - largo)
        if all(c in CANONICOS for c in seq[ini:ini + largo]):
            return (ini, largo)
    return None


def acceso_de(cabecera: str) -> str:
    """sp|ACC|... -> ACC (the accession); anything else passes through."""
    if cabecera.startswith("sp|"):
        return cabecera[3:].split("|", 1)[0]
    return cabecera


def parse_fasta(ruta: Path):
    pares, cab, seq = [], "", []
    for linea in ruta.read_text(encoding="utf-8").splitlines():
        if linea.startswith(">"):
            if cab:
                pares.append((cab, "".join(seq)))
            cab, seq = linea[1:], []
        else:
            seq.append(linea.strip())
    if cab:
        pares.append((cab, "".join(seq)))
    return pares


def deriva_muestreo(pares):
    """THE COMPLETE SAMPLING DESIGN, re-derived from the public library.

    Returns the sources: (ordinal i, library index idx, accession, ini, fin,
    per-read seed) — everything truth.tsv records except the noise-emitted
    read lengths.
    """
    paso = max(len(pares) // max(N_SOLICITADO, 1), 1)
    fuentes = []
    for idx, (cab, seq) in enumerate(pares):
        if idx % paso != 0:
            continue
        rng = Rng(SEMILLA_MAESTRA ^ ((idx * 0x9E37) & _M64))
        ventana = ventana_limpia(seq, rng)
        if ventana is None:
            continue
        ini, largo = ventana
        fuentes.append((idx, acceso_de(cab), ini, ini + largo, seq[ini:ini + largo]))
        if len(fuentes) == N_SOLICITADO:
            break
    # THE DECOY SCHEDULE (v2): one inverted-window decoy per source at every
    # consensus depth plus the recognizer-class block — and NO decoy for a
    # source whose window is dominated by one class (the pre-registered
    # exclusion: its inversion is the same string, not a negative).
    paso_decoy = max(len(fuentes) // max(N_DECOYS, 1), 1)
    filas = []
    for i, (idx, acc, ini, fin, ventana) in enumerate(fuentes):
        semilla_read = (SEMILLA_MAESTRA ^ ((idx * 0x5171) & _M64) ^ i) & _M64
        for prof in PROFUNDIDADES:
            filas.append((f"nano_d{prof}_{i:05d}", 0, acc, ini, fin,
                          "nanopore", prof, semilla_read))
        filas.append((f"qsi_{i:05d}", 0, acc, ini, fin, "qsi-v3", 1, semilla_read))
        filas.append((f"fluoro_{i:05d}", 0, acc, ini, fin, "fluoro-2018", 1, semilla_read))
        if i % paso_decoy == 0:
            if dominante_qsi(ventana) >= DOMINANTE_MAX:
                continue
            for prof in PROFUNDIDADES:
                filas.append((f"decoy_d{prof}_{i:05d}", 1, acc, ini, fin,
                              "nanopore", prof, semilla_read))
            filas.append((f"decoy_{i:05d}", 1, acc, ini, fin,
                          "qsi-v3", 1, semilla_read))
    return fuentes, filas


# ── VERIFICACIÓN ──

def verifica_checksums() -> bool:
    man = (AQUI / "fixtures" / "truthset.manifiesto").read_text(encoding="utf-8")
    import hashlib
    esperados = {}
    for linea in man.splitlines():
        if linea.startswith("sha256:"):
            nombre, digest = linea[len("sha256:"):].split("=", 1)
            esperados[nombre] = digest
    ok = True
    for nombre, digest in sorted(esperados.items()):
        ruta = AQUI / "fixtures" / nombre
        if not ruta.exists():
            print(f"  FALTA  {nombre}")
            ok = False
            continue
        h = hashlib.sha256(ruta.read_bytes()).hexdigest()
        marca = "OK " if h == digest else "MAL"
        if h != digest:
            ok = False
        print(f"  {marca}  {nombre}  {h[:16]}…")
    return ok


def verifica_muestreo(fasta: Path) -> bool:
    pares = parse_fasta(fasta)
    print(f"  la librería pública: {len(pares):,} proteínas")
    fuentes, filas = deriva_muestreo(pares)
    print(f"  el muestreo re-derivado: {len(fuentes)} fuentes · {len(filas)} filas de verdad")
    rederivado = {f[0]: f for f in filas}
    enviadas = {}
    lineas = (AQUI / "fixtures" / "truth.tsv").read_text(encoding="utf-8").splitlines()
    cabecera = lineas[0].split("\t")
    for linea in lineas[1:]:
        p = linea.split("\t")
        enviadas[p[0]] = p
    # (pinned lesson): every id on one side must exist on the other — a
    # misaligned input is rejected out loud, never silently absorbed.
    solo_re = set(rederivado) - set(enviadas)
    solo_env = set(enviadas) - set(rederivado)
    if solo_re or solo_env:
        print(f"  DESALINEADO: {len(solo_re)} re-derivadas sin fila · {len(solo_env)} filas sin re-derivar")
        return False
    columnas = ["id", "es_decoy", "acc", "ini", "fin", "modelo", "profundidad", "semilla"]
    malas = 0
    for fid, fila in rederivado.items():
        env = enviadas[fid]
        for col, valor in zip(columnas, fila):
            pos = cabecera.index(col)
            if str(valor) != env[pos]:
                print(f"  DIFIERE {fid} · {col}: re-derivado {valor} ≠ enviado {env[pos]}")
                malas += 1
    if malas:
        print(f"  {malas} columnas difieren — el diseño NO reproduce el truth set")
        return False
    print(f"  las {len(rederivado)} filas verificadas columna a columna "
          f"(id, es_decoy, acc, ini, fin, modelo, profundidad, semilla) — "
          f"la columna `longitud` es la salida del ruido (los fixtures congelados son el registro)")
    return True


def main():
    if len(sys.argv) >= 2 and sys.argv[1] == "verificar":
        if len(sys.argv) < 3:
            raise SystemExit("uso: genera_truthset.py verificar <uniprot_sprot.fasta>\n"
                             "  (the public Swiss-Prot 2026_03 FASTA — ~288 MB — from UniProt)")
        fasta = Path(sys.argv[2])
        if not fasta.exists():
            raise SystemExit(f"no encuentro el fasta: {fasta}")
        print("── LOS CHECKSUMS de los fixtures contra el manifiesto ──")
        ok1 = verifica_checksums()
        print("── EL MUESTREO re-derivado de la librería pública ──")
        ok2 = verifica_muestreo(fasta)
        if ok1 and ok2:
            print("VERIFICADO: el diseño del truth set se reproduce desde la librería pública.")
        else:
            print("FALLÓ la verificación.")
            sys.exit(1)
        return
    raise SystemExit(__doc__)


if __name__ == "__main__":
    main()
