"""Write the protein figure specs used by the trypsin page and the visualization guide.

Reads PDB 3PTB and ligand-crystal.pdb from trypsin-build.py. No calculator is used.

    python trypsin-figures.py --models ../models/proteins --output ../../figures
"""

import argparse
from pathlib import Path

from atomli.visualize import view_pdb


def with_ligand(template, ligand_pdb):
    """3PTB text with the benzamidine heavy-atom block replaced in place by the block with hydrogens."""
    ligand = [line for line in ligand_pdb.splitlines() if line.startswith("HETATM")]
    out, written = [], False
    for line in template.splitlines():
        if line.startswith("HETATM") and line[17:20].strip() == "BEN":
            if not written:
                out.extend(ligand)
                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)
    args = parser.parse_args()
    template = (args.models / "3PTB.pdb").read_text()

    # Initial model of the re-docking page: trypsin, crystal benzamidinium with hydrogens, ligand highlighted.
    complex_text = with_ligand(template, (args.models / "ligand-crystal.pdb").read_text())
    model = view_pdb(complex_text, height=460, style="bTube", atom_scale=220, bond_scale=220, labels=False, controls=False)
    model.select(model.find(resname="BEN"))
    model.write_spec(args.output / "showcases/trypsin-model.json",
                    structure_path=args.output / "showcases/trypsin-model.pdb")

    # Guide figure: the crystal file as is, pocket residues selected, representation switchable by the reader.
    guide = view_pdb(template, height=480, style="bTube", atom_scale=220, bond_scale=220, labels=False,
                 controls=["proteinRepresentation", "style"])
    ligand = guide.find(resname="BEN")
    guide.select(guide.near(ligand, 4.0))
    guide.write_spec(args.output / "tutorials/protein-ligand.json",
                     structure_path=args.output / "tutorials/protein-ligand.pdb")


if __name__ == "__main__":
    main()
