"""Redock a ligand into its crystal structure with AutoDock Vina and score each pose by RMSD.

Quotes by default. Add --submit --max-credits N to run one job. Keep the output
folder to resume. Needs proteiniq_job.py from the same page in this folder.
"""
from __future__ import annotations

import csv
import math
from pathlib import Path
import re

import proteiniq_job

SMILES = re.compile(r"^[A-Za-z0-9@+\-\[\]()=#$/\\%.:*]+$")
# AutoDock atom types that are not plain element symbols.
AD_ELEMENTS = {"A": "C", "NA": "N", "NS": "N", "OA": "O", "OS": "O", "SA": "S", "HD": "H", "HS": "H"}
# Covalent radii in Å, for perceiving bonds from coordinates.
RADII = {"C": 0.76, "N": 0.71, "O": 0.66, "S": 1.05, "P": 1.07, "F": 0.57, "CL": 1.02, "BR": 1.20, "I": 1.39}


def receptor_from_complex(pdb_text: str) -> str:
    """Drop ligands, ions and waters (HETATM) and their CONECT records, keeping the protein."""
    kept = [line for line in pdb_text.splitlines(keepends=True) if not line.startswith(("HETATM", "CONECT"))]
    if not any(line.startswith("ATOM") for line in kept):
        raise ValueError("No protein ATOM records in the complex.")
    return "".join(kept)


def crystal_ligand(pdb_text: str, residue: str, chain: str) -> list[tuple[str, tuple[float, float, float]]]:
    """Heavy atoms of one bound ligand, as (element, coordinates)."""
    atoms = []
    for line in pdb_text.splitlines():
        if line.startswith("HETATM") and line[17:20].strip() == residue and line[21] == chain:
            element = (line[76:78].strip() or line[12:16].strip()[0]).upper()
            if element != "H":
                atoms.append((element, (float(line[30:38]), float(line[38:46]), float(line[46:54]))))
    if not atoms:
        raise ValueError(f"No {residue} ligand in chain {chain}.")
    return atoms


def search_box(atoms, padding: float = 5.0) -> dict:
    """The crystal ligand's bounding box, padded on every side, as Vina center and size settings."""
    box = {}
    for axis, index in zip("xyz", range(3)):
        low, high = min(xyz[index] for _, xyz in atoms), max(xyz[index] for _, xyz in atoms)
        box[f"center_{axis}"] = round((low + high) / 2, 3)
        box[f"size_{axis}"] = round(high - low + 2 * padding, 3)
    return box


def make_request(complex_pdb: Path, smiles: str, residue: str, chain: str) -> dict:
    text = complex_pdb.read_text(encoding="utf-8")
    if not SMILES.match(smiles) or "." in smiles:
        raise ValueError("Give one ligand as a single SMILES string.")
    receptor = proteiniq_job.text_input("protein", "protein", "pdb", receptor_from_complex(text),
                                        f"{complex_pdb.stem} receptor")
    ligand = proteiniq_job.text_input("ligand", "ligand", "smiles", smiles, residue)
    settings = {
        "multi_ligand_mode": "single", "docking_mode": "dock", "scoring_function": "vina",
        "exhaustiveness": 8, "num_modes": 9, "energy_range": 3, "min_rmsd": 1, "seed": 42,
        "search_mode": "manual", **search_box(crystal_ligand(text, residue, chain)),
        "receptor_use_pdb2pqr": "pdb2pqr", "receptor_pdb2pqr_ph": 7,
        "receptor_remove_covalent_ligand_chains": True,
    }
    return {"tool": "autodock-vina", "input": {"inputs": [receptor, ligand]}, "settings": settings}


def read_poses(pdbqt: Path) -> list[tuple[float, list[tuple[str, tuple[float, float, float]]]]]:
    """Each MODEL of Vina's native output: its affinity and its heavy atoms."""
    poses = []
    for line in pdbqt.read_text(encoding="utf-8").splitlines():
        if line.startswith("MODEL"):
            affinity, atoms = None, []
        elif line.startswith("REMARK VINA RESULT:"):
            affinity = float(line.split()[3])
        elif line.startswith(("ATOM", "HETATM")):
            element = AD_ELEMENTS.get(line[77:79].strip(), line[77:79].strip()).upper()
            if element != "H":
                atoms.append((element, (float(line[30:38]), float(line[38:46]), float(line[46:54]))))
        elif line.startswith("ENDMDL"):
            poses.append((affinity, atoms))
    if not poses:
        raise ValueError(f"No poses in {pdbqt.name}")
    return poses


def bond_graph(atoms) -> list[set[int]]:
    """Neighbours of each atom, from interatomic distances."""
    neighbours = [set() for _ in atoms]
    for i, (element_i, xyz_i) in enumerate(atoms):
        for j in range(i + 1, len(atoms)):
            element_j, xyz_j = atoms[j]
            if math.dist(xyz_i, xyz_j) < RADII.get(element_i, 0.8) + RADII.get(element_j, 0.8) + 0.45:
                neighbours[i].add(j)
                neighbours[j].add(i)
    return neighbours


def symmetric_rmsd(pose, reference) -> float:
    """In-place heavy-atom RMSD, minimised over every atom mapping that preserves the bond graph.

    Vina renames and reorders atoms, and a flipped phenyl ring is the same pose, so
    atoms are matched by element and bonding rather than by name.
    """
    if sorted(e for e, _ in pose) != sorted(e for e, _ in reference):
        raise ValueError("Pose and reference ligand have different heavy atoms.")
    pose_bonds, ref_bonds = bond_graph(pose), bond_graph(reference)
    # Visit pose atoms in breadth-first order so each new atom has a placed neighbour.
    order, seen = [], set()
    for start in range(len(pose)):
        queue = [start] if start not in seen else []
        seen.update(queue)
        while queue:
            atom = queue.pop(0)
            order.append(atom)
            for neighbour in sorted(pose_bonds[atom] - seen):
                seen.add(neighbour)
                queue.append(neighbour)
    best = [math.inf]

    def extend(depth: int, mapping: dict[int, int], used: set[int], total: float) -> None:
        if total >= best[0]:
            return
        if depth == len(order):
            best[0] = total
            return
        atom = order[depth]
        for candidate in range(len(reference)):
            if (candidate in used or reference[candidate][0] != pose[atom][0]
                    or len(ref_bonds[candidate]) != len(pose_bonds[atom])):
                continue
            if all((mapping[n] in ref_bonds[candidate]) for n in pose_bonds[atom] if n in mapping):
                mapping[atom] = candidate
                used.add(candidate)
                extend(depth + 1, mapping, used,
                       total + math.dist(pose[atom][1], reference[candidate][1]) ** 2)
                del mapping[atom]
                used.discard(candidate)

    extend(0, {}, set(), 0.0)
    if best[0] == math.inf:
        raise ValueError("Pose and reference ligand have different bonding.")
    return math.sqrt(best[0] / len(pose))


def report(result: dict, output: Path, complex_pdb: Path, residue: str, chain: str) -> None:
    (native,) = proteiniq_job.output_files(output, r"_output\.pdbqt$")
    reference = crystal_ligand(complex_pdb.read_text(encoding="utf-8"), residue, chain)
    rows = [(rank, affinity, symmetric_rmsd(atoms, reference))
            for rank, (affinity, atoms) in enumerate(read_poses(native), 1)]
    with open(output / "poses.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["rank", "affinity_kcal_mol", "rmsd_to_crystal_angstrom"])
        writer.writerows((rank, f"{affinity:.3f}", f"{rmsd:.2f}") for rank, affinity, rmsd in rows)
    print(f"{len(rows)} poses of {residue} against chain {chain} of {complex_pdb.stem}")
    print("rank  affinity (kcal/mol)  RMSD to crystal (A)")
    for rank, affinity, rmsd in rows:
        print(f"{rank:>4}  {affinity:>19.2f}  {rmsd:>19.2f}")
    # A heavy-atom RMSD under 2 Å is the usual threshold for a correctly reproduced pose.
    within = [rank for rank, _, rmsd in rows if rmsd < 2.0]
    print(f"Top pose {'reproduces' if rows[0][2] < 2.0 else 'misses'} the crystal pose; "
          f"poses within 2 A: {', '.join(map(str, within)) or 'none'}")
    print(f"Pose table: {output / 'poses.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "vina-output")
    arguments.add_argument("--complex", type=Path, required=True,
                           help="PDB file of the crystal complex; the receptor and reference come from it.")
    arguments.add_argument("--smiles", help="SMILES of the ligand to dock.")
    arguments.add_argument("--ligand-residue", default="STI", help="Residue name of the bound ligand.")
    arguments.add_argument("--ligand-chain", default="A", help="Chain of the bound ligand copy.")
    args = arguments.parse_args()
    if not args.resume and args.smiles is None:
        arguments.error("--smiles is required for a new run.")
    proteiniq_job.main(
        args,
        lambda: make_request(args.complex, args.smiles, args.ligand_residue, args.ligand_chain),
        lambda result, output: report(result, output, args.complex, args.ligand_residue, args.ligand_chain),
    )
