"""Build linked figures from recorded protein relaxation, MD, and local forces."""
import argparse
import json
from pathlib import Path

import numpy as np

from atomli.biomol import select, validate
from atomli.io import read, write
from atomli.visualize import Study, Viewer, plot


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")


def layers(atoms):
    ligand = select(atoms, resname="BEN")
    ions = select(atoms, element="Ca")
    protein = sorted(set(range(len(atoms))) - set(ligand) - set(ions))
    return {name: indices for name, indices in (
        ("Protein", protein), ("Benzamidinium", ligand), ("Ions", ions),
    ) if indices}


def backbone_frames(frames):
    atoms = frames[0]
    indices = sorted(set(select(atoms, name="CA", hetero=False)
                         + select(atoms, resname="BEN") + select(atoms, element="Ca")))
    return [frame[indices] for frame in frames]


def trajectory_viewer(frames):
    return Viewer(frames, height=450, look={
        "layers": layers(frames[0]), "proteinRepresentation": "cartoon",
        "labels": False, "cell": False, "legend": False,
    }).set_fps(8).pause()


def trace_plot(rows, *, relaxation, threshold):
    x = [row["step"] if relaxation else row["time_fs"] for row in rows]
    states = [f"sample-{i}" for i in range(len(rows))]
    energy = np.array([row["energy_ev"] for row in rows])
    values = [row["fmax_ev_per_angstrom"] if relaxation else row["temperature_k"] for row in rows]
    traces = [
        {"type": "scatter", "mode": "lines+markers", "x": x,
         "y": (energy - energy[0]).tolist(), "customdata": states,
         "name": "Potential energy change", "line": {"color": "#38739b"}, "marker": {"size": 5}},
        {"type": "scatter", "mode": "lines+markers", "x": x, "y": values,
         "customdata": states, "name": "Maximum force" if relaxation else "Temperature",
         "xaxis": "x2", "yaxis": "y2", "line": {"color": "#b16a35"}, "marker": {"size": 5}},
    ]
    layout = {
        "showlegend": False, "margin": {"l": 70, "r": 20, "t": 45, "b": 48},
        "xaxis": {"anchor": "y", "showticklabels": False},
        "yaxis": {"domain": [0.58, 1.0], "title": {"text": "ΔEpot (eV)"}},
        "xaxis2": {"anchor": "y2", "title": {"text": "FIRE step" if relaxation else "Time (fs)"}},
        "yaxis2": {"domain": [0, 0.40], "title": {"text": "Fmax (eV/Å)" if relaxation else "T (K)"}},
        "shapes": [{"type": "line", "xref": "x2 domain", "x0": 0, "x1": 1, "yref": "y2",
                    "y0": threshold, "y1": threshold, "line": {"color": "#74818b", "dash": "dot"}}],
    }
    if relaxation:
        layout["yaxis2"]["type"] = "log"
        layout["yaxis2"]["tickvals"] = [0.05, 0.1, 0.5, 1, 5]
        layout["yaxis2"]["ticktext"] = ["0.05", "0.1", "0.5", "1", "5"]
    return plot.plotly({"data": traces, "layout": layout},
                       title="Protein relaxation" if relaxation else "Protein NVT dynamics", height=450)


def trajectory_study(output, name, frames, rows, report, *, relaxation):
    if len(frames) != len(rows) or len(rows) < 2:
        raise ValueError("Each recorded trajectory frame requires one scalar sample")
    compact = backbone_frames(frames)
    study = (Study(name, "Trypsin relaxation" if relaxation else "Trypsin NVT dynamics",
                   system="3PTB trypsin, benzamidinium, and calcium", method=report["model"])
             .figure("trace", trace_plot(rows, relaxation=relaxation,
                                        threshold=report["force_threshold_ev_per_angstrom"] if relaxation else report["temperature_k"]),
                     height=450, caption="Click a measured point to select its geometry.")
             .figure("geometry", trajectory_viewer(compact), height=450,
                     caption="Cα trace, complete ligand, and calcium. All atoms enter the calculation."))
    if relaxation:
        study.fact("steps", report["relaxation"]["steps"], label="FIRE steps")
        study.fact("fmax", rows[-1]["fmax_ev_per_angstrom"], "eV/Å", label="Final maximum force", precision=4)
        study.fact("energy_change", rows[-1]["energy_ev"] - rows[0]["energy_ev"],
                   "eV", label="Energy change", precision=2)
        labels = {f"sample-{i}": f"Step {row['step']} · Fmax {row['fmax_ev_per_angstrom']:.4f} eV/Å"
                  for i, row in enumerate(rows)}
    else:
        study.fact("duration", rows[-1]["time_fs"], "fs", label="Trajectory duration", precision=0)
        study.fact("target_temperature", report["temperature_k"], "K", label="Thermostat target", precision=0)
        study.fact("last_temperature", rows[-1]["temperature_k"], "K", label="Final temperature", precision=1)
        labels = {f"sample-{i}": f"{row['time_fs']:.0f} fs · {row['temperature_k']:.1f} K"
                  for i, row in enumerate(rows)}
    study.link("sample", source="trace", target="geometry",
               states={f"sample-{i}": i for i in range(len(rows))}, labels=labels)
    study.provenance("Coordinates and traces", f"{report['model']} on {report['device']}; recorded native Atomli drivers")
    study.provenance("Model scope", "Workflow demonstration; protein accuracy is unvalidated")
    study.write(output / "studies" / name)


def region_study(output, local, report):
    analysis = report["analysis"]
    forces = np.asarray(analysis["forces_ev_per_angstrom"])
    if forces.shape != (len(local), 3):
        raise ValueError("Local forces must match the cluster atom order")
    norms = np.linalg.norm(forces, axis=1)
    caps = sorted({i for cap in analysis["cluster"]["caps"] for i in cap["added_atoms"]})
    ligand = select(local, resname="BEN")
    pocket = sorted(set(range(len(local))) - set(caps) - set(ligand))
    colors = ["#d58a27" if i in caps else None for i in range(len(local))]
    look = {"layers": {name: indices for name, indices in
                       (("Pocket", pocket), ("Benzamidinium", ligand), ("Caps", caps)) if indices},
            "atomColors": colors, "colorLegend": {"#d58a27": "ACE/NME caps"},
            "labels": False, "cell": False, "legend": True}
    strongest = np.argsort(norms)[-12:]
    topology = local.topology
    labels = []
    for i in strongest:
        atom = topology["atoms"][int(i)]
        residue = topology["residues"][atom["residue"]]
        labels.append(f"{residue['name']}{residue['sequence']}:{atom['name']}")
    method = "g-xTB" if analysis["method"] == "gxtb" else f"{analysis['xc']}/{analysis['basis']}"
    figure = plot.plotly({"data": [{
        "type": "bar", "orientation": "h", "x": norms[strongest].tolist(), "y": labels,
        "customdata": [f"atom-{i}" for i in strongest],
        "marker": {"color": ["#d58a27" if int(i) in caps else "#38739b" for i in strongest]},
    }], "layout": {"margin": {"l": 125, "r": 15, "t": 45, "b": 50},
                  "xaxis": {"title": {"text": "Force norm (eV/Å)"}}, "yaxis": {"type": "category"}}},
        title=f"Largest local {method} forces", height=470)
    study = (Study("protein-region", "Capped trypsin pocket", method=analysis["method"])
             .fact("atoms", len(local), label="Cluster atoms")
             .fact("charge", analysis["cluster"]["formal_charge"], "e", label="Formal charge")
             .fact("caps", len(analysis["cluster"]["caps"]), label="Peptide caps")
             .figure("forces", figure, height=470, caption="Select a bar to locate its atom.")
             .figure("cluster", Viewer([local], look=look), height=470,
                     caption="Benzamidinium and the receptor pocket. ACE/NME caps are amber."))
    study.link("atom", source="forces", target="cluster",
               states={f"atom-{i}": Viewer([local], look=look).select([int(i)]) for i in strongest},
               labels={f"atom-{i}": f"{label} · |F| = {norms[i]:.3f} eV/Å" for i, label in zip(strongest, labels)})
    study.provenance("Forces", f"{analysis['method']} analytical forces on the isolated post-MD capped cluster")
    study.provenance("Geometry", f"{report['model']} trajectory; caps added after region extraction")
    study.write(output / "studies/protein-region")


def build(run, output):
    run, output = Path(run), Path(output)
    report = json.loads((run / "run.json").read_text())
    if report["status"] != "complete" or not report["relaxation"]["converged"]:
        raise ValueError("Figures require a completed run and converged relaxation")
    relaxation = read(run / "relaxation.h5", ":")
    dynamics = read(run / "trajectory.h5", ":")
    local = read(run / "analysis-cluster.h5")
    for atoms in (relaxation[-1], dynamics[-1], local):
        validate(atoms)
    trajectory_study(output, "protein-relaxation", relaxation, report["relaxation"]["trace"], report, relaxation=True)
    trajectory_study(output, "protein-dynamics", dynamics, report["md_trace"], report, relaxation=False)
    region_study(output, local, report)
    data = output / "examples/biomol"
    write(data / "relaxed.mmcif", relaxation[-1])
    write(data / "md-final.mmcif", dynamics[-1])
    write_json(data / "simulation.json", report)
    return report


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--run", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    build(args.run, args.output)
