"""Build the trypsin-benzamidine (PDB 3PTB) re-docking models. No calculator is used.

Crystal structures have no hydrogens, so this step uses PDBFixer/OpenMM and RDKit, not atomli.
Run it in a separate environment (Python 3.13 wheels exist for all three):

    python3.13 -m venv prep-venv
    prep-venv/bin/pip install pdbfixer openmm rdkit
    prep-venv/bin/python trypsin-build.py --pdb ../models/proteins/3PTB.pdb --output ../models/proteins

Writes, for trypsin-run.py:
    protein-h.pdb            protein with hydrogens at pH 7.4 (PDBFixer), hydrogens relaxed with Amber14 + OBC2
    ligand-crystal.pdb/.xyz  benzamidinium (+1) with hydrogens, crystal heavy-atom positions
    pocket-cluster.xyz/.json residues with any heavy atom within 6 A of the ligand, cut bonds capped with H
"""

import argparse
import json
from pathlib import Path

import numpy as np
from openmm import CustomExternalForce, LangevinMiddleIntegrator, Platform, unit
from openmm.app import ForceField, HBonds, Modeller, NoCutoff, PDBFile, Simulation
from pdbfixer import PDBFixer
from rdkit import Chem
from rdkit.Chem import AllChem

POCKET_RADIUS = 6.0  # A, whole residues with any heavy atom this close to a ligand heavy atom
CAP_LENGTH = {"N": 1.01, "C": 1.09, "S": 1.34}  # X-H bond lengths for the cap hydrogens, A
FORMAL_CHARGE_ATOMS = {"ASP": ("HD2", -1), "GLU": ("HE2", -1)}  # (protonating H, charge when that H is absent)


def split_crystal(pdb):
    """Protein ATOM lines, the calcium ion and the benzamidine HETATM lines of the crystal file."""
    protein, ion, ligand = [], [], []
    for line in Path(pdb).read_text().splitlines():
        if line.startswith("ATOM"):
            protein.append(line)
        elif line.startswith("HETATM") and line[17:20].strip() == "BEN":
            ligand.append(line)
        elif line.startswith("HETATM") and line[17:20].strip() == "CA":
            ion.append(line)
    return protein, ion, ligand


def protonate_protein(protein_lines, work):
    """Add hydrogens at pH 7.4 with PDBFixer, then relax only the hydrogens (heavy atoms restrained)."""
    work.write_text("\n".join(protein_lines) + "\nEND\n")
    fixer = PDBFixer(filename=str(work))
    fixer.findMissingResidues()
    fixer.missingResidues = {}  # the crystal model is complete where it is resolved; add nothing
    fixer.findNonstandardResidues()
    fixer.findMissingAtoms()
    fixer.addMissingAtoms()
    fixer.addMissingHydrogens(7.4)
    forcefield = ForceField("amber14-all.xml", "implicit/obc2.xml")
    modeller = Modeller(fixer.topology, fixer.positions)
    system = forcefield.createSystem(modeller.topology, nonbondedMethod=NoCutoff, constraints=None)
    restraint = CustomExternalForce("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)")
    restraint.addGlobalParameter("k", 5000.0 * unit.kilojoules_per_mole / unit.nanometer**2)
    for name in ("x0", "y0", "z0"):
        restraint.addPerParticleParameter(name)
    for atom, position in zip(modeller.topology.atoms(), modeller.positions):
        if atom.element.symbol != "H":
            restraint.addParticle(atom.index, [position.x, position.y, position.z])
    system.addForce(restraint)
    simulation = Simulation(modeller.topology, system, LangevinMiddleIntegrator(300, 1, 0.002),
                            Platform.getPlatformByName("CPU"))
    simulation.context.setPositions(modeller.positions)
    simulation.minimizeEnergy(maxIterations=2000)
    positions = simulation.context.getState(getPositions=True).getPositions()
    return modeller.topology, positions


def ligand_with_hydrogens(ligand_lines):
    """Benzamidinium from the crystal heavy atoms: template bond orders, then geometric hydrogens."""
    block = "\n".join(ligand_lines) + "\nEND\n"
    molecule = Chem.MolFromPDBBlock(block, removeHs=False, proximityBonding=True)
    template = Chem.MolFromSmiles("NC(=[NH2+])c1ccccc1")
    molecule = AllChem.AssignBondOrdersFromTemplate(template, molecule)
    molecule = Chem.AddHs(molecule, addCoords=True)
    heavy = [(line[12:16].strip(), line[17:20].strip()) for line in ligand_lines]
    names = [name for name, _ in heavy]
    names += [f"H{n}" for n in range(1, molecule.GetNumAtoms() - len(heavy) + 1)]
    symbols = [atom.GetSymbol() for atom in molecule.GetAtoms()]
    positions = molecule.GetConformer().GetPositions()
    return names, symbols, positions


def write_xyz(path, symbols, positions, comment=""):
    lines = [str(len(symbols)), comment]
    lines += [f"{s:2s} {x:12.6f} {y:12.6f} {z:12.6f}" for s, (x, y, z) in zip(symbols, positions)]
    Path(path).write_text("\n".join(lines) + "\n")


def write_ligand_pdb(path, names, positions, chain="A", residue="BEN", number=1):
    lines = []
    for serial, (name, (x, y, z)) in enumerate(zip(names, positions), 1):
        symbol = name[0]
        label = f" {name:<3s}" if len(name) < 4 else name
        lines.append(f"HETATM{serial:5d} {label} {residue:>3s} {chain}{number:4d}    {x:8.3f}{y:8.3f}{z:8.3f}  1.00  0.00          {symbol:>2s}  ")
    Path(path).write_text("\n".join(lines) + "\nEND\n")


def formal_charge(residue_atoms, residue_name, is_nterm, is_cterm):
    """Formal charge of a residue from its hydrogen content at pH 7.4 (isolated amino-acid conventions)."""
    names = {name for name, _ in residue_atoms}
    charge = 0
    if residue_name in FORMAL_CHARGE_ATOMS:
        hydrogen, deprotonated = FORMAL_CHARGE_ATOMS[residue_name]
        charge += 0 if hydrogen in names else deprotonated
    elif residue_name == "LYS":
        charge += 1 if "HZ3" in names else 0
    elif residue_name == "ARG":
        charge += 1
    elif residue_name == "HIS":
        charge += 1 if {"HD1", "HE2"} <= names else 0
    elif residue_name == "CYS" and "SG" in names and "HG" not in names:
        pass  # disulfide cysteines are neutral
    if is_nterm:
        charge += 1  # NH3+
    if is_cterm:
        charge -= 1  # COO-
    return charge


def pocket_cluster(topology, positions, ligand_positions, ligand_symbols):
    """Whole residues near the ligand, cut bonds capped with hydrogens along the severed bond."""
    xyz = np.array([[p.x, p.y, p.z] for p in positions]) * 10.0  # nm -> A
    atoms = list(topology.atoms())
    heavy_ligand = ligand_positions[[s != "H" for s in ligand_symbols]]
    selected = []
    for residue in topology.residues():
        indices = [a.index for a in residue.atoms() if a.element.symbol != "H"]
        distance = np.linalg.norm(xyz[indices][:, None, :] - heavy_ligand[None, :, :], axis=2).min()
        if distance <= POCKET_RADIUS:
            selected.append(residue)
    selected_ids = {residue.index for residue in selected}
    chain_first = {chain.index: next(chain.residues()).index for chain in topology.chains()}
    chain_last = {chain.index: list(chain.residues())[-1].index for chain in topology.chains()}
    symbols, coordinates, labels, charge = [], [], [], 0
    for residue in selected:
        members = [(a.name, a.index) for a in residue.atoms()]
        is_nterm = residue.index == chain_first[residue.chain.index]
        is_cterm = residue.index == chain_last[residue.chain.index]
        charge += formal_charge(members, residue.name, is_nterm, is_cterm)
        for atom in residue.atoms():
            symbols.append(atom.element.symbol)
            coordinates.append(xyz[atom.index])
            labels.append(f"{residue.name}{residue.id}:{atom.name}")
    caps = []
    for bond in topology.bonds():
        a, b = bond
        inside_a, inside_b = a.residue.index in selected_ids, b.residue.index in selected_ids
        if inside_a == inside_b:
            continue
        inner, outer = (a, b) if inside_a else (b, a)
        direction = xyz[outer.index] - xyz[inner.index]
        direction /= np.linalg.norm(direction)
        length = CAP_LENGTH[inner.element.symbol]
        caps.append((inner, outer, xyz[inner.index] + length * direction))
    for inner, outer, position in caps:
        symbols.append("H")
        coordinates.append(position)
        labels.append(f"CAP:{inner.residue.name}{inner.residue.id}:{inner.name}-{outer.residue.name}{outer.residue.id}:{outer.name}")
    return symbols, np.array(coordinates), labels, charge, selected, caps


def build(pdb, output):
    output.mkdir(parents=True, exist_ok=True)
    protein_lines, ion_lines, ligand_lines = split_crystal(pdb)
    topology, positions = protonate_protein(protein_lines, output / "protein-crystal.tmp.pdb")
    (output / "protein-crystal.tmp.pdb").unlink()
    with open(output / "protein-h.pdb", "w") as handle:
        PDBFile.writeFile(topology, positions, handle, keepIds=True)
    names, symbols, ligand_positions = ligand_with_hydrogens(ligand_lines)
    write_xyz(output / "ligand-crystal.xyz", symbols, ligand_positions, "benzamidinium, crystal heavy atoms + hydrogens, charge +1")
    write_ligand_pdb(output / "ligand-crystal.pdb", names, ligand_positions)
    cluster_symbols, cluster_positions, labels, cluster_charge, selected, caps = pocket_cluster(
        topology, positions, ligand_positions, symbols)
    write_xyz(output / "pocket-cluster.xyz", cluster_symbols, cluster_positions,
              f"pocket cluster, {len(selected)} residues, charge {cluster_charge:+d}")
    ion = np.array([[float(line[30:38]), float(line[38:46]), float(line[46:54])] for line in ion_lines])
    nearest_calcium = float(np.linalg.norm(cluster_positions[:, None, :] - ion[None, :, :], axis=2).min())
    ligand_names = [name for name in names]
    (output / "pocket-cluster.json").write_text(json.dumps({
        "pdb": "3PTB", "radius_angstrom": POCKET_RADIUS, "protonation_ph": 7.4,
        "residues": [f"{r.name}{r.id}" for r in selected], "atoms": len(cluster_symbols),
        "cap_hydrogens": len(caps), "cluster_charge": cluster_charge, "ligand_charge": 1,
        "complex_charge": cluster_charge + 1, "ligand_atom_names": ligand_names,
        "ligand_symbols": symbols, "labels": labels,
        "calcium_to_nearest_cluster_atom_angstrom": nearest_calcium,
        "protein_atoms_with_hydrogen": topology.getNumAtoms(),
    }, indent=1) + "\n")
    print(f"protein+H {topology.getNumAtoms()} atoms; cluster {len(cluster_symbols)} atoms, "
          f"{len(selected)} residues, {len(caps)} caps, charge {cluster_charge:+d}; "
          f"nearest Ca2+ to cluster {nearest_calcium:.1f} A")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--pdb", type=Path, default=Path(__file__).resolve().parents[1] / "models/proteins/3PTB.pdb")
    parser.add_argument("--output", type=Path, default=Path("trypsin-models"))
    args = parser.parse_args()
    build(args.pdb, args.output)
