"""Recompute every structural number in content/guides/antibody-vs-antigen.mdx.

Downloads four public complexes from the RCSB PDB and reports, for each
antibody-antigen pair, the residues with any heavy atom within a cutoff of the
partner, and the surface area each side loses on binding. Waters and other
heteroatoms are removed; only the first model is used.

    1VFB  D1.3 Fv + hen egg-white lysozyme (HEL)   A,B | C   1.8 A
    1DVF  D1.3 Fv + anti-idiotype E5.2 Fv          A,B | C,D 1.9 A
    3HFM  HyHEL-10 Fab + HEL                       L,H | Y   3.0 A
    1MLC  D44.1 Fab + HEL (first copy)             A,B | E   2.5 A

Buried area is the Shrake-Rupley SASA (1.4 A probe, 960 points, Biopython)
of the chain set alone minus its SASA inside the complex. CDRs are the Kabat
loops of D1.3, located by sequence motif because the PDB numbering of the
heavy chain is sequential, not Kabat.

    python -I epitope_contacts.py <work-dir>
"""
import copy
import sys
import urllib.request
from pathlib import Path

from Bio.PDB import NeighborSearch, PDBParser, ShrakeRupley
from Bio.PDB.Model import Model
from Bio.PDB.Polypeptide import index_to_one, three_to_index
from Bio.PDB.Structure import Structure

WORK = Path(sys.argv[1])
WORK.mkdir(parents=True, exist_ok=True)
COMPLEXES = {
    "1VFB": (["A", "B"], ["C"]),
    "1DVF": (["A", "B"], ["C", "D"]),
    "3HFM": (["L", "H"], ["Y"]),
    "1MLC": (["A", "B"], ["E"]),
}


def load(pdb_id):
    path = WORK / f"{pdb_id}.pdb"
    if not path.exists():
        urllib.request.urlretrieve(f"https://files.rcsb.org/download/{pdb_id}.pdb", path)
    model = PDBParser(QUIET=True).get_structure(pdb_id, path)[0]
    for chain in model:
        for res in list(chain):
            if res.id[0] != " ":
                chain.detach_child(res.id)
    return model


def rid(res):
    """Residue number with its insertion code, so 52 and 52A stay distinct."""
    return f"{res.id[1]}{res.id[2].strip()}"


def contacts(model, side_a, side_b, cutoff):
    atoms_b = [a for c in side_b for a in model[c].get_atoms()]
    ns = NeighborSearch(atoms_b)
    res_a, res_b = set(), set()
    for atom in (a for c in side_a for a in model[c].get_atoms()):
        for other in ns.search(atom.coord, cutoff):
            res_a.add((atom.get_parent().get_parent().id, rid(atom.get_parent()), atom.get_parent().get_resname()))
            res_b.add((other.get_parent().get_parent().id, rid(other.get_parent()), other.get_parent().get_resname()))
    return res_a, res_b


def sasa(model, chains):
    st = Structure("x")
    mo = Model(0)
    st.add(mo)
    for c in chains:
        mo.add(copy.deepcopy(model[c]))
    ShrakeRupley(probe_radius=1.4, n_points=960).compute(st, level="R")
    return {(r.get_parent().id, rid(r)): r.sasa for r in st[0].get_residues()}


def buried(model, side, other):
    alone, inside = sasa(model, side), sasa(model, side + other)
    return {k: alone[k] - inside[k] for k in alone}


print("== contacts within 4 A and 5 A")
sets = {}
for pdb_id, (ab, ag) in COMPLEXES.items():
    m = load(pdb_id)
    for cut in (4.0, 5.0):
        a, g = contacts(m, ab, ag, cut)
        print(pdb_id, cut, "antibody-side", len(a), "partner-side", len(g))
        if cut == 4.0:
            sets[pdb_id] = (a, g)

hel = {k: {r[1] for r in sets[k][1]} for k in ("1VFB", "3HFM", "1MLC")}
union = set().union(*hel.values())
print("HEL epitopes: union", len(union), "of 129;", "D1.3 & HyHEL-10:", sorted(hel["1VFB"] & hel["3HFM"]),
      "D44.1 shared with either:", sorted(hel["1MLC"] & (hel["1VFB"] | hel["3HFM"])))

print("== D1.3 paratope: lysozyme (1VFB) vs E5.2 (1DVF), chain A=VL, B=VH")
p_hel = {(r[0], r[1]) for r in sets["1VFB"][0]}
p_e52 = {(r[0], r[1]) for r in sets["1DVF"][0]}
print("lysozyme", len(p_hel), "E5.2", len(p_e52), "shared", len(p_hel & p_e52),
      "lysozyme only", sorted(p_hel - p_e52), "E5.2 only", sorted(p_e52 - p_hel))

m1 = load("1VFB")
vl = "".join(index_to_one(three_to_index(r.get_resname())) for r in m1["A"])
vh = "".join(index_to_one(three_to_index(r.get_resname())) for r in m1["B"])
loops = {"A": ["RASGNIHNYLA", "YTTTLAD", "QHFWSTPRT"], "B": ["GYGVN", "MIWGDGNTDYNSALKS", "ERDYRLDY"]}
cdr = set()
for chain, seq in (("A", vl), ("B", vh)):
    nums = [rid(r) for r in m1[chain]]
    for motif in loops[chain]:
        i = seq.find(motif)
        assert i >= 0
        cdr |= {(chain, n) for n in nums[i:i + len(motif)]}
print("Kabat CDR residues", len(cdr), "paratope in CDR", len(p_hel & cdr), "outside", sorted(p_hel - cdr))

print("== buried area (A^2) and residue counts by threshold")
for pdb_id in ("1VFB", "1DVF"):
    ab, ag = COMPLEXES[pdb_id]
    m = load(pdb_id)
    b_ab, b_ag = buried(m, ab, ag), buried(m, ag, ab)
    print(pdb_id, "antibody-side", round(sum(b_ab.values())), "partner-side", round(sum(b_ag.values())))
    if pdb_id == "1VFB":
        for t in (1.0, 10.0):
            print("  dSASA >=", t, "paratope", sum(v >= t for v in b_ab.values()), "epitope", sum(v >= t for v in b_ag.values()))
