"""Re-dock benzamidine into trypsin (PDB 3PTB) and score the poses with g-xTB.

Reads the files written by trypsin-build.py. Samples rigid-ligand poses around the
crystal pose, scores each as E(cluster+ligand) - E(cluster) - E(ligand) with g-xTB, relaxes
the ligand of the best ten with the pocket cluster frozen, and writes a study (numbers,
energy-versus-RMSD plot linked to the protein viewer, table, provenance) plus poses.json:

    python trypsin-run.py --models ../models/proteins --output ../../studies/trypsin-redocking
"""

import argparse
import importlib.metadata
import json
import time
from pathlib import Path

import numpy as np

from atomli import Atoms
from atomli.calculators import XTB
from atomli.constraints import FixAtoms
from atomli.io import read
from atomli.optimize import BFGS
from atomli.visualize import Study, plot, view_pdb

SEED = 20261111
N_POSES = 300          # clash-free rigid poses that are scored
N_RELAX = 10           # best rigid poses whose ligand is relaxed
SPHERE = 3.5           # translation sphere around the crystal ligand centroid, angstrom
CLASH = 2.2            # heavy-atom pairs closer than this reject a pose, angstrom
NEAR_NATIVE = 2.0      # heavy-atom RMSD below this counts as the crystal pose, angstrom
FMAX = 0.05            # ligand relaxation force tolerance, eV/angstrom
HEAVY = 9              # ligand heavy atoms: ring C1-C6, amidine C, N1, N2 (first in the file)
# Symmetry-equivalent heavy-atom permutations of benzamidinium: ring flip (C2<->C6, C3<->C5) and N1<->N2.
SYMMETRY = [list(range(HEAVY)), [0, 5, 4, 3, 2, 1, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 8, 7], [0, 5, 4, 3, 2, 1, 6, 8, 7]]


def calculator(charge):
    return XTB(method="gxtb", charge=charge, device="gpu")


def energy(atoms, charge):
    atoms = atoms.copy()
    atoms.calc = calculator(charge)
    return float(atoms.get_potential_energy())


def rmsd(positions, reference):
    """Heavy-atom RMSD without refitting (the pocket is frozen), minimum over the symmetry permutations."""
    return min(float(np.sqrt(((positions[:HEAVY][order] - reference[:HEAVY]) ** 2).sum(axis=1).mean())) for order in SYMMETRY)


def random_rotations(rng, count):
    q = rng.normal(size=(count, 4))
    q /= np.linalg.norm(q, axis=1, keepdims=True)  # uniform on SO(3)
    w, x, y, z = q.T
    return np.stack([np.stack([1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], axis=1),
                     np.stack([2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], axis=1),
                     np.stack([2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], axis=1)], axis=1)


def sample_poses(rng, crystal, protein_heavy, wanted):
    """Random rigid poses: uniform rotation about the centroid, translation uniform in a sphere."""
    centroid = crystal[:HEAVY].mean(axis=0)
    poses, trials = [], 0
    while len(poses) < wanted:
        count = 20000
        trials += count
        rotation = random_rotations(rng, count)
        shift = rng.normal(size=(count, 3))
        shift *= (SPHERE * rng.random((count, 1)) ** (1 / 3)) / np.linalg.norm(shift, axis=1, keepdims=True)
        candidate = np.einsum("nij,kj->nki", rotation, crystal - centroid) + centroid + shift[:, None, :]
        nearest = np.linalg.norm(candidate[:, :HEAVY, None, :] - protein_heavy[None, None, :, :], axis=3).min(axis=(1, 2))
        poses.extend(candidate[nearest >= CLASH])
    return np.array(poses[:wanted]), trials


def protein_heavy_atoms(path):
    rows = [(float(l[30:38]), float(l[38:46]), float(l[46:54])) for l in Path(path).read_text().splitlines()
            if l.startswith(("ATOM", "HETATM")) and l[76:78].strip() != "H"]
    return np.array(rows)


class Docking:
    def __init__(self, cluster, ligand, cluster_charge, ligand_charge):
        self.cluster, self.ligand = cluster, ligand
        self.cluster_charge, self.ligand_charge = cluster_charge, ligand_charge
        self.symbols = cluster.get_chemical_symbols() + ligand.get_chemical_symbols()
        self.cluster_positions = cluster.get_positions()
        self.e_cluster = energy(cluster, cluster_charge)

    def ligand_at(self, positions):
        return Atoms(self.ligand.get_chemical_symbols(), positions=positions)

    def complex_at(self, positions):
        return Atoms(self.symbols, positions=np.vstack([self.cluster_positions, positions]))

    def interaction(self, positions):
        """E(cluster+ligand) - E(cluster) - E(ligand at the same geometry), eV."""
        both = energy(self.complex_at(positions), self.cluster_charge + self.ligand_charge)
        return both - self.e_cluster - energy(self.ligand_at(positions), self.ligand_charge)

    def relax(self, positions, log):
        """Relax the ligand with every cluster atom frozen; return positions, steps, converged."""
        atoms = self.complex_at(positions)
        atoms.set_constraint(FixAtoms(indices=list(range(len(self.cluster)))))
        atoms.calc = calculator(self.cluster_charge + self.ligand_charge)
        optimizer = BFGS(atoms, logfile=str(log))
        converged = optimizer.run(fmax=FMAX, steps=200)
        return atoms.get_positions()[len(self.cluster):], optimizer.nsteps, bool(converged)


def load_results(path, crystal):
    """Records saved by an earlier run, in the structure the report step uses."""
    saved = json.loads(path.read_text())
    summary = saved["summary"]
    records = [{"id": "crystal", "kind": "crystal", "positions": crystal, "rmsd": 0.0, "e_int": summary["crystal_rigid_e_int_ev"]}]
    records += [dict(pose, positions=np.array(pose["positions"])) for pose in saved["poses"] if pose["kind"] == "rigid"]
    relaxed = [dict(pose, positions=np.array(pose["positions"])) for pose in saved["poses"] if pose["kind"] == "relaxed"]
    rigid = sorted(records[1:], key=lambda r: r["e_int"])
    return records, rigid, relaxed, summary["random_trials"], summary["elapsed_seconds"]


def pose_text(template, names, positions):
    """3PTB text with the benzamidine HETATM block replaced in place by `positions` (named atoms with hydrogens)."""
    lines, out, written = template.splitlines(), [], False
    for line in lines:
        if line.startswith("HETATM") and line[17:20].strip() == "BEN":
            if not written:
                for serial, (name, (x, y, z)) in enumerate(zip(names, positions), 1):
                    label = f" {name:<3s}" if len(name) < 4 else name
                    out.append(f"HETATM{1631 + serial:5d} {label} BEN A   1    {x:8.3f}{y:8.3f}{z:8.3f}  1.00  0.00          {name[0]:>2s}  ")
                written = True
            continue
        out.append(line)
    return "\n".join(out) + "\n"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--models", type=Path, default=Path(__file__).resolve().parents[1] / "models/proteins")
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--poses", type=int, default=N_POSES, help="rigid poses to score")
    parser.add_argument("--reuse", action="store_true", help="rebuild the study from an existing poses.json without recomputing")
    parser.add_argument("--relax", type=int, default=N_RELAX, help="best rigid poses to relax")
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)

    meta = json.loads((args.models / "pocket-cluster.json").read_text())
    cluster, ligand = read(args.models / "pocket-cluster.xyz"), read(args.models / "ligand-crystal.xyz")
    names = meta["ligand_atom_names"]
    crystal = ligand.get_positions()
    protein_heavy = protein_heavy_atoms(args.models / "protein-h.pdb")
    if args.reuse:
        records, rigid, relaxed, trials, elapsed = load_results(args.output / "poses.json", crystal)
    else:
        docking = Docking(cluster, ligand, meta["cluster_charge"], meta["ligand_charge"])
        started = time.monotonic()

        # 1. Sample and score rigid poses.
        rng = np.random.default_rng(SEED)
        print(f"seed {SEED}; cluster {len(cluster)} atoms charge {meta['cluster_charge']:+d}; ligand charge {meta['ligand_charge']:+d}")
        poses, trials = sample_poses(rng, crystal, protein_heavy, args.poses)
        print(f"{args.poses} poses survive the {CLASH} A clash filter out of {trials} random poses")
        records = [{"id": "crystal", "kind": "crystal", "positions": crystal}]
        records += [{"id": f"p{i:03d}", "kind": "rigid", "positions": pose} for i, pose in enumerate(poses)]
        for number, record in enumerate(records):
            record["rmsd"] = rmsd(record["positions"], crystal)
            record["e_int"] = docking.interaction(record["positions"])
            print(f"{record['id']:>8s} rmsd {record['rmsd']:5.2f} A  E_int {record['e_int']:8.3f} eV  [{number + 1}/{len(records)}]", flush=True)

        # 2. Relax the ligand (pocket frozen) of the best rigid poses and of the crystal pose, then rescore.
        rigid = sorted((r for r in records if r["kind"] == "rigid"), key=lambda r: r["e_int"])
        relaxed = []
        for record in [records[0]] + rigid[:args.relax]:
            positions, steps, converged = docking.relax(record["positions"], args.output / f"{record['id']}-relax.log")
            entry = {"id": f"{record['id']}-relaxed", "kind": "relaxed", "start": record["id"], "positions": positions,
                     "steps": steps, "converged": converged, "rmsd": rmsd(positions, crystal),
                     "e_int": docking.interaction(positions), "e_int_start": record["e_int"], "rmsd_start": record["rmsd"]}
            relaxed.append(entry)
            print(f"{entry['id']:>16s} steps {steps} converged {converged} rmsd {entry['rmsd']:.2f} A E_int {entry['e_int']:.3f} eV", flush=True)
        if not all(entry["converged"] for entry in relaxed):
            raise RuntimeError("a ligand relaxation did not converge")
        elapsed = time.monotonic() - started


    # 3. Rankings.
    docked = [entry for entry in relaxed if entry["start"] != "crystal"]
    docked.sort(key=lambda r: r["e_int"])
    crystal_relaxed = next(entry for entry in relaxed if entry["start"] == "crystal")
    near = [r for r in rigid if r["rmsd"] < NEAR_NATIVE]
    rigid_rank = {r["id"]: k + 1 for k, r in enumerate(rigid)}
    first_near_rank = min(rigid_rank[r["id"]] for r in near) if near else None
    best = docked[0]
    summary = {
        "seed": SEED, "poses_scored": len(rigid), "random_trials": trials, "near_native_poses": len(near),
        "best_pose": best["id"], "best_e_int_ev": best["e_int"], "best_rmsd": best["rmsd"],
        "best_rigid_pose": rigid[0]["id"], "best_rigid_e_int_ev": rigid[0]["e_int"], "best_rigid_rmsd": rigid[0]["rmsd"],
        "first_near_native_rigid_rank": first_near_rank,
        "crystal_rigid_e_int_ev": records[0]["e_int"], "crystal_relaxed_e_int_ev": crystal_relaxed["e_int"],
        "crystal_relaxed_rmsd": crystal_relaxed["rmsd"], "elapsed_seconds": elapsed,
        "relaxed_ranking": [(r["id"], r["e_int"], r["rmsd"]) for r in docked],
    }
    (args.output / "poses.json").write_text(json.dumps({
        "summary": summary,
        "poses": [{k: (v.tolist() if isinstance(v, np.ndarray) else v) for k, v in r.items()} for r in records[1:] + relaxed],
    }, indent=1) + "\n")

    # 4. Study: funnel plot linked to the protein viewer.
    template = (args.models / "3PTB.pdb").read_text()
    linked = {"crystal": records[0], crystal_relaxed["id"]: crystal_relaxed}
    linked.update({r["id"]: r for r in docked})
    starts = {r["start"] for r in docked}
    linked.update({r["id"]: r for r in rigid if r["id"] in starts})  # the rigid pose each relaxation started from
    ligand_atoms = view_pdb(template).find(resname="BEN")
    viewers = {}
    for key, record in linked.items():
        viewer = view_pdb(pose_text(template, names, record["positions"]), height=460, style="bTube",
                          atom_scale=220, bond_scale=220, labels=False)
        viewer.select(ligand_atoms)
        viewers[key] = viewer
    labels = {key: f"{key}: {r['e_int']:.2f} eV, RMSD {r['rmsd']:.2f} Å" for key, r in linked.items()}

    def trace(name, rows, color, symbol, size, opacity):
        return {"type": "scatter", "mode": "markers", "name": name, "x": [r["rmsd"] for r in rows], "y": [r["e_int"] for r in rows],
                "customdata": [r["id"] if r["id"] in linked else None for r in rows],
                "text": [labels.get(r["id"], f"{r['id']}: {r['e_int']:.2f} eV, RMSD {r['rmsd']:.2f} Å") for r in rows],
                "hovertemplate": "%{text}<extra></extra>",
                "marker": {"color": color, "symbol": symbol, "size": size, "opacity": opacity, "line": {"width": 0}}}

    data = [trace("Sampled rigid poses", rigid, "#2266cc", "circle", 7, 0.55),
            trace("Ligand relaxed in the frozen pocket", docked, "#2266cc", "diamond", 11, 1.0),
            trace("Crystal pose", [records[0]], "#dc4b4b", "star", 14, 1.0),
            trace("Crystal pose, relaxed", [crystal_relaxed], "#dc4b4b", "diamond-open", 12, 1.0)]
    YMAX = 8.0
    above = sum(1 for r in rigid if r["e_int"] > YMAX)
    layout = {"margin": {"l": 64, "r": 16, "t": 12, "b": 96}, "legend": {"orientation": "h", "y": -0.28, "x": 0},
              "xaxis": {"title": {"text": "Heavy-atom RMSD to the crystal pose (Å)", "standoff": 8}, "rangemode": "tozero"},
              "yaxis": {"title": {"text": "Interaction energy (eV)", "standoff": 8}, "range": [-7.5, YMAX]}}
    funnel = plot.plotly({"data": data, "layout": layout}, title="Interaction energy against RMSD for sampled benzamidinium poses")

    study = Study("trypsin-redocking", "Re-docking benzamidine into trypsin",
                  system="Trypsin pocket cluster (PDB 3PTB, %d atoms, charge %+d) and benzamidinium (+1)" % (len(cluster), meta["cluster_charge"]),
                  method="g-xTB single points and ligand relaxations, rigid pose sampling")
    study.fact("best_energy", best["e_int"], "eV", label="Lowest relaxed interaction energy", precision=2)
    study.fact("best_rmsd", best["rmsd"], "Å", label="RMSD of that pose to the crystal pose", precision=2)
    study.fact("crystal_rank", first_near_rank if first_near_rank else "none", label="Best rank of a pose within 2 Å (rigid)")
    study.fact("n_scored", len(rigid), label="Rigid poses scored")
    study.figure("funnel", funnel, height=420, caption=f"Each point is one scored pose; {above} rigid poses above {YMAX:.0f} eV are off the axis. Click a relaxed pose, a crystal point or one of the ten relaxation starting poses to show it.")
    study.figure("structure", viewers["crystal"], height=460, caption="Trypsin cartoon with benzamidinium (highlighted) in the S1 pocket:")
    study.link("pose", source="funnel", target="structure", states=viewers, initial="crystal", labels=labels)
    rows = [{"id": r["id"], "stage": "relaxed", "e": r["e_int"], "rmsd": r["rmsd"]} for r in docked]
    rows += [{"id": r["id"], "stage": "rigid", "e": r["e_int"], "rmsd": r["rmsd"]}
             for r in sorted((linked[s] for s in starts), key=lambda r: r["e_int"])]
    rows += [{"id": crystal_relaxed["id"], "stage": "relaxed", "e": crystal_relaxed["e_int"], "rmsd": crystal_relaxed["rmsd"]},
             {"id": "crystal", "stage": "rigid", "e": records[0]["e_int"], "rmsd": 0.0}]
    study.table("poses", [{"key": "id", "label": "Pose", "align": "left"}, {"key": "stage", "label": "Stage", "align": "left"},
                          {"key": "e", "label": "Interaction energy", "unit": "eV", "precision": 3},
                          {"key": "rmsd", "label": "RMSD", "unit": "Å", "precision": 2}], rows, select="pose")
    study.provenance("Interaction energies", f"atomli XTB(method='gxtb', device='gpu'), atomli {importlib.metadata.version('atomli')}: E(cluster+ligand) - E(cluster) - E(ligand at the same geometry), no deformation energy")
    study.provenance("Poses", f"{len(rigid)} rigid poses, NumPy seed {SEED}, uniform rotations, translations in a {SPHERE} Å sphere, heavy-atom clashes under {CLASH} Å rejected")
    study.provenance("RMSD", "benzamidinium heavy atoms against the crystal pose, minimum over the ring-flip and amidinium N1/N2 equivalences")
    study.provenance("Structure", "PDB 3PTB, trypsin with benzamidine at 1.7 Å resolution; hydrogens added with PDBFixer/OpenMM at pH 7.4, not by atomli")
    print(study.write(args.output))
    print(json.dumps(summary, indent=1))


if __name__ == "__main__":
    main()
