"""Check: the supercell pattern of build_supercell_animation.py, read at the carved anion's cells and rotated into the metal frame
(rigid translations removed), equals the cluster vector the couplings were projected on (cluster_vectors_*.json). Run from the package root:
    python scripts/test_supercell_builder.py"""
import glob
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).parent))
from build_supercell_animation import supercell_displacement  # noqa: E402

worst, n, worst_dep = 0.0, 0, 0.0
for f in sorted(glob.glob("modes/*/selected_modes_*.json")):
    d = json.load(open(f))
    cv = json.load(open(f.replace("selected_modes_", "cluster_vectors_")))
    c = cv["cluster"]
    xs = {m["mode_id"]: np.array(m["x"]) for m in cv["modes"]}
    ca, off = np.array(c["cluster_to_cell_atom_0based"]), np.array(c["cluster_lattice_offset"])
    R, mm = np.array(c["rotation_rows_new_axes"]), np.array(c["masses_amu"])
    t = np.zeros((3 * len(mm), 3))
    for a in range(3):
        t[a::3, a] = np.sqrt(mm / mm.sum())
    nat = len(d["structure"]["symbols"])
    for m in d["modes"]:
        grid, _pos, u, _s, _cell = supercell_displacement(d, m)
        cidx = [int(np.ravel_multi_index(tuple(np.mod(o, grid)), tuple(grid))) for o in off]  # np.ndindex order = C order
        uc = np.array([u[ci * nat + a] for ci, a in zip(cidx, ca)])
        x = (uc * np.sqrt(mm)[:, None]).ravel()
        x = x - (x @ t) @ t.T
        x = (x.reshape(-1, 3) @ R.T).ravel()
        worst = max(worst, np.abs(x - xs[m["mode_id"]]).max()); n += 1
        # deposited-frame drawing: same (atom, position mod supercell) -> same displacement
        g2, pos2, u2, _s2, _c2 = supercell_displacement(d, m, deposited_frame=True)
        sc = np.array(d["structure"]["cell_angstrom"]) * g2[:, None]
        p1 = np.linalg.solve(sc.T, _pos.T).T % 1.0
        p2 = np.linalg.solve(sc.T, pos2.T).T % 1.0
        key1 = {(i % nat, tuple(np.round(p1[i], 5) % 1.0)): u[i] for i in range(len(p1))}
        dep_dev = max(np.abs(key1[(i % nat, tuple(np.round(p2[i], 5) % 1.0))] - u2[i]).max() for i in range(len(p2)))
        worst_dep = max(worst_dep, dep_dev)
print(f"{n} modes, max |builder - coupling vector| = {worst:.2e}; deposited-frame vs wrapped drawing max diff = {worst_dep:.2e}")
assert worst < 1e-10 and worst_dep < 1e-10, (worst, worst_dep)
print("SUPERCELL BUILDER CONSISTENT")
