"""Prepare trypsin and benzamidinium with native Atomli chemistry.

This step creates coordinates and topology. It does not run a calculator.
Run protein-mlip.py to relax the model and analyze a selected region.
"""
import argparse
import json
from pathlib import Path

from atomli.biomol import prepare, select, within, extract_cluster
from atomli.io import read, write
from atomli.visualize import Viewer


def build(pdb, output, *, ph=7.4, radius=6.0, figure_output=None):
    output = Path(output)
    output.mkdir(parents=True, exist_ok=True)
    source = read(pdb)
    ligand_residues = [residue for residue in source.topology["residues"] if residue["name"] == "BEN"]
    if len(ligand_residues) != 1:
        raise ValueError("The example requires one BEN residue")
    residue = ligand_residues[0]
    key = f"{residue['chain']}:{residue['sequence']}{residue['insertion']}:{residue['segment']}"
    result = prepare(source, ph=ph, variants={key: "BEN+"}, remove_waters=True)
    atoms = result.atoms
    ligand = select(atoms, resname="BEN")
    protein = select(atoms, hetero=False)
    other = sorted(set(range(len(atoms))) - set(protein) - set(ligand))
    layers = [{"name": "Protein", "indices": protein}, {"name": "Benzamidinium", "indices": ligand}]
    if other:
        layers.append({"name": "Ions", "indices": other})
    write(output / "complex.h5", atoms)
    write(output / "complex.mmcif", atoms)
    write(output / "protein-h.pdb", atoms[protein])
    write(output / "ligand-crystal.pdb", atoms[ligand])
    write(output / "ligand-crystal.xyz", atoms[ligand])
    write(output / "ligand-crystal.h5", atoms[ligand])
    pocket = within(atoms, ligand, radius, residues=True, include_reference=False)
    cluster = extract_cluster(atoms, pocket, reference_atom=ligand[0], unpaired=0)
    write(output / "pocket-cluster.h5", cluster.atoms)
    write(output / "pocket-cluster.xyz", cluster.atoms)
    write(output / "pocket-cluster.mmcif", cluster.atoms)
    viewer = Viewer([atoms], height=480, look={"proteinRepresentation": "cartoon", "layers": layers,
                                             "style": "bTube", "labels": False, "cell": False})
    viewer.write_spec(output / "model.json", structure_path=output / "model.mmcif")
    (output / "preparation.json").write_text(json.dumps(result.report, indent=2) + "\n")
    (output / "cluster.json").write_text(json.dumps(cluster.report, indent=2) + "\n")
    (output / "layers.json").write_text(json.dumps(layers, indent=2) + "\n")
    ligand_topology = atoms[ligand].topology
    metadata = {"source": str(pdb), "preparation": "atomli.biomol", "protonation_ph": result.report["ph"],
                "radius_angstrom": radius, "atoms": len(cluster.atoms),
                "cluster_charge": cluster.report["formal_charge"], "ligand_charge": 1,
                "complex_charge": cluster.report["formal_charge"] + 1,
                "ligand_atom_names": [atom["name"] for atom in ligand_topology["atoms"]],
                "ligand_symbols": atoms[ligand].get_chemical_symbols(),
                "cap_hydrogens": sum(origin is None and symbol == "H" for origin, symbol in
                                     zip(cluster.report["output_to_input"], cluster.atoms.get_chemical_symbols())),
                "residues": [residue["name"] + residue["sequence"] for residue in cluster.atoms.topology["residues"]],
                "protein_atoms_with_hydrogen": len(protein)}
    (output / "pocket-cluster.json").write_text(json.dumps(metadata, indent=2) + "\n")
    if figure_output is not None:
        figure_output = Path(figure_output)
        figure_output.mkdir(parents=True, exist_ok=True)
        viewer.write_spec(figure_output / "model.json", structure_path=figure_output / "model.mmcif")
        for name, report in (("preparation.json", result.report), ("cluster.json", cluster.report)):
            (figure_output / name).write_text(json.dumps(report, indent=2) + "\n")
        summary = {"source": str(pdb), "atoms": len(atoms), "ligand_atoms": len(ligand),
                   "pocket_atoms": len(cluster.atoms), "caps": len(cluster.report["caps"]),
                   "complex_formal_charge": result.report["formal_charge"], "preparation": "atomli.biomol",
                   "geometry": "prepared coordinates; no energy minimization"}
        (figure_output / "prepared.json").write_text(json.dumps(summary, indent=2) + "\n")
    return atoms, result.report


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--pdb", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--ph", type=float, default=7.4)
    parser.add_argument("--radius", type=float, default=6.0)
    parser.add_argument("--figure-output", type=Path)
    args = parser.parse_args()
    atoms, report = build(args.pdb, args.output, ph=args.ph, radius=args.radius, figure_output=args.figure_output)
    print(json.dumps({"atoms": len(atoms), "formal_charge": report["formal_charge"],
                      "added_atoms": len(report["added_atoms"]), "output": str(args.output)}))


if __name__ == "__main__":
    main()
