#!/usr/bin/env python3
"""
THE SUBMISSION CLIENT — protein-read identification benchmark v2.

Sends every fixture track of the benchmark to the kmer.bio identification
service — the reads plus the name of the signed reference library — and
records one verdict per read: the top candidate's accession and its raw
containment. Those verdicts are what metrics.py sweeps over the frozen
threshold grid.

THE INTERFACE (the paper's Section 2): the service is exposed over the Model
Context Protocol (MCP, Streamable HTTP — stateless) at https://kmer.bio/mcp.
The protein identification panel is the commercial product; its public API
the free anonymous door (600 credits a day) covers the benchmark run; write
to info@kmer.bio for a key on larger runs. This client implements the
documented interface and runs unchanged (--tool if the name differs).

The run is resumable: verdicts already recorded are kept, and a quota stop
leaves the state saved.

USAGE
  python submit.py --todo                      # every fixture track
  python submit.py --fasta fixtures/qsi_v3.fa --salida verdicts/qsi_v3.tsv
Options:
  --url https://kmer.bio/mcp   the MCP endpoint
  --tool screening_proteico   the protein identification tool (the default)
  --library swiss-prot-2026_03 the signed library, by name
"""

import json
import re
import sys
import time
import urllib.request
from pathlib import Path

AQUI = Path(__file__).parent
FIXTURES = AQUI / "fixtures"
VEREDICTOS = AQUI / "verdicts"

URL_DEFECTO = "https://kmer.bio/mcp"
TOOL_DEFECTO = "screening_proteico"
LIBRERIA_DEFECTO = "swiss-prot-2026_03"
UA = "kmerbio-kit-proteico/1.0 (reproduction kit)"

# The track set of the benchmark (the fixtures), with their verdict files.
TRACKS = [
    ("nano_full20.fa", "nano_full20.tsv"),
    ("nano_dayhoff6.fa", "nano_dayhoff6.tsv"),
    ("qsi_v3.fa", "qsi_v3.tsv"),
    ("fluoro.fa", "fluoro.tsv"),
    ("decoy_full20.fa", "decoy_full20.tsv"),
    ("decoy_dayhoff6.fa", "decoy_dayhoff6.tsv"),
    ("decoy_qsi_v3.fa", "decoy_qsi_v3.tsv"),
    ("decoy_fluoro.fa", "decoy_fluoro.tsv"),
]

RE_CUOTA = re.compile(r"agotad|cuota|quota|saldo|cr[eé]dito|429|too many|rate limit", re.I)


class CorteQuota(Exception):
    pass


class McpCliente:
    """MCP Streamable HTTP (stateless): initialize → tools/call per session."""

    def __init__(self, url: str):
        self.url = url
        self._id = iter(range(1, 10_000_000))
        self.server_info = None

    def _post(self, payload: dict, timeout: int = 600) -> dict | None:
        req = urllib.request.Request(
            self.url, data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json",
                     "Accept": "application/json, text/event-stream",
                     "User-Agent": UA})
        with urllib.request.urlopen(req, timeout=timeout) as r:
            raw = r.read().decode()
        for line in raw.splitlines():
            if line.startswith("data: ") and len(line) > 6:
                try:
                    return json.loads(line[6:])
                except json.JSONDecodeError:
                    continue
        return None

    def conectar(self):
        r = self._post({
            "jsonrpc": "2.0", "id": next(self._id), "method": "initialize",
            "params": {"protocolVersion": "2025-03-26", "capabilities": {},
                       "clientInfo": {"name": "kmerbio-kit-proteico", "version": "1.0"}},
        })
        self.server_info = (r or {}).get("result", {}).get("serverInfo")
        self._post({"jsonrpc": "2.0", "method": "notifications/initialized"})
        return self.server_info

    def tools_list(self) -> list[dict]:
        r = self._post({"jsonrpc": "2.0", "id": next(self._id),
                        "method": "tools/list", "params": {}})
        return (r or {}).get("result", {}).get("tools", [])

    def tool_call(self, name: str, arguments: dict, timeout: int = 600) -> dict:
        r = self._post({"jsonrpc": "2.0", "id": next(self._id), "method": "tools/call",
                        "params": {"name": name, "arguments": arguments}}, timeout=timeout)
        if r is None:
            return {"ok": False, "error": "respuesta vacía"}
        if "error" in r:
            return {"ok": False, "error": r["error"]}
        resultado = r.get("result", {})
        if resultado.get("isError"):
            item = (resultado.get("content") or [{}])[0]
            return {"ok": False, "error": item.get("text", "error del tool")}
        item = (resultado.get("content") or [{}])[0]
        texto = item.get("text", "")
        try:
            return {"ok": True, "json": json.loads(texto)}
        except (json.JSONDecodeError, TypeError):
            return {"ok": True, "texto": texto}


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


def busca(obj, claves):
    """The first occurrence of any of the keys (recursive) — tolerant of the
    service's naming (acceso/accession/hit_nombrado; contencion/containment)."""
    if isinstance(obj, dict):
        for k, v in obj.items():
            if k in claves:
                return v
        for v in obj.values():
            r = busca(v, claves)
            if r is not None:
                return r
    elif isinstance(obj, list):
        for v in obj:
            r = busca(v, claves)
            if r is not None:
                return r
    return None


def extrae_veredictos(respuesta):
    """The per-read verdict rows from a tool response: (id, acceso, contencion)."""
    filas = []
    contenedores = []
    if isinstance(respuesta, dict):
        for k in ("los_resultados", "resultados", "veredictos", "reads", "resultado", "filas", "data"):
            if k in respuesta:
                contenedores = respuesta[k] if isinstance(respuesta[k], list) else [respuesta[k]]
                break
        else:
            contenedores = [respuesta]
    elif isinstance(respuesta, list):
        contenedores = respuesta
    for item in contenedores:
        if not isinstance(item, dict):
            continue
        rid = busca(item, ("id", "read_id"))
        if rid is None:
            continue
        acceso = busca(item, ("mejor", "acceso", "accession", "hit_nombrado", "hit", "llamado"))
        cont = busca(item, ("contencion", "containment", "confianza", "confidence"))
        filas.append((str(rid), str(acceso or "-"), float(cont or 0.0)))
    return filas


def envia_track(mcp, fasta: Path, salida: Path, tool, libreria):
    pares = lee_fasta(fasta)
    ya = set()
    if salida.exists():
        for linea in salida.read_text(encoding="utf-8").splitlines()[1:]:
            if linea.strip():
                ya.add(linea.split("\t")[0])          # resumable: no double spend
    pendientes = [(c, s) for c, s in pares if c.split("|")[0] not in ya]
    if not pendientes:
        print(f"  {fasta.name}: {len(ya)} veredictos ya registrados — nada que enviar")
        return
    contenido = "".join(f">{c}\n{s}\n" for c, s in pendientes)
    print(f"  {fasta.name}: {len(pendientes)} reads → el servicio…", flush=True)
    # el contrato del tool: query_tea (el FASTA crudo); el panel es el de la casa
    r = mcp.tool_call(tool, {"query_tea": contenido})
    if not r.get("ok"):
        texto = str(r.get("error", ""))
        if RE_CUOTA.search(texto):
            raise CorteQuota(texto)
        raise SystemExit(f"  el servicio rechazó el track {fasta.name}: {texto}")
    filas = extrae_veredictos(r.get("json", r.get("texto")))
    if not filas:
        raise SystemExit(f"  el servicio no devolvió veredictos por read para {fasta.name} "
                         "(formato inesperado — reporta a info@kmer.bio)")
    salida.parent.mkdir(parents=True, exist_ok=True)
    cuerpo = f"id\tacceso\tcontencion\n"
    if salida.exists():
        cuerpo += "".join(l + "\n" for l in salida.read_text(encoding="utf-8").splitlines()[1:]
                          if l.strip())
    cuerpo += "".join(f"{i}\t{a}\t{c}\n" for i, a, c in filas)
    salida.write_text(cuerpo, encoding="utf-8")
    print(f"  {fasta.name}: {len(filas)} veredictos → {salida.name}")


def main():
    args = sys.argv[1:]

    def opt(nombre, defecto=None):
        return args[args.index(nombre) + 1] if nombre in args else defecto

    url = opt("--url", URL_DEFECTO)
    tool = opt("--tool", TOOL_DEFECTO)
    libreria = opt("--library", opt("--libreria", LIBRERIA_DEFECTO))
    mcp = McpCliente(url)
    info = mcp.conectar()
    print(f"── kmer.bio MCP: {info.get('name', '?')} {info.get('version', '?')} · {url}")
    herramientas = [t["name"] for t in mcp.tools_list()]
    if tool not in herramientas:
        print(f"EL PANEL NO ESTÁ EN TU ACCESO: la herramienta '{tool}' no está entre las "
              f"{len(herramientas)} disponibles ({', '.join(herramientas[:8])}…).")
        print("El acceso público al panel de identificación proteica está en despliegue "
              "escalonado: escribe a info@kmer.bio (las peticiones de reproducción del "
              "benchmark tienen prioridad). Todo lo demás del kit — la verificación de los "
              "fixtures, la semántica pineada, las tablas congeladas — funciona hoy, offline.")
        sys.exit(2)
    if "--todo" in args:
        for fasta, salida in TRACKS:
            envia_track(mcp, FIXTURES / fasta, VEREDICTOS / salida, tool, libreria)
    elif "--fasta" in args:
        fasta = Path(opt("--fasta"))
        salida = Path(opt("--salida", VEREDICTOS / (fasta.stem + ".tsv")))
        envia_track(mcp, fasta, salida, tool, libreria)
    else:
        raise SystemExit(__doc__)


if __name__ == "__main__":
    try:
        main()
    except CorteQuota as e:
        print(f"CUOTA AGOTADA: {e} — el estado queda guardado; re-lanza mañana (resumible).")
        sys.exit(3)
