"""Extra 3: spin-density and ligand-field-orbital CUBE files from the retained ORCA 6.0.1 reference wavefunctions.

Post-processing only (orca_plot on copies of existing .gbw/.densities files; no SCF/CASSCF is run, sources are never
written). Needs `module load orca/6.0.1` (orca_plot, orca_2mkl) and numpy.

    python export_cubes.py CAMPAIGN_ROOT WORKDIR OUTDIR [SALT ...]
"""
import hashlib
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path

import numpy as np

EXPORTER_VERSION = "1.0.0"
CAMPAIGN, WORK, OUT = (Path(a).resolve() for a in sys.argv[1:4])
NGRID = 80          # orca_plot grid points per axis (default box: atoms +/- 7 bohr)
STRIDE = 2          # browser grid = every 2nd point of the original grid
ACTIVE = range(114, 119)  # 0-based MO slots of the 5 AILFT ligand-field eigenorbitals (verified per salt from the .lft.gbw energies)
SRC = {  # judged reference wavefunction folder per salt (relative to CAMPAIGN); SEED: see note
    "SEED": "calculations/orca_seed_rep2/reference",
    "R5_pI": "calculations/orca_R5_pI_cand02_gamma2/orca/reference",
    "R3_F": "calculations/orca_R3_F/cand00_gamma2/orca/reference",
    "R4_pCl": "calculations/orca_R4_pCl_cand00_gamma2/orca/reference",
    "R4_pBr": "calculations/orca_R4_pBr_cand02_gamma2/orca/reference",
}
JUDGED_INPUT = {  # the reference.inp the deposited couplings were computed from (same geometry + embedding required)
    "SEED": "gamma2/VOdmit2_ewald/orca/reference.inp",
    "R5_pI": "calculations/orca_R5_pI_cand02_gamma2/orca/reference.inp",
    "R3_F": "calculations/orca_R3_F/cand00_gamma2/orca/reference.inp",
    "R4_pCl": "calculations/orca_R4_pCl_cand00_gamma2_cut800/orca/reference.inp",
    "R4_pBr": "calculations/orca_R4_pBr_cand02_gamma2_cut800/orca/reference.inp",
}
SALTS = sys.argv[4:] or list(SRC)
D_LABELS = ["dz2", "dxz", "dyz", "dx2-y2", "dxy"]


def sha(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()


def orca_plot(cwd, gbw, script):
    r = subprocess.run(["bash", "-lc", f"module load orca/6.0.1 && orca_plot {gbw} -i"], input=script, text=True, cwd=cwd,
                       capture_output=True, timeout=1800)
    if "PLOTTING FINISHED" not in r.stdout:
        raise RuntimeError(r.stdout[-2000:] + r.stderr[-2000:])
    return re.findall(r"Output file: (\S+)", r.stdout)


def read_cube(p):
    lines = Path(p).read_text().splitlines()
    nat, *org = lines[2].split()
    nat = int(nat)
    ax = [lines[3 + i].split() for i in range(3)]
    n = [int(a[0]) for a in ax]
    vec = np.array([[float(x) for x in a[1:]] for a in ax])
    atoms = [lines[6 + i].split() for i in range(abs(nat))]
    h = 6 + abs(nat) + (1 if nat < 0 else 0)  # MO cubes: negative atom count + one 'n_mo mo_index' line
    data = np.array(" ".join(lines[h:]).split(), dtype=float).reshape(n)
    return dict(header=lines[:h], origin=np.array(org[:3], dtype=float), n=n, vec=vec, atoms=atoms, data=data)


def write_cube(p, cub, data, step_mult, title):
    n = data.shape
    out = [title, "browser grid: every %d-th point of the original orca_plot grid (same origin, bohr)" % step_mult,
           cub["header"][2]]
    for i in range(3):
        out.append(f"{n[i]:5d}" + "".join(f"{x * step_mult:12.6f}" for x in cub["vec"][i]))
    out += cub["header"][6:]
    flat = data.reshape(n[0] * n[1], n[2])
    for row in flat:
        for k in range(0, len(row), 6):
            out.append("".join(f"{x:13.5E}" for x in row[k:k + 6]))
    Path(p).write_text("\n".join(out) + "\n")


def iso_for_fraction(values, weights, frac):
    """Isovalue v such that the points with |values| >= v hold `frac` of sum(weights) (weights >= 0)."""
    order = np.argsort(-np.abs(values))
    c = np.cumsum(weights[order])
    return float(np.abs(values[order][np.searchsorted(c, frac * c[-1])]))


def lf_table(out_text, level):
    """The AILFT 'ligand field one electron eigenfunctions' table (energies cm-1 + d coefficients) of a level."""
    blk = out_text.split(f"AILFT MATRIX ELEMENTS ({level})")[1]
    rows = re.findall(r"^\s+([1-5])\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*$", blk.split("Ligand field orbitals were stored")[0], re.M)
    return [dict(lf_orbital=int(r[0]), energy_cm1=float(r[2]), d_coefficients=dict(zip(D_LABELS, map(float, r[3:])))) for r in rows]


def run(salt):
    src = CAMPAIGN / SRC[salt]
    w = WORK / salt
    w.mkdir(parents=True, exist_ok=True)
    files = ["reference.gbw", "reference.densities", "reference.densitiesinfo", "reference.nevpt2.lft.gbw", "reference.casscf.lft.gbw", "reference.out", "reference.inp"]
    for f in files:
        if not (w / f).exists():
            shutil.copy2(src / f, w / f)
    sources = {f: dict(original=str(SRC[salt] + "/" + f), sha256=sha(src / f), bytes=(src / f).stat().st_size) for f in files}
    same_input = sha(src / "reference.inp") == sha(CAMPAIGN / JUDGED_INPUT[salt])
    outt = (src / "reference.out").read_text(errors="replace")
    lf_nev, lf_cas = lf_table(outt, "NEVPT2"), lf_table(outt, "CASSCF")
    # verify the LF slots: the .lft.gbw orbital energies of MOs 114-118 must reproduce the AILFT eigenvalue gaps
    subprocess.run(["bash", "-lc", "module load orca/6.0.1 && orca_2mkl reference.nevpt2.lft -molden"], cwd=w, capture_output=True)
    ene = [float(x) for x in re.findall(r"Ene=\s*(\S+)", (w / "reference.nevpt2.lft.molden.input").read_text())]
    gaps = [(ene[i] - ene[ACTIVE[0]]) * 219474.6313705 for i in ACTIVE]
    slot_dev = max(abs(g - r["energy_cm1"]) for g, r in zip(gaps, lf_nev))
    assert slot_dev < 1.0, (salt, gaps, lf_nev)
    od = OUT / salt
    od.mkdir(parents=True, exist_ok=True)
    made = []
    # 1) state-specific spin density of CASSCF root 0 (spin-free, from the SA-CASSCF 2-RDM; ORCA density reference.mult.2.root.0.casscf.r)
    if not (w / "spin_root0.cube").exists():
        orca_plot(w, "reference.gbw", f"1\n3\nn\nreference.mult.2.root.0.casscf.r\n4\n{NGRID}\n11\n12\n")
        (w / "reference.spindens.cube").rename(w / "spin_root0.cube")
    made.append(("spin_density_root0", "spin_root0.cube", None))
    # 2) the five AILFT ligand-field eigenorbitals (NEVPT2 ordering), MOs 114-118 of reference.nevpt2.lft.gbw
    for k, mo in enumerate(ACTIVE):
        fn = f"lf{k + 1}_mo{mo}.cube"
        if not (w / fn).exists():
            orca_plot(w, "reference.nevpt2.lft.gbw", f"4\n{NGRID}\n2\n{mo}\n11\n12\n")
            (w / f"reference.nevpt2.lft.mo{mo}a.cube").rename(w / fn)
        made.append((f"lf_orbital_{k + 1}", fn, k))
    records = []
    spin = read_cube(w / "spin_root0.cube")
    dv = abs(np.linalg.det(spin["vec"]))
    for kind, fn, k in made:
        cub = read_cube(w / fn)
        assert cub["n"] == [NGRID] * 3 and np.allclose(cub["vec"], spin["vec"]) and np.allclose(cub["origin"], spin["origin"])
        d = cub["data"]
        assert np.isfinite(d).all()
        shutil.copy2(w / fn, od / fn)
        bfn = fn.replace(".cube", f"_browser_stride{STRIDE}.cube")
        write_cube(od / bfn, cub, d[::STRIDE, ::STRIDE, ::STRIDE], STRIDE, f"{salt} {kind} (browser grid)")
        if k is None:
            integral = float(d.sum() * dv)
            rec = dict(kind=kind, quantity="spin density rho_alpha - rho_beta (e / bohr^3)", sign="physical sign; within CAS(1,5) with doubly occupied inactive orbitals it is non-negative up to grid/print noise (min on grid %.3e)" % d.min(),
                       state="CASSCF root 0 (lowest doublet), state-specific density from the state-averaged SA-CASSCF(1,5) calculation (5 doublet roots, equal weights)",
                       spin_orbit="spin-free (no SOC); the SOC-mixed ground state is stored by ORCA only as an electron density (reference.root.0.cas.qdsoc.p / .pt.qdsoc.p), not as a spin density",
                       orca_density_name="reference.mult.2.root.0.casscf.r", grid_integral=integral,
                       suggested_isovalues=[iso_for_fraction(d.ravel(), np.clip(d.ravel(), 0, None), f) for f in (0.5, 0.8)],
                       isovalue_rule="isovalues enclosing 50% and 80% of the integrated positive spin density on this grid")
        else:
            r = lf_nev[k]
            cas = max(lf_cas, key=lambda c: abs(sum(c["d_coefficients"][x] * r["d_coefficients"][x] for x in D_LABELS)))
            w2 = {x: c ** 2 for x, c in r["d_coefficients"].items()}
            dom = sorted(w2.items(), key=lambda t: -t[1])
            norm = float((d ** 2).sum() * dv)
            rec = dict(kind=kind, quantity="orbital amplitude (bohr^-3/2)", sign="orbital phase is arbitrary (overall sign carries no meaning); show +/- lobes with the same |isovalue|",
                       orbital_type="AILFT ligand-field eigenorbital (active-space orbital rotated to diagonalise the fitted NEVPT2 ligand-field matrix); not a canonical, natural or SCF SOMO",
                       lf_orbital_nevpt2_order=k + 1, mo_slot_0based=list(ACTIVE)[k], nevpt2_lf_energy_cm1=r["energy_cm1"],
                       casscf_lf_orbital_same_vector=cas["lf_orbital"], casscf_lf_energy_cm1=cas["energy_cm1"],
                       ideal_d_coefficients=r["d_coefficients"], ideal_d_weights_sorted=[[x, v] for x, v in dom],
                       label_rule="largest ideal-d weights from ORCA's AILFT eigenvector table (metal frame: z = V=O axis, x/y as in the AILFT d basis)",
                       occupation_note=("CASSCF root 0 (ground doublet) maps onto LF root 0 with overlap 1.000; for d1 this is the single electron in LF orbital 1"
                                        if k == 0 else "empty in CASSCF root 0; occupied in the excited doublet that AILFT maps to it"),
                       sa_casscf_active_occupation=0.2, grid_norm_integral=norm,
                       suggested_isovalues=[iso_for_fraction(d.ravel(), d.ravel() ** 2, f) for f in (0.5, 0.8)],
                       isovalue_rule="|isovalue| enclosing 50% and 80% of the orbital's squared amplitude on this grid")
            if k == 0:
                rec["check_lf1_squared_vs_spin_root0"] = dict(max_abs_diff=float(np.abs(d ** 2 - spin["data"]).max()), max_spin=float(spin["data"].max()),
                                                              integral_abs_diff=float(np.abs(d ** 2 - spin["data"]).sum() * dv))
        rec.update(file=f"orbitals/{salt}/{fn}", browser_file=f"orbitals/{salt}/{bfn}", grid_points=cub["n"], grid_units="bohr (cube convention: positive point counts)",
                   origin_bohr=cub["origin"].tolist(), axis_vectors_bohr=cub["vec"].tolist(), browser_grid_points=[len(range(0, NGRID, STRIDE))] * 3,
                   value_precision="5 significant digits as written by orca_plot", sha256=sha(od / fn), browser_sha256=sha(od / bfn))
        records.append(rec)
    meta = dict(salt_id=salt, exporter_version=EXPORTER_VERSION, method=dict(
        reference="SA-CASSCF(1,5) over 5 doublet roots (equal weights) / SC-NEVPT2 / AILFT (actorbs dorbs) / SOC by RI-SOMF(1X) with QDPT; "
                  "def2-TZVP on V,O,S, def2-SVP elsewhere; Ewald-fitted point-charge embedding (orca/embedding.pc); ORCA 6.0.1",
        geometry="the embedded [VO(L)2]2- cluster of the deposited <salt>_anion_embedded_cluster.xyz / displacement manifest, metal frame (V at origin, z = V=O axis); "
                 "cube atom coordinates are in bohr in the same frame"),
        source_folder=SRC[salt], source_files=sources, wavefunction_input_identical_to_judged_reference=same_input, judged_reference_input=JUDGED_INPUT[salt],
        lf_slot_check_max_dev_cm1=slot_dev, ailft_nevpt2=lf_nev, ailft_casscf=lf_cas, cubes=records)
    if salt == "SEED":
        meta["note"] = ("The judged seed reference (gamma2/VOdmit2_ewald/orca) retained only reference.gbw. Cubes use the independent start-orbital "
                        "replicate (calculations/orca_seed_rep2/reference): byte-identical reference.inp (same geometry, basis, method) and embedding.pc; "
                        "final CASSCF energy identical (-5220.567651781 Eh in both outputs); NEVPT2 single-point energies differ by 2.4e-6 Eh; "
                        "NEVPT2 ligand-field levels agree within 0.6 cm-1.")
    (od / "cubes_metadata.json").write_text(json.dumps(meta, indent=1))
    print(salt, "done", [r["file"] for r in records], flush=True)


if __name__ == "__main__":
    for s in SALTS:
        run(s)
