"""Fixed-host g-xTB binding energies for CO2, N2 and CH4 in the CC3 cage.

Reads the structures written by co2-cage-build.py:

    python co2-cage-run.py --models ../models --output cc3-results
    python co2-cage-run.py --models ../models --output cc3-results --analyze-only
"""

import argparse
import json
from pathlib import Path

import numpy as np

from atomli import Atoms
from atomli.io import read

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


def combine(host, guest):
    return Atoms(host.get_chemical_symbols() + guest.get_chemical_symbols(),
                 positions=np.vstack([host.get_positions(), guest.get_positions()]))


def analyze(output):
    """Compare retained electronic populations with the host fixed."""
    electronic = {}
    for name in ('free-co2', 'co2', 'ch4', 'n2'):
        atoms = read(output / f'{name}.xyz')
        atoms.calc = calculator()
        electronic[name] = electronic_analysis(atoms, output / name,
            fragments={'guest': range(168, len(atoms))} if name != 'free-co2' else {'guest': range(3)})
    save_json(output / 'confinement.json', {
        'electronic': electronic,
        'hessian_status': 'Analytical g-xTB Hessian unavailable; no numerical derivative is used',
    })


def main():
    here = Path(__file__).resolve().parent
    parser = argparse.ArgumentParser()
    parser.add_argument("--models", type=Path, default=here.parent / "models")
    parser.add_argument("--output", type=Path, default=Path("cc3-results"))
    parser.add_argument("--analyze-only", action="store_true")
    args = parser.parse_args()
    if args.analyze_only:
        analyze(args.output)
        return
    host = read(args.models / "cc3-host-start.extxyz")
    args.output.mkdir(parents=True, exist_ok=True)

    host_energy = relax(host, fmax=0.05, output=args.output / 'host')
    save_structure(host, args.output / "host")
    records = []
    for name in ("CO2", "CH4", "N2"):
        guest = read(args.models / f"cc3-guest-{name.lower()}-start.extxyz")
        guest_energy = relax(guest, fmax=0.002, output=args.output / f'free-{name.lower()}')
        save_structure(guest, args.output / f"free-{name.lower()}")
        guest.set_positions(guest.get_positions() - guest.get_positions().mean(axis=0))
        complex_atoms = combine(host, guest)
        complex_energy = relax(complex_atoms, frozen=len(host), fmax=0.002, steps=500, output=args.output / name.lower())
        binding = complex_energy - host_energy - guest_energy
        records.append({"guest": name, "host_energy_ev": host_energy, "guest_energy_ev": guest_energy,
                        "complex_energy_ev": complex_energy, "binding_energy_ev": binding})
        (args.output / 'energies.json').write_text(json.dumps(records, indent=2) + '\n')
        save_structure(complex_atoms, args.output / name.lower())
    (args.output / "energies.json").write_text(json.dumps(records, indent=2) + "\n")
    analyze(args.output)


if __name__ == "__main__":
    main()
