"""Electronic analysis of the best thymol pose in beta-cyclodextrin at PBE/def2-SVP.

Reads the optimized complex written by cyclodextrin-run.py, runs PBE/def2-SVP
single points on the full 172-atom complex, on the host alone and on the guest
alone (both at the complex geometry), and writes numbers and sampled fields:

    python cyclodextrin-analysis.py --results ../results/cyclodextrin --work cd-analysis

Outputs in --work: analysis.json (all numbers) and fields.npz (sampled grids for
cyclodextrin-figures.py). Everything is a vertical, gas-phase calculation at the
g-xTB geometry. Hirshfeld charges are not computed (no reference atom densities).
"""

import argparse
import json
import time
from pathlib import Path

import numpy as np
from scipy.spatial import cKDTree

from atomli import Atoms
from atomli.analysis import Analysis
from atomli.calculators import QC
from atomli.analysis.reactivity import conceptual_dft_analysis
from atomli.io import read

HOST_ATOMS = 147
SPACING = 0.10  # angstrom, grid used for every integral
BOHR3 = 6.748334  # electron/bohr^3 -> electron/angstrom^3


def qc(charge=0, unpaired=0):
    kwargs = {"unpaired": unpaired} if unpaired else {}
    return QC(xc="PBE", basis="def2-SVP", charge=charge, device="cpu",
              convergence={"energy": 1e-7}, **kwargs)


def timed(label, function, log):
    start = time.monotonic()
    value = function()
    log[label] = time.monotonic() - start
    print(f"{label}: {log[label]:.1f} s", flush=True)
    return value


def fragment(atoms, indices):
    return Atoms([atoms.get_chemical_symbols()[i] for i in indices],
                 positions=atoms.get_positions()[indices])


def density_field(atoms, origin, axes, shape):
    return atoms.calc.analyze_fields(["electron_density"], origin=list(origin), axes=[list(a) for a in axes],
                                     shape=list(shape), charges=False, atoms=atoms)


def density_on(atoms, origin, axes, shape):
    field = density_field(atoms, origin, axes, shape)
    return np.asarray(field["fields"]["electron_density"]["values"], dtype=np.float64)


def frontier(atoms, label, log):
    session = Analysis(atoms)
    result = timed(label, lambda: session.conceptual_dft(method="frontier", charge_model="lowdin"), log)
    return result


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--results", type=Path, required=True)
    parser.add_argument("--work", type=Path, default=Path("cd-analysis"))
    parser.add_argument("--guest", default="thymol")
    parser.add_argument("--pose", type=int, default=2)
    parser.add_argument("--skip-mbis", action="store_true", help="skip the slow complex MBIS fit")
    args = parser.parse_args()
    args.work.mkdir(parents=True, exist_ok=True)
    complex_atoms = read(args.results / f"{args.guest}-{args.pose}.xyz")
    complex_atoms.set_pbc(False)
    n = len(complex_atoms)
    host_index, guest_index = np.arange(HOST_ATOMS), np.arange(HOST_ATOMS, n)
    log, out = {}, {"guest": args.guest, "pose": args.pose, "atoms": n,
                    "method": "PBE/def2-SVP, CPU, density fitting, at the g-xTB geometry",
                    "grid_spacing_angstrom": SPACING}
    positions = complex_atoms.get_positions()

    # complex
    complex_atoms.calc = qc()
    out["energy_complex_ev"] = timed("scf complex", complex_atoms.get_potential_energy, log)
    ext = np.ptp(positions, axis=0) + 2 * 3.0
    shape = [int(round(e / SPACING)) for e in ext]
    session = Analysis(complex_atoms, shape=shape, margin=3.0)
    grid = session.density_field()
    origin, axes = np.asarray(grid["origin"]), np.asarray(grid["axes"])
    shape = tuple(grid["shape"])
    voxel = abs(np.linalg.det(axes))
    rho_complex = np.asarray(grid["fields"]["electron_density"]["values"], dtype=np.float64)
    out["grid_shape"] = list(shape)
    out["electrons_expected"] = int(complex_atoms.get_atomic_numbers().sum())
    out["electrons_on_grid"] = float(rho_complex.sum() * voxel)

    # population charges on the complex
    charges = {"gxtb": None}
    recognition = json.loads((args.results / "recognition.json").read_text())[args.guest]
    charges["gxtb"] = np.asarray(recognition["electronic"]["charges_e"])
    for name in ("mulliken", "lowdin", "npa"):
        charges[name] = np.asarray(timed(name, lambda name=name: session.charges(name), log))
    bader = timed("bader", session.bader, log)
    charges["bader"] = np.asarray(bader.atom_charges)
    if not args.skip_mbis:
        mbis = timed("mbis", session.mbis, log)
        charges["mbis"] = np.asarray(mbis.atom_charges)
    out["charges"] = {k: v.tolist() for k, v in charges.items()}
    out["fragment_charge_e"] = {k: {"host": float(v[host_index].sum()), "guest": float(v[guest_index].sum())}
                                for k, v in charges.items()}
    out["bader_unassigned_electrons"] = float(bader.unassigned_electrons)
    out["bader_basin_count"] = int(bader.basin_count)
    out["symbols"] = complex_atoms.get_chemical_symbols()

    # frontier orbitals of the complex and condensed Fukui on the guest atoms
    ct = frontier(complex_atoms, "frontier complex", log)
    out["fukui_in_complex"] = {"plus": ct.fukui_plus[guest_index].tolist(), "minus": ct.fukui_minus[guest_index].tolist(),
                               "guest_share_plus": float(ct.fukui_plus[guest_index].sum()),
                               "guest_share_minus": float(ct.fukui_minus[guest_index].sum()),
                               "host_share_plus": float(ct.fukui_plus[host_index].sum()),
                               "host_share_minus": float(ct.fukui_minus[host_index].sum())}
    state = complex_atoms.calc.get_electronic_state(matrices=False)
    eig, occ = np.asarray(state["eigenvalues"]).ravel(), np.asarray(state["occupations"]).ravel()
    out["complex_homo_ev"] = float(eig[occ > 1e-6].max())
    out["complex_lumo_ev"] = float(eig[occ <= 1e-6].min())

    # NCI and QTAIM on the complex density, in a box around the guest
    gpos = positions[guest_index]
    lo, hi = gpos.min(axis=0) - 3.0, gpos.max(axis=0) + 3.0
    box_axes = np.eye(3) * SPACING
    box_origin = lo
    box_shape = [int(np.ceil((h - l) / SPACING)) for l, h in zip(lo, hi)]
    nci = timed("nci", lambda: session.nci(origin=box_origin.tolist(), axes=box_axes.tolist(), shape=box_shape,
                                           rdg_cutoff=0.5, rho_cutoff=0.35), log)
    rdg, slr = np.asarray(nci.rdg), np.asarray(nci.sign_lambda2_rho)
    out["nci"] = {"low_rdg_points": int(nci.low_rdg_points), "attractive_fraction": float(nci.attractive_fraction),
                  "vdw_fraction": float(nci.vdw_fraction), "steric_fraction": float(nci.steric_fraction),
                  "box_shape": box_shape}

    # three-fragment densities on the complex grid
    host = fragment(complex_atoms, host_index)
    guest = fragment(complex_atoms, guest_index)
    host.calc, guest.calc = qc(), qc()
    out["energy_host_ev"] = timed("scf host", host.get_potential_energy, log)
    out["energy_guest_ev"] = timed("scf guest", guest.get_potential_energy, log)
    out["interaction_energy_pbe_ev"] = out["energy_complex_ev"] - out["energy_host_ev"] - out["energy_guest_ev"]
    rho_host = timed("density host", lambda: density_on(host, origin, axes, shape), log)
    field_guest = timed("density guest", lambda: density_field(guest, origin, axes, shape), log)
    rho_guest = np.asarray(field_guest["fields"]["electron_density"]["values"], dtype=np.float64)
    # Grid integration of all-electron densities leaves a per-atom error. Evaluating the isolated
    # guest on the same grid gives the same error for the same atoms, so the difference isolates
    # the change on complexation.
    guest_session = Analysis(guest)
    iso = {"bader": np.asarray(guest_session.bader(field_data=field_guest).atom_charges)}
    if not args.skip_mbis:
        iso["mbis"] = np.asarray(guest_session.mbis(field_data=field_guest).atom_charges)
    out["isolated_guest_grid_charge_e"] = {k: {"atoms": v.tolist(), "sum": float(v.sum())} for k, v in iso.items()}
    out["guest_charge_change_e"] = {k: float(charges[k][guest_index].sum() - v.sum()) for k, v in iso.items()}
    out["guest_atom_charge_change_e"] = {k: (charges[k][guest_index] - v).tolist() for k, v in iso.items()}
    delta = rho_complex - rho_host - rho_guest
    out["delta_rho_integral_e"] = float(delta.sum() * voxel)
    # integrate the difference over the nearest-atom (Voronoi) cell of each fragment
    tree = cKDTree(positions)
    ijk = np.stack(np.meshgrid(*[np.arange(s) for s in shape], indexing="ij"), axis=-1).reshape(-1, 3)
    owner = np.empty(ijk.shape[0], dtype=np.int32)
    for start in range(0, ijk.shape[0], 1_000_000):
        points = origin + ijk[start:start + 1_000_000] @ axes
        owner[start:start + 1_000_000] = tree.query(points, workers=-1)[1]
    owner = owner.reshape(shape)
    guest_cell = owner >= HOST_ATOMS
    out["delta_rho_guest_cell_e"] = float(delta[guest_cell].sum() * voxel)
    out["delta_rho_host_cell_e"] = float(delta[~guest_cell].sum() * voxel)
    out["delta_rho_extrema_e_per_a3"] = [float(delta.min()), float(delta.max())]

    # isolated guest at the complex geometry: frontier Fukui and a finite-difference check
    cd = timed("frontier guest", lambda: guest_session.conceptual_dft(method="frontier", charge_model="lowdin"), log)
    out["fukui_guest"] = {"plus": cd.fukui_plus.tolist(), "minus": cd.fukui_minus.tolist(),
                          "dual": cd.dual_descriptor.tolist(),
                          "homo_ev": -cd.ionization_potential_ev, "lumo_ev": -cd.electron_affinity_ev,
                          "hardness_ev": cd.chemical_hardness_ev}
    q_neutral = np.asarray(guest_session.charges("lowdin"))
    cation, anion = fragment(complex_atoms, guest_index), fragment(complex_atoms, guest_index)
    cation.calc, anion.calc = qc(charge=1, unpaired=1), qc(charge=-1, unpaired=1)
    e_cat = timed("scf guest cation", cation.get_potential_energy, log)
    e_an = timed("scf guest anion", anion.get_potential_energy, log)
    q_cat = np.asarray(Analysis(cation).charges("lowdin"))
    q_an = np.asarray(Analysis(anion).charges("lowdin"))
    fd = conceptual_dft_analysis(neutral_energy_ev=out["energy_guest_ev"], cation_energy_ev=e_cat,
                                 anion_energy_ev=e_an, neutral_charges=q_neutral,
                                 cation_charges=q_cat, anion_charges=q_an)
    out["fukui_guest_delta_scf"] = {"plus": fd.fukui_plus.tolist(), "minus": fd.fukui_minus.tolist(),
                                    "ionization_potential_ev": fd.ionization_potential_ev,
                                    "electron_affinity_ev": fd.electron_affinity_ev}
    out["timing_s"] = log

    # sampled fields for the figures: full-resolution NCI box, 2x-strided for display
    near_guest = cKDTree(gpos)
    near_host = cKDTree(positions[host_index])
    ii = np.stack(np.meshgrid(*[np.arange(s) for s in box_shape], indexing="ij"), axis=-1).reshape(-1, 3)
    pts = box_origin + ii @ box_axes
    d_guest = near_guest.query(pts, workers=-1)[0].reshape(box_shape)
    d_host = near_host.query(pts, workers=-1)[0].reshape(box_shape)
    hb = recognition["hydrogen_bonds"]
    np.savez_compressed(
        args.work / "fields.npz", box_origin=box_origin, box_spacing=SPACING, rdg=rdg.astype(np.float32),
        slr=slr.astype(np.float32), d_guest=d_guest.astype(np.float32), d_host=d_host.astype(np.float32),
        delta=delta.astype(np.float32), origin=origin, axes=axes, positions=positions,
        symbols=np.array(complex_atoms.get_chemical_symbols()), hbond=np.array(
            [[h["donor"], h["hydrogen"], h["acceptor"]] for h in hb], dtype=int).reshape(-1, 3))
    (args.work / "analysis.json").write_text(json.dumps(out, indent=2) + "\n")
    print("done")


if __name__ == "__main__":
    main()
