"""Score a predicted protein complex against a reference structure with DockQ.

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 json
from pathlib import Path

import proteiniq_job

STRUCTURE_FORMATS = {".pdb": "pdb", ".ent": "ent", ".cif": "cif"}
# DockQ v2 prints these bands; Basu and Wallner chose them to match the CAPRI classes.
BANDS = [(0.80, "High"), (0.49, "Medium"), (0.23, "Acceptable"), (0.0, "Incorrect")]
# CAPRI criteria: (class, minimum fnat, maximum LRMSD, maximum iRMSD); either RMSD may pass.
CAPRI = [("High", 0.5, 1.0, 1.0), ("Medium", 0.3, 5.0, 2.0), ("Acceptable", 0.1, 10.0, 4.0)]


def pdb_chains(path: Path) -> set[str]:
    return {line[21] for line in path.read_text(encoding="utf-8").splitlines()
            if line.startswith(("ATOM", "HETATM")) and len(line) > 21}


def make_request(model: Path, native: Path, chain_mapping: str = "") -> dict:
    if chain_mapping and (chain_mapping.count(":") != 1 or "," in chain_mapping):
        raise ValueError("Write the chain mapping as MODEL:NATIVE, one character per chain, e.g. AB:AB.")
    inputs = []
    for path, slot in ((model, "model"), (native, "native")):
        structure = proteiniq_job.file_input(path, slot, "protein", STRUCTURE_FORMATS)
        # An interface needs two chains. mmCIF chain IDs are left for DockQ to read.
        if structure["format"] != "cif" and len(pdb_chains(path)) < 2:
            raise ValueError(f"{path.name} has fewer than two chains, so it has no interface to score.")
        inputs.append(structure)
    settings = {"chain_mapping": chain_mapping, "small_molecule": False, "capri_peptide": False,
                "no_align": False, "allowed_mismatches": 0}
    return {"tool": "dockq", "input": {"inputs": inputs}, "settings": settings}


def dockq_terms(fnat: float, irmsd: float, lrmsd: float) -> tuple[float, float, float]:
    """The three averaged terms of DockQ: fnat and the two RMSDs scaled to 0..1."""
    return fnat, 1 / (1 + (irmsd / 1.5) ** 2), 1 / (1 + (lrmsd / 8.5) ** 2)


def band(dockq: float) -> str:
    return next(name for floor, name in BANDS if dockq >= floor)


def capri_class(fnat: float, irmsd: float, lrmsd: float) -> str:
    for name, min_fnat, max_lrmsd, max_irmsd in CAPRI:
        if fnat >= min_fnat and (lrmsd <= max_lrmsd or irmsd <= max_irmsd):
            return name
    return "Incorrect"


def interfaces(native_report: dict) -> list[dict]:
    """One row per native interface for the chain mapping DockQ chose."""
    rows = []
    for metrics in native_report["best_result"].values():
        if metrics.get("is_het") or metrics.get("fnat") is None:
            continue  # Small-molecule interfaces are scored from LRMSD alone.
        terms = dockq_terms(metrics["fnat"], metrics["iRMSD"], metrics["LRMSD"])
        rows.append({**metrics, "interface": f"{metrics['chain1']}:{metrics['chain2']}",
                     "terms": terms, "band": band(metrics["DockQ"]),
                     "capri": capri_class(metrics["fnat"], metrics["iRMSD"], metrics["LRMSD"])})
    return rows


def report(result: dict, output: Path) -> None:
    (native_file,) = proteiniq_job.output_files(output, r"dockq_results\.json$")
    native_report = json.loads(native_file.read_text(encoding="utf-8"))
    rows = interfaces(native_report)
    print(f"DockQ {result.get('version', '')}, chain mapping {native_report['best_mapping_str']} "
          f"(model:native), GlobalDockQ {native_report['GlobalDockQ']:.3f}")
    for row in rows:
        fnat_term, irmsd_term, lrmsd_term = row["terms"]
        ligand, receptor = ((row["chain1"], row["chain2"]) if row["class1"] == "ligand"
                            else (row["chain2"], row["chain1"]))
        print(f"Interface {row['interface']}: DockQ {row['DockQ']:.3f}, {row['band']}; "
              f"CAPRI criteria give {row['capri']}")
        print(f"  fnat     {row['fnat']:6.3f}    term {fnat_term:.3f}  "
              f"{row['nat_correct']} of {row['nat_total']} native contacts")
        print(f"  iRMSD    {row['iRMSD']:6.2f} Å  term {irmsd_term:.3f}")
        print(f"  LRMSD    {row['LRMSD']:6.2f} Å  term {lrmsd_term:.3f}  "
              f"chain {ligand} placed with chain {receptor} superposed")
        print(f"  fnonnat  {row['fnonnat']:6.3f}               "
              f"{row['nonnat_count']} of {row['model_total']} model contacts not in the native")
        print(f"  clashes  {row['clashes']:6d}")
    with open(output / "interfaces.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(["interface", "dockq", "band", "capri_class", "fnat", "irmsd", "lrmsd",
                         "fnonnat", "f1", "clashes"])
        writer.writerows([row["interface"], row["DockQ"], row["band"], row["capri"], row["fnat"],
                          row["iRMSD"], row["LRMSD"], row["fnonnat"], row["F1"], row["clashes"]]
                         for row in rows)
    print(f"Interface table: {output / 'interfaces.csv'}")


if __name__ == "__main__":
    arguments = proteiniq_job.parser(__doc__, "dockq-output")
    arguments.add_argument("--model", type=Path, help="Predicted or docked complex (PDB or mmCIF).")
    arguments.add_argument("--native", type=Path, help="Reference complex, usually an experimental structure.")
    arguments.add_argument("--chain-mapping", default="", help="Optional MODEL:NATIVE mapping, e.g. AB:AB.")
    args = arguments.parse_args()
    if not args.resume and (args.model is None or args.native is None):
        arguments.error("--model and --native are required for a new run.")
    proteiniq_job.main(args, lambda: make_request(args.model, args.native, args.chain_mapping), report)
