"""Optimize beta-cyclodextrin, two guests and eight guest poses with g-xTB on the GPU.

Reads the files written by cyclodextrin-build.py and writes the relaxed structures,
optimizer logs and poses.json (binding energies):

    python cyclodextrin-run.py --models ../models/cyclodextrin --output cyclodextrin-results
"""

import argparse
import json
from pathlib import Path

import numpy as np

from atomli.io import read

from chemical_analysis import electronic_analysis, hydrogen_bonds, save_json
from host_guest import calculator, combine, relax, save_structure

HOST_ATOMS = 147


def screen_best_poses(output):
    """g-xTB fragment charges and the O-H...O contact screen for the best pose of each guest."""
    records = json.loads((output / "poses.json").read_text())
    analysis = {}
    for guest in ("thymol", "carvacrol"):
        rows = [row for row in records if row["guest"] == guest]
        best = min(rows, key=lambda row: row["binding_energy_ev"])
        prefix = output / f"{guest}-{best['pose']}"
        atoms = read(prefix.with_suffix(".xyz"))
        atoms.calc = calculator()
        state = electronic_analysis(atoms, prefix, fragments={"host": range(HOST_ATOMS), "guest": range(HOST_ATOMS, len(atoms))})
        analysis[guest] = {"best_pose": best["pose"], "binding_energy_ev": best["binding_energy_ev"],
                           "pose_spread_ev": max(row["binding_energy_ev"] for row in rows) - best["binding_energy_ev"],
                           "electronic": state, "hydrogen_bonds": hydrogen_bonds(atoms, HOST_ATOMS)}
    save_json(output / "recognition.json", analysis)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--models", type=Path, required=True)
    parser.add_argument("--output", type=Path, default=Path("cyclodextrin-results"))
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    rotations = [np.array(r) for r in json.loads((args.models / "rotations.json").read_text())]
    host = read(args.models / "host-start.xyz")
    host_energy = relax(host, output=args.output / "fixed-host", steps=500)
    save_structure(host, args.output / "fixed-host")
    records = []
    for name in ("thymol", "carvacrol"):
        guest = read(args.models / f"{name}-start.xyz")
        guest_energy = relax(guest, output=args.output / f"free-{name}")
        save_structure(guest, args.output / f"free-{name}")
        coordinates = np.asarray(guest.get_positions())
        coordinates -= coordinates.mean(axis=0)
        for index, rotation in enumerate(rotations):
            pose = guest.copy()
            pose.set_positions(coordinates @ rotation.T)
            atoms = combine(host, pose)
            energy = relax(atoms, frozen=HOST_ATOMS, output=args.output / f"{name}-{index}")
            records.append({"guest": name, "pose": index, "host_energy_ev": host_energy,
                            "guest_energy_ev": guest_energy, "complex_energy_ev": energy,
                            "binding_energy_ev": energy - host_energy - guest_energy})
            (args.output / "poses.json").write_text(json.dumps(records, indent=2) + "\n")
            save_structure(atoms, args.output / f"{name}-{index}")
    screen_best_poses(args.output)


if __name__ == "__main__":
    main()
