"""Multi-frame extended-XYZ animation of one exported mode over its q-grid supercell (or the unit cell for q = 0).

    python build_supercell_animation.py modes/<salt>/selected_modes_<set>.json MODE_ID OUT.extxyz [--frames 20] [--max-disp 0.25]

Displacement of atom k in cell n (integer vector, 0 <= n_i < grid_i), per unit normal coordinate Q (amu^1/2 A):
  're'  : sqrt(1/N) Re(e_k exp(2 pi i q.n)) / sqrt(m_k)      (q with 2q = G: e_k exp(2 pi i q.n) is real up to a global phase)
  'cos' : sqrt(2/N) Re(e_k exp(2 pi i q.n)) / sqrt(m_k)
  'sin' : sqrt(2/N) Im(e_k exp(2 pi i q.n)) / sqrt(m_k)
N = prod(grid), q = q_index / grid, e = lattice-phase eigenvector (mode JSON eig_re + i eig_im). Frame f shows Q = A sin(2 pi f / frames), with A chosen so
the largest atomic displacement in the supercell is --max-disp A (visual exaggeration; the 300 K rms Q is in mode_index.csv).
For q = 0 the supercell is the unit cell (the pattern repeats in every cell). --deposited-frame draws atom k at frac_k + s_k + n
(s = structure.lattice_shift_to_deposited, whole molecules as in the deposited extxyz) with the Bloch phase of cell n + s_k.
"""
import argparse
import json
import math

import numpy as np


def supercell_displacement(d, m, deposited_frame=False):
    grid = np.array(d["q_grid"]) if any(m["q_index"]) else np.array([1, 1, 1])
    q = np.array(m["q_index"]) / np.array(d["q_grid"])
    e = np.array(m["eig_re"]) + 1j * (np.array(m["eig_im"]) if m["eig_im"] is not None else 0.0)
    mass = np.array(d["structure"]["masses_amu"])
    cell = np.array(d["structure"]["cell_angstrom"])
    frac = np.array(d["structure"]["frac_positions"])
    n_tot = int(np.prod(d["q_grid"]))  # normalisation is over the q-grid supercell even when only one cell is written
    shift = np.array(d["structure"]["lattice_shift_to_deposited"]) if deposited_frame else np.zeros_like(frac, dtype=int)
    pos, disp, sym = [], [], []
    for n in np.ndindex(*grid):
        ph = np.exp(2j * np.pi * (np.array(n)[None, :] + shift) @ q)  # atom k drawn at frac_k + shift_k + n is phonopy atom k in cell n + shift_k
        z = e * ph[:, None]
        if m["part"] == "re":
            u = z.real / math.sqrt(n_tot)
        elif m["part"] == "cos":
            u = math.sqrt(2.0 / n_tot) * z.real
        else:
            u = math.sqrt(2.0 / n_tot) * z.imag
        disp.append(u / np.sqrt(mass)[:, None])
        pos.append((frac + shift + np.array(n)) @ cell)
        sym += d["structure"]["symbols"]
    return grid, np.vstack(pos), np.vstack(disp), sym, cell


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("modes_json"); ap.add_argument("mode_id"); ap.add_argument("out")
    ap.add_argument("--frames", type=int, default=20); ap.add_argument("--max-disp", type=float, default=0.25)
    ap.add_argument("--deposited-frame", action="store_true", help="draw atoms at the deposited (whole-molecule) positions, phases adjusted")
    a = ap.parse_args()
    d = json.load(open(a.modes_json))
    m = next(x for x in d["modes"] if x["mode_id"] == a.mode_id)
    grid, pos, u, sym, cell = supercell_displacement(d, m, a.deposited_frame)
    amp = a.max_disp / np.linalg.norm(u, axis=1).max()
    lat = (cell * grid[:, None]).ravel()
    with open(a.out, "w") as fh:
        for f in range(a.frames):
            s = math.sin(2 * math.pi * f / a.frames)
            fh.write(f"{len(sym)}\nLattice=\"{' '.join(f'{x:.8f}' for x in lat)}\" Properties=species:S:1:pos:R:3 pbc=\"T T T\" "
                     f"mode_id={m['mode_id']} frequency_cm1={m['frequency_cm1']:.6f} supercell={'x'.join(map(str, grid))} frame={f}/{a.frames} "
                     f"Q_amu05A={s * amp:.6e} Q_vis_amp={amp:.6e} max_disp_A={a.max_disp}\n")
            for el, p in zip(sym, pos + s * amp * u):
                fh.write(f"{el} {p[0]:.6f} {p[1]:.6f} {p[2]:.6f}\n")


if __name__ == "__main__":
    main()
