"""Fold a protein sequence with ESMFold and map where the model is confident.

Quotes by default. Add --submit --max-credits N to run one job. Keep the output
folder to resume. Needs proteiniq_job.py from the same page in this folder.
"""
from __future__ import annotations

import csv
from pathlib import Path

import proteiniq_job

AMINO_ACIDS = set("ACDEFGHIKLMNPQRSTVWY")
# pLDDT bands used by AlphaFold DB and the ESMFold paper.
BANDS = [(90, "very high"), (70, "confident"), (50, "low"), (0, "very low")]


def read_sequence(fasta: Path) -> str:
    lines = fasta.read_text(encoding="utf-8").splitlines()
    if sum(line.startswith(">") for line in lines) > 1:
        raise ValueError("Give one sequence per run; this example reports one chain.")
    sequence = "".join(line.strip() for line in lines if not line.startswith(">")).upper()
    unknown = set(sequence) - AMINO_ACIDS
    if not sequence or unknown:
        raise ValueError(f"Not a protein sequence; unexpected letters: {sorted(unknown)}")
    return sequence


def make_request(fasta: Path) -> dict:
    sequence = read_sequence(fasta)
    protein = proteiniq_job.text_input("protein", "protein", "fasta", sequence, fasta.stem)
    settings = {"model_type": "esmfold", "num_recycles": 4, "save_pae_matrix": False}
    return {"tool": "esmfold", "input": {"inputs": [protein]}, "settings": settings}


def residue_plddt(pdb: Path) -> list[tuple[str, int, str, float]]:
    """ESMFold stores pLDDT in the B-factor column; read it from each Cα atom."""
    residues = []
    for line in pdb.read_text(encoding="utf-8").splitlines():
        if line.startswith("ATOM") and line[12:16].strip() == "CA":
            residues.append((line[21], int(line[22:26]), line[17:20], float(line[60:66])))
    if not residues:
        raise ValueError(f"No Cα atoms in {pdb.name}")
    return residues


def band(plddt: float) -> str:
    return next(name for floor, name in BANDS if plddt > floor or floor == 0)


def low_confidence_segments(residues, threshold: float = 70) -> list[tuple[int, int, float]]:
    """Runs of consecutive residues below the threshold, with their lowest pLDDT."""
    segments, current = [], []
    for _, number, _, plddt in residues + [("", -1, "", 100.0)]:
        if plddt < threshold:
            current.append((number, plddt))
        elif current:
            segments.append((current[0][0], current[-1][0], min(p for _, p in current)))
            current = []
    return segments


def report(result: dict, output: Path) -> None:
    summary = result["summary"]
    (model,) = proteiniq_job.output_files(output, r"\.pdb$")
    residues = residue_plddt(model)
    with open(output / "plddt.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["chain", "residue", "name", "plddt", "band"])
        writer.writerows([*residue, band(residue[3])] for residue in residues)
    ca_mean = sum(plddt for *_, plddt in residues) / len(residues)
    # The summary averages every atom; the per-residue Cα mean is usually higher.
    print(f"{summary['total_residues']} residues, mean pLDDT {summary['best_plddt']:.1f} "
          f"over atoms and {ca_mean:.1f} over Cα, pTM {summary['ptm']:.2f}")
    for floor, name in BANDS:
        count = sum(band(plddt) == name for *_, plddt in residues)
        print(f"  {name:>9}: {count} residues")
    for start, end, lowest in low_confidence_segments(residues):
        print(f"  below 70: residues {start}-{end} (lowest {lowest:.1f})")
    print(f"Per-residue table: {output / 'plddt.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "esmfold-output")
    arguments.add_argument("--sequence", type=Path, help="FASTA file with one protein sequence.")
    args = arguments.parse_args()
    if not args.resume and args.sequence is None:
        arguments.error("--sequence is required for a new run.")
    proteiniq_job.main(args, lambda: make_request(args.sequence), report)
