"""Extra 4: candidate-level alternative-packing records from the campaign's CSP funnels (CLARI -> UMA -> selection -> DFT).

Reads existing records only (no new packings, relaxations or energies):
  <campaign>/calculations/clari_<salt>[/workflow]/   the 11 loop funnels (R6_* folders are byte-identical copies of the
                                                     screen funnels S_4CCH / S_3Br and are reported as aliases)
  /project/igustin/QECT/flat_ligand_screen/S_*/      the 11-cation flat-ligand screen
  <campaign>/calculations/periodic_dft_<salt>/       DFT (CP2K) relaxations of shortlisted packings

    python export_packings.py CAMPAIGN_ROOT SCREEN_ROOT RELEASE OUTDIR
"""
import csv
import glob
import hashlib
import importlib.util
import io
import json
import re
import sys
from pathlib import Path

import numpy as np
import pandas as pd

EXPORTER_VERSION = "1.0.0"
CAMPAIGN, SCREEN, RELEASE, OUT = (Path(a).resolve() for a in sys.argv[1:5])
EV_TO_KJ_MOL = 96.48533212331002
HARTREE_TO_KJ_MOL = 2625.4996394798254
TOP_N = 15
LOOP = ["R2_AsPh4", "R2_NBu4", "R2_NEt4", "R3_CN", "R3_F", "R4_mF", "R4_pBr", "R4_pCl", "R5_pCl2", "R5_pCl4", "R5_pI"]
SCREEN_NAMES = {"S_2Br": "ortho-Br", "S_2Cl": "ortho-Cl", "S_2F": "ortho-F", "S_2Naph": "2-naphthyl", "S_3Br": "meta-Br", "S_3Cl": "meta-Cl",
                "S_4CCH": "para-ethynyl", "S_4NO2": "para-NO2", "S_4Ph": "para-phenyl", "S_PPN": "PPN+ counterion", "S_pClAs": "para-Cl on As core"}
ALIAS = {"S_4CCH": "R6_4CCH", "S_3Br": "R6_mBr"}  # screen funnels promoted to round 6 (clari_R6_* are identical copies)
SKIP_DFT = re.compile(r"imag|probe|phonons|disp-|sp_mode|grid_offset|equilibrium|_diag|mode_recovery|tests")

spec = importlib.util.spec_from_file_location("fold_screen", SCREEN / "fold_screen.py")
fold_screen = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fold_screen)  # the screen's own fold readout (max dithiolene fold per anion)


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


def fmt(x):
    return "" if x is None or (isinstance(x, float) and not np.isfinite(x)) else (repr(float(x)) if isinstance(x, (float, np.floating)) else str(x))


def max_fold(cif_text):
    from ase.io import read
    at = read(io.StringIO(cif_text), format="cif")
    f = fold_screen.folds(at)
    return float(max(f)) if f else None


def protocol_key(inp):
    t = Path(inp).read_text(errors="replace")
    g = lambda pat: (re.search(pat, t, re.I | re.M).group(1) if re.search(pat, t, re.I | re.M) else "")  # noqa: E731
    basis = sorted(set(re.findall(r"BASIS_SET\s+(\S+)", t)))
    fam = sorted({re.sub(r"-q\d+$", "", b) for b in basis})
    return dict(xc=g(r"&XC_FUNCTIONAL\s+(\S+)"), dispersion=g(r"TYPE\s+(DFTD\d\S*)"), cutoff_ry=g(r"^\s*CUTOFF\s+(\S+)"), rel_cutoff_ry=g(r"REL_CUTOFF\s+(\S+)"),
                finer_xc_grid=g(r"USE_FINER_GRID\s+(\S+)").upper(), basis_family=";".join(fam), kpoints=g(r"SCHEME\s+(.+)$").strip(), run_type=g(r"RUN_TYPE\s+(\S+)"))


def dft_runs(salt_dft_dir, atoms_per_fu):
    """Every completed CP2K relaxation under periodic_dft_<salt>/<label>[/<protocol>] (probes, phonon and diagnostic runs skipped)."""
    runs = []
    for res in sorted(glob.glob(str(salt_dft_dir / "**" / "periodic_crystal_results.json"), recursive=True)):
        jd = Path(res).parent
        rel = jd.relative_to(salt_dft_dir).as_posix()
        if SKIP_DFT.search(rel):
            continue
        r = json.loads(Path(res).read_text())
        if r.get("calculation") not in ("cell_opt", "geo_opt"):
            continue
        first = rel.split("/")[0]
        ml = re.match(r"(cand\d+.*?s\d{6})", first)
        label = ml.group(1) if ml else first  # continuation folders (_cont1, _resume...) belong to the same candidate
        m = re.search(r"s(\d{6})", label)
        mr = re.search(r"_r(\d)_", label)
        nat = (r.get("results") or {}).get("forces", {}).get("atoms")
        e = (r.get("results") or {}).get("energy_hartree")
        fs = r.get("final_structure") or {}
        inp = jd / "cp2k_crystal_stage2.inp" if (r.get("chain") or {}).get("stage") == 2 and (jd / "cp2k_crystal_stage2.inp").exists() else jd / "cp2k_crystal.inp"
        key = protocol_key(inp) if inp.exists() else {}
        fu = nat / atoms_per_fu if (nat and atoms_per_fu) else None
        outs = sorted(list(jd.glob("cp2k_crystal.out")) + list(jd.glob("cp2k_crystal.part*.out")), key=lambda p: p.stat().st_mtime)
        last_e, n_done, latest = None, 0, None
        if outs:
            latest = outs[-1]
            t = latest.read_text(errors="replace")
            es = re.findall(r"ENERGY\| Total FORCE_EVAL.*?:\s+(\S+)", t)
            last_e = float(es[-1]) if es else None
            n_done = t.count("OPTIMIZATION COMPLETED")
        runs.append(dict(label=label, run_dir=str(jd.relative_to(CAMPAIGN)), sample_idx=int(m.group(1)) if m else None, run=int(mr.group(1)) if mr else None,
                         status=r.get("status"), converged=r.get("converged"), stationary=fs.get("stationary"), calculation=r.get("calculation"),
                         n_atoms=nat, formula_units=fu, energy_hartree=e, energy_hartree_per_fu=(e / fu if (e is not None and fu) else None),
                         protocol=key, protocol_key="|".join(f"{k}={key.get(k, '')}" for k in ("xc", "dispersion", "cutoff_ry", "rel_cutoff_ry", "finer_xc_grid", "basis_family")),
                         identity_preserved=(fs.get("identity") or {}).get("preserved"), final_cif=(str((CAMPAIGN / fs["cif"]).relative_to(CAMPAIGN)) if fs.get("cif") and (CAMPAIGN / fs["cif"]).exists() else None),
                         results_sha256=sha(res), cp2k_latest_output=latest.name if latest else None, cp2k_last_energy_hartree=last_e,
                         cp2k_latest_output_has_optimization_completed=bool(n_done)))
    return runs


def t1_models():
    """crystal model -> phonopy original path (deposited inputs.json): identifies the packing each T1 model was computed from."""
    out = {}
    for f in glob.glob(str(RELEASE / "inputs" / "*" / "inputs.json")):
        d = json.loads(Path(f).read_text())
        out[d["salt"]] = d["files"]["phonopy_params"]["original"]
    return out


def main():
    rows, structs, dft_rows, summary = [], [], [], []
    t1 = t1_models()
    sdir = OUT / "packings" / "structures"
    sdir.mkdir(parents=True, exist_ok=True)
    funnels = [(s, CAMPAIGN / "calculations" / f"clari_{s}", "campaign_loop_csp") for s in LOOP] + \
              [(s, SCREEN / s, "flat_ligand_screen") for s in SCREEN_NAMES]
    for salt, fdir, pop in funnels:
        base = fdir / "workflow" if (fdir / "workflow").is_dir() else fdir
        ws = json.loads((base / "workflow_state.json").read_text())
        smiles = ws["params"]["smiles"]
        sel = json.loads((base / "select" / "dft_candidates_manifest.json").read_text()) if (base / "select" / "dft_candidates_manifest.json").exists() else None
        pre = json.loads((base / "dft_input" / "dft_candidates_manifest.json").read_text()) if (base / "dft_input" / "dft_candidates_manifest.json").exists() else None
        fe = json.loads((base / "select" / "uma_free_energy" / "uma_free_energy.json").read_text()) if (base / "select" / "uma_free_energy" / "uma_free_energy.json").exists() else None
        allsamp = pd.read_csv(base / "select" / "all_samples.csv") if (base / "select" / "all_samples.csv").exists() else None
        zdirs = sorted((base / "clari").glob("z*"), key=lambda p: int(p.name[1:].split("-")[0]))
        runs_by_dir = {Path(r["dir"]).parent.name: r["run"] for r in (sel or {}).get("summary", {}).get("pooled_runs", [])}
        cands = {c["label"]: c for c in (sel or {}).get("candidates", [])}
        cand_by_sample = {(c["run"], c["sample_idx"]): c for c in cands.values()}
        dups = {}
        for c in cands.values():
            for dd in c.get("duplicates") or []:
                key = (dd.get("run"), dd.get("sample_idx")) if isinstance(dd, dict) else None
                if key:
                    dups[key] = c["label"]
        fe_rank = {r["label"]: r for r in ((fe or {}).get("ranking") or {}).get("300K", [])}
        fe_cand = {c["label"]: c for c in (fe or {}).get("candidates", [])}
        pre_labels = {c["label"] for c in (pre or {}).get("candidates", [])}
        alias = ALIAS.get(salt)
        dsalt = alias or salt
        ddir = CAMPAIGN / "calculations" / f"periodic_dft_{dsalt}"
        atoms_per_fu = None
        recs = []
        for z in zdirs:
            cfg = json.loads((z / "config.json").read_text())
            comp = cfg["requests"][0]["smiles"]
            fu = [n for smi, n in comp if "V" in smi][0]
            rel = pd.read_csv(z / "uma_relaxed" / "relaxations.csv")
            up = pd.read_parquet(z / "uma_relaxed" / "predictions.parquet") if (z / "uma_relaxed" / "predictions.parquet").exists() else pd.DataFrame(columns=["sample_idx", "cif"])
            relaxed_cif = dict(zip(up["sample_idx"], up["cif"]))
            run = runs_by_dir.get(z.name)
            for _, r in rel.iterrows():
                si = int(r["sample_idx"])
                a = allsamp[(allsamp["run"] == run) & (allsamp["sample_idx"] == si)] if (allsamp is not None and run is not None) else pd.DataFrame()
                rec = dict(candidate_id=f"{salt}:Z{fu}:s{si:06d}", salt_id=salt, campaign_salt_alias=alias or "", population=pop,
                           counterion_label=SCREEN_NAMES.get(salt, salt), salt_smiles=smiles, formula_units_per_cell=fu, clari_run_folder=str(z.relative_to(fdir.parent)),
                           clari_sample_index=si, pooled_run_index=run, uma_relaxation_status=r["status"], uma_converged=bool(r["converged"]), uma_steps=(int(r["steps"]) if pd.notna(r["steps"]) else None),
                           uma_final_energy_eV_per_cell=float(r["final_energy_ev"]), uma_final_energy_eV_per_fu=float(r["final_energy_ev"]) / fu,
                           uma_final_max_force_eV_per_A=float(r["final_max_force_ev_per_a"]), volume_A3_per_fu=float(r["final_volume_a3"]) / fu,
                           min_interatomic_distance_A=float(r["minimum_distance_a"]), uma_error=("" if pd.isna(r.get("error")) else str(r.get("error"))), uma_relaxed_structure_available=si in relaxed_cif,
                           identity_ok=(bool(a["identity_ok"].iloc[0]) if len(a) else None), spacegroup=(a["spacegroup"].iloc[0] if len(a) else None),
                           density_g_cm3=(float(a["density_g_cm3"].iloc[0]) if len(a) else None), _cif=relaxed_cif.get(si))
                c = cand_by_sample.get((run, si))
                rec["shortlist_label"] = c["label"] if c else ""
                rec["uma_rel_kj_mol_per_fu_reported"] = c["uma_rel_kj_mol_per_fu"] if c else None
                recs.append(rec)
        checked = allsamp is not None  # R2_NBu4: funnel stopped after UMA relaxation, no selection stage -> identity never checked
        ok = [x for x in recs if x["uma_converged"] and (x["identity_ok"] if checked else True) and np.isfinite(x["uma_final_energy_eV_per_fu"])]
        for x in recs:
            x["identity_checked"] = checked
        emin = min(x["uma_final_energy_eV_per_fu"] for x in ok) if ok else None
        for k, x in enumerate(sorted(ok, key=lambda x: x["uma_final_energy_eV_per_fu"])):
            x["uma_rank_within_salt"] = k
            x["uma_delta_E_kJ_mol_per_fu"] = (x["uma_final_energy_eV_per_fu"] - emin) * EV_TO_KJ_MOL
        runs = dft_runs(ddir, None) if ddir.is_dir() else []
        # atoms per formula unit from a shortlisted candidate (formula + Z), then re-derive FU for every DFT run
        if cands:
            c0 = next(iter(cands.values()))
            atoms_per_fu = c0["n_atoms"] / c0["formula_units"]
            runs = dft_runs(ddir, atoms_per_fu) if ddir.is_dir() else []
        # DFT energies ranked only within one protocol key, over converged + stationary runs; per candidate keep its lowest such run
        best = {}
        for rr in runs:
            if rr["converged"] and rr["stationary"] is not False and rr["energy_hartree_per_fu"] is not None and rr["formula_units"] and abs(rr["formula_units"] - round(rr["formula_units"])) < 1e-6:
                k = (rr["label"], rr["protocol_key"])
                if k not in best or rr["energy_hartree_per_fu"] < best[k]["energy_hartree_per_fu"]:
                    best[k] = rr
        by_key = {}
        for (lab, pk), rr in best.items():
            by_key.setdefault(pk, []).append(rr)
        for pk, lst in by_key.items():
            e0 = min(r["energy_hartree_per_fu"] for r in lst)
            for r in lst:
                r["delta_E_dft_kJ_mol_per_fu"] = (r["energy_hartree_per_fu"] - e0) * HARTREE_TO_KJ_MOL
                r["n_compared_in_protocol"] = len(lst)
        t1_path = t1.get(dsalt, "")
        for rr in runs:
            dft_rows.append(dict(salt_id=salt, campaign_salt_id=dsalt, candidate_label=rr["label"], run_dir=rr["run_dir"], calculation=rr["calculation"], status=rr["status"],
                                 converged=rr["converged"], stationary=rr["stationary"], identity_preserved=rr["identity_preserved"], n_atoms=rr["n_atoms"],
                                 formula_units=fmt(rr["formula_units"]), energy_hartree=fmt(rr["energy_hartree"]), energy_hartree_per_fu=fmt(rr["energy_hartree_per_fu"]),
                                 protocol_key=rr["protocol_key"], kpoints=rr["protocol"].get("kpoints", ""),
                                 delta_E_dft_kJ_mol_per_fu_same_protocol=fmt(rr.get("delta_E_dft_kJ_mol_per_fu")) if best.get((rr["label"], rr["protocol_key"])) is rr else "",
                                 ranking_note=("ranked against %d candidate(s) with the same protocol key" % rr["n_compared_in_protocol"]) if best.get((rr["label"], rr["protocol_key"])) is rr
                                 else "not ranked: " + ("not converged/stationary" if not (rr["converged"] and rr["stationary"] is not False) else "higher-energy duplicate run of the same candidate and protocol"),
                                 t1_model_phonon_source=t1_path if t1_path.split("/")[2:3] == [rr["label"]] else "",
                                 final_structure=rr["final_cif"] or "", results_sha256=rr["results_sha256"],
                                 status_source="periodic_crystal_results.json as last collected (a 'running' status can be a stale snapshot of a chain stopped later)",
                                 cp2k_latest_output=rr["cp2k_latest_output"] or "", cp2k_last_energy_hartree_informational=fmt(rr["cp2k_last_energy_hartree"]),
                                 cp2k_latest_output_has_optimization_completed=rr["cp2k_latest_output_has_optimization_completed"]))
        dft_labels = {r["label"] for r in runs}
        for x in recs:
            lab = x["shortlist_label"]
            key = (x["pooled_run_index"], x["clari_sample_index"])
            if not x["uma_converged"]:
                st, why = "rejected", f"UMA relaxation {x['uma_relaxation_status']} (selection requires converged)"
            elif x["identity_ok"] is False:
                st, why = "rejected", "molecular identity broken after UMA relaxation"
            elif not checked:
                st, why = "not_evaluated", "funnel stopped after UMA relaxation (no selection stage in workflow_state.json); molecular identity not checked; ranked on UMA energy only"
            elif x["identity_ok"] is None:
                st, why = "not_evaluated", "not in the funnel's ranked table (all_samples.csv)"
            elif lab:
                st, why = "shortlisted", f"within {sel['summary']['filters']['energy_window_kj_mol_per_fu']} kJ/mol/FU UMA window after dedup (rank {cands[lab]['uma_rank']})"
            elif key in dups:
                st, why = "rejected", f"duplicate packing of {dups[key]} (pymatgen StructureMatcher ltol/stol/angle {sel['summary']['filters']['dedup']})"
            elif x.get("uma_delta_E_kJ_mol_per_fu") is not None and x["uma_delta_E_kJ_mol_per_fu"] > sel["summary"]["filters"]["energy_window_kj_mol_per_fu"]:
                st, why = "rejected", f"outside the {sel['summary']['filters']['energy_window_kj_mol_per_fu']} kJ/mol/FU UMA energy window"
            else:
                st, why = "not_shortlisted", "inside the energy window but not shortlisted; the funnel recorded no per-sample reason (dedup or max-candidate limit)"
            x["selection_status"], x["selection_reason"] = st, why
            f = fe_rank.get(lab)
            x["uma_free_energy_300K_rel_kJ_mol_per_fu"] = f["rel_free_energy_kj_mol_per_fu"] if f else None
            x["uma_lattice_energy_rel_kJ_mol_per_fu_fe_stage"] = f["rel_lattice_energy_kj_mol_per_fu"] if f else None
            fc = fe_cand.get(lab)
            x["uma_free_energy_300K_kJ_mol_per_fu"] = (fc["thermodynamics"][0]["free_energy_kJ_mol"] / fc["formula_units"]) if fc else None
            x["uma_fe_min_mesh_frequency_cm1"] = fc.get("min_mesh_frequency_cm1") if fc else None
            x["passed_uma_free_energy_prefilter_to_dft"] = (lab in pre_labels) if (lab and pre is not None) else None
            x["dft_relaxed"] = lab in dft_labels if lab else False
            bests = [r for (l2, pk), r in best.items() if l2 == lab]
            x["dft_delta_E_kJ_mol_per_fu"] = "; ".join(f"{r['delta_E_dft_kJ_mol_per_fu']!r} [{r['protocol_key']}; n={r['n_compared_in_protocol']}]" for r in bests) if bests else ""
            x["t1_crystal_model"] = dsalt if (lab and t1_path.split("/")[2:3] == [lab]) else ""
        # structures: top-N UMA packings (relaxed CIF) + DFT finals
        top = [x for x in sorted(ok, key=lambda x: x["uma_final_energy_eV_per_fu"])][:TOP_N]
        for x in top:
            if not x["_cif"]:
                continue
            fn = sdir / salt / (x["candidate_id"].replace(":", "_") + "_uma_relaxed.cif")
            fn.parent.mkdir(parents=True, exist_ok=True)
            fn.write_text(x["_cif"])
            x["uma_max_fold_deg"] = max_fold(x["_cif"])
            structs.append(dict(candidate_id=x["candidate_id"], salt_id=salt, kind="uma_relaxed", source="clari funnel uma_relaxed/predictions.parquet (cif column)",
                                file=str(fn.relative_to(OUT)), sha256=sha(fn), uma_rank_within_salt=x["uma_rank_within_salt"],
                                uma_delta_E_kJ_mol_per_fu=fmt(x["uma_delta_E_kJ_mol_per_fu"]), max_fold_deg=fmt(x["uma_max_fold_deg"]), selection_status=x["selection_status"]))
        for rr in runs:
            if rr["final_cif"] and best.get((rr["label"], rr["protocol_key"])) is rr:
                src = CAMPAIGN / rr["final_cif"]
                fn = sdir / salt / f"{salt}_{rr['label']}_{Path(rr['run_dir']).name}_dft_final.cif"
                fn.write_bytes(src.read_bytes())
                from ase.io import read
                f = fold_screen.folds(read(str(src)))
                structs.append(dict(candidate_id=next((x["candidate_id"] for x in recs if x["shortlist_label"] == rr["label"]), ""), salt_id=salt, kind="dft_final",
                                    source=rr["final_cif"], file=str(fn.relative_to(OUT)), sha256=sha(fn), uma_rank_within_salt="", uma_delta_E_kJ_mol_per_fu="",
                                    max_fold_deg=fmt(max(f) if f else None), selection_status=f"DFT {rr['protocol_key']}; dE={rr.get('delta_E_dft_kJ_mol_per_fu')!r} kJ/mol/FU"))
        for x in recs:
            x.pop("_cif")
            x.setdefault("uma_rank_within_salt", None); x.setdefault("uma_delta_E_kJ_mol_per_fu", None); x.setdefault("uma_max_fold_deg", None)
        rows += recs
        summary.append(dict(salt_id=salt, population=pop, campaign_salt_alias=alias or "", n_clari_samples=len(recs), n_uma_converged=sum(x["uma_converged"] for x in recs),
                            n_identity_ok=len(ok), n_shortlisted=len(cands), n_passed_free_energy_prefilter=len(pre_labels) if pre is not None else None,
                            n_dft_candidates_relaxed=len(dft_labels), n_dft_runs=len(runs), rejected_identity_reported=json.dumps((sel or {}).get("summary", {}).get("rejected", {}))))
        print(salt, summary[-1], flush=True)
    keys = list(rows[0].keys())
    with open(OUT / "packings" / "candidate_index.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=keys)
        w.writeheader()
        for x in rows:
            w.writerow({k: fmt(v) if isinstance(v, (float, np.floating)) else ("" if v is None else v) for k, v in x.items()})
    for name, data in (("dft_runs.csv", dft_rows), ("structures_index.csv", structs), ("funnel_summary.csv", summary)):
        with open(OUT / "packings" / name, "w", newline="") as fh:
            w = csv.DictWriter(fh, fieldnames=list(data[0].keys()))
            w.writeheader(); w.writerows(data)
    print("rows", len(rows), "structures", len(structs), "dft runs", len(dft_rows))


if __name__ == "__main__":
    main()
