"""Profile the noncovalent contacts between a protein and its bound ligand with PLIP.

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
from collections import Counter, defaultdict
from pathlib import Path
import xml.etree.ElementTree as ElementTree

import proteiniq_job

FORMATS = {".pdb": "pdb", ".ent": "ent"}
# Each PLIP interaction type and the XML field that holds its characteristic distance.
DISTANCES = {
    "hydrophobic_interaction": "dist", "hydrogen_bond": "dist_d-a", "water_bridge": "dist_a-w",
    "salt_bridge": "dist", "pi_stack": "centdist", "pi_cation_interaction": "dist",
    "halogen_bond": "dist", "metal_complex": "dist",
}
IGNORED_HETEROGENS = {"HOH", "WAT", "DOD", "NA", "CL", "K", "MG", "CA", "ZN", "SO4", "PO4", "GOL", "EDO"}


def ligand_residues(pdb_text: str) -> set[str]:
    """HETATM residue names other than water, common ions and buffer molecules."""
    return {line[17:20].strip() for line in pdb_text.splitlines()
            if line.startswith("HETATM") and line[17:20].strip() not in IGNORED_HETEROGENS}


def make_request(structure: Path) -> dict:
    complex_input = proteiniq_job.file_input(structure, "structure", "protein", FORMATS)
    if not ligand_residues(complex_input["content"]):
        raise ValueError(f"{structure.name} has no ligand HETATM records for PLIP to profile.")
    settings = {
        "analysis_mode": "small_molecule", "model": 1, "nohydro": False,
        "hydroph_dist_max": 4.0, "hbond_dist_max": 4.1, "hbond_don_angle_min": 100,
        "saltbridge_dist_max": 5.5, "pistack_dist_max": 5.5, "pication_dist_max": 6.0,
        "halogen_dist_max": 4.0, "water_bridge_mindist": 2.5, "water_bridge_maxdist": 4.1,
    }
    return {"tool": "plip", "input": {"inputs": [complex_input]}, "settings": settings}


def read_interactions(xml_report: Path) -> list[dict]:
    """One row per interaction in PLIP's XML report, across every binding site."""
    rows = []
    for site in ElementTree.parse(xml_report).getroot().iter("bindingsite"):
        ids = site.find("identifiers")
        ligand = ":".join(ids.findtext(tag, "").strip() for tag in ("hetid", "chain", "position"))
        for kind, distance_field in DISTANCES.items():
            for element in site.iter(kind):
                rows.append({
                    "ligand": ligand, "type": kind.replace("_interaction", "").replace("_", " "),
                    "chain": element.findtext("reschain"), "residue": int(element.findtext("resnr")),
                    "name": element.findtext("restype"),
                    "distance": float(element.findtext(distance_field)),
                })
    return rows


def by_residue(rows: list[dict]) -> dict[tuple[str, int, str], list[dict]]:
    """Interactions grouped by protein residue, in chain and sequence order."""
    groups = defaultdict(list)
    for row in rows:
        groups[(row["chain"], row["residue"], row["name"])].append(row)
    return dict(sorted(groups.items()))


def report(result: dict, output: Path) -> None:
    (xml_report,) = proteiniq_job.output_files(output, r"\.xml$")
    rows = read_interactions(xml_report)
    if not rows:
        print("PLIP found no interactions.")
        return
    with open(output / "interactions.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    residues = by_residue(rows)
    ligands = ", ".join(sorted({row["ligand"] for row in rows}))
    print(f"{ligands}: {len(rows)} interactions with {len(residues)} residues")
    for kind, count in Counter(row["type"] for row in rows).most_common():
        print(f"  {kind:>17}: {count}")
    for (chain, number, name), contacts in residues.items():
        detail = ", ".join(f"{row['type']} {row['distance']:.2f}" for row in contacts)
        label = f"{name}{number}{chain}"
        print(f"  {label:<8} {detail}")
    print(f"Interaction table: {output / 'interactions.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "plip-output")
    arguments.add_argument("--structure", type=Path, help="PDB file of the protein-ligand complex.")
    args = arguments.parse_args()
    if not args.resume and args.structure is None:
        arguments.error("--structure is required for a new run.")
    proteiniq_job.main(args, lambda: make_request(args.structure), report)
