#!/usr/bin/env python3
"""Standalone analytic and optional LAMMPS verifier for the 37-degree rotated triclinic Ar pair.

Verifies the periodic minimum-image Lennard-Jones potential energy from:
    validation/inputs/lammps/data.lmp
    validation/inputs/lammps/in.lammps
    validation/inputs/lammps/conditions.json

Usage:
    python3 validation/scripts/reproduce_lammps_lj_rotation.py
    python3 validation/scripts/reproduce_lammps_lj_rotation.py --run-lammps
"""
from __future__ import annotations

import argparse
import json
import math
import re
import shutil
import subprocess
import sys
from pathlib import Path

INPUT_DIR = Path(__file__).resolve().parent.parent / "inputs" / "lammps"


def parse_lammps_data(path: Path) -> tuple[list[tuple[float, float, float]], list[tuple[float, float, float]]]:
    text = path.read_text(encoding="utf-8")
    xlo, xhi = map(float, re.search(r"([-\d.eE+]+)\s+([-\d.eE+]+)\s+xlo\s+xhi", text).groups())
    ylo, yhi = map(float, re.search(r"([-\d.eE+]+)\s+([-\d.eE+]+)\s+ylo\s+yhi", text).groups())
    zlo, zhi = map(float, re.search(r"([-\d.eE+]+)\s+([-\d.eE+]+)\s+zlo\s+zhi", text).groups())
    tilt = re.search(r"([-\d.eE+]+)\s+([-\d.eE+]+)\s+([-\d.eE+]+)\s+xy\s+xz\s+yz", text)
    xy, xz, yz = map(float, tilt.groups()) if tilt else (0.0, 0.0, 0.0)

    cell = [
        (xhi - xlo, 0.0, 0.0),
        (xy, yhi - ylo, 0.0),
        (xz, yz, zhi - zlo),
    ]

    atoms: list[tuple[float, float, float]] = []
    in_atoms = False
    for line in text.splitlines():
        s = line.strip()
        if s.startswith("Atoms"):
            in_atoms = True
            continue
        if in_atoms:
            if not s:
                if atoms:
                    break
                continue
            parts = s.split()
            if len(parts) >= 5:
                atoms.append((float(parts[2]), float(parts[3]), float(parts[4])))
    return cell, atoms


def lj_pair_energy_ev(cell: list[tuple[float, float, float]], atoms: list[tuple[float, float, float]], eps: float, sigma: float, cutoff: float) -> tuple[float, float]:
    a, b, c = cell
    p0, p1 = atoms[0], atoms[1]
    dx0, dy0, dz0 = p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]
    total = 0.0
    min_r = float("inf")
    for ia in (-1, 0, 1):
        for ib in (-1, 0, 1):
            for ic in (-1, 0, 1):
                dx = dx0 + ia * a[0] + ib * b[0] + ic * c[0]
                dy = dy0 + ia * a[1] + ib * b[1] + ic * c[1]
                dz = dz0 + ia * a[2] + ib * b[2] + ic * c[2]
                r = math.sqrt(dx * dx + dy * dy + dz * dz)
                if r < min_r:
                    min_r = r
                if 0.0 < r < cutoff:
                    sr6 = (sigma / r) ** 6
                    total += 4.0 * eps * (sr6 * sr6 - sr6)
    return min_r, total


def main() -> int:
    parser = argparse.ArgumentParser(description="Verify 37-degree rotated triclinic Ar LJ benchmark.")
    parser.add_argument("--run-lammps", action="store_true", help="Also run local `lmp` binary if installed.")
    parser.add_argument("--lmp-bin", default=None, help="Path to LAMMPS executable (default: auto-detect lmp / lmp_serial).")
    args = parser.parse_args()

    cond = json.loads((INPUT_DIR / "conditions.json").read_text(encoding="utf-8"))
    cell, atoms = parse_lammps_data(INPUT_DIR / "data.lmp")
    cutoff = float(cond.get("cutoff", cond["options"]["pair_style"].split()[-1]))
    min_r, analytic_e = lj_pair_energy_ev(cell, atoms, cond["epsilon"], cond["sigma"], cutoff)
    ref_e = float(cond["reference_energy_ev"])
    diff = abs(analytic_e - ref_e)

    print(f"Minimum periodic distance : {min_r:.9f} A (expected {cond['nearest_r']:.9f} A)")
    print(f"Analytic LJ energy        : {analytic_e:.15f} eV")
    print(f"Published reference       : {ref_e:.15f} eV")
    print(f"Absolute difference       : {diff:.3e} eV")
    assert diff < 1e-12, f"Analytic energy mismatch: {diff}"

    if args.run_lammps:
        lmp = args.lmp_bin or shutil.which("lmp") or shutil.which("lmp_serial") or shutil.which("lmp_mpi")
        if not lmp:
            print("LAMMPS binary not found on PATH; skipped live LAMMPS check.", file=sys.stderr)
            return 2
        proc = subprocess.run([lmp, "-in", "in.lammps"], cwd=INPUT_DIR, capture_output=True, text=True, check=True)
        match = re.search(r"^\s*0\s+[-\d.eE+]+\s+([-\d.eE+]+)", proc.stdout, re.MULTILINE)
        assert match, "Could not parse thermo PotEng from LAMMPS output"
        lmp_e = float(match.group(1))
        lmp_diff = abs(lmp_e - ref_e)
        print(f"Live LAMMPS PotEng        : {lmp_e:.15f} eV (abs diff {lmp_diff:.3e} eV)")
        assert lmp_diff < 2e-7, f"LAMMPS mismatch: {lmp_diff}"

    print("ROTATED TRICLINIC AR PAIR VERIFICATION PASSED.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
