"""Silicon phonons from a machine-learning potential, build stage: structures and q points only.

Writes the diamond primitive cell, the repeated cell whose force constants the run stage
determines, the dense q path Gamma-X-W-K-Gamma-L and the q mesh of the density of states.
No calculator is attached and no energy is computed.

    python silicon-phonons-build.py --output ../../studies/silicon-phonons

Then run silicon-phonons-run.py with the same --output.
"""
import argparse
import json
from pathlib import Path

import numpy as np

from atomli.build import bulk
from atomli.io import write
from atomli.visualize import Viewer

START_LATTICE = 5.5  # angstrom, relaxed by the model in the run stage
SUPERCELL = 6  # repeats of the primitive cell along each axis: 432 atoms
CONVERGENCE_SUPERCELLS = [2, 3, 4, 6, 8]
POINTS_PER_SEGMENT = 60
DOS_MESH = 32  # Gamma-centred q mesh of the density of states
# Corners in units of 2 pi / a, Cartesian axes of the diamond cell.
CORNERS = {"Γ": (0, 0, 0), "X": (1, 0, 0), "W": (1, .5, 0), "K": (.75, .75, 0), "L": (.5, .5, .5)}
PATH = ["Γ", "X", "W", "K", "Γ", "L"]


def q_path(cell, points):
    """Dense q path: (positions in 2 pi / a, labels, label positions, reciprocal-lattice coordinates)."""
    a = 2 * cell[0, 1]  # fcc primitive vectors have components a/2
    reciprocal = np.linalg.inv(cell).T * a  # rows b_i in units of 2 pi / a
    positions, fractions, labels, label_positions, offset = [], [], [PATH[0]], [0.0], 0.0
    for index, (start, stop) in enumerate(zip(PATH[:-1], PATH[1:])):
        p0, p1 = np.asarray(CORNERS[start], float), np.asarray(CORNERS[stop], float)
        length = np.linalg.norm(p1 - p0)
        t = np.linspace(0, 1, points + 1)[1 if index else 0:]
        for ti in t:
            positions.append(offset + ti * length)
            fractions.append(((p0 + ti * (p1 - p0)) @ np.linalg.inv(reciprocal)).tolist())
        offset += length
        labels.append(stop), label_positions.append(offset)
    return positions, labels, label_positions, fractions


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    root = Path(parser.parse_args().output)
    inputs = root / "input"
    inputs.mkdir(parents=True, exist_ok=True)

    primitive = bulk("Si", "diamond", a=START_LATTICE)
    write(inputs / "si-primitive.extxyz", primitive)
    supercell = primitive.repeat((SUPERCELL,) * 3)
    write(inputs / "si-supercell.extxyz", supercell)

    positions, labels, label_positions, fractions = q_path(np.asarray(primitive.cell), POINTS_PER_SEGMENT)
    (inputs / "qpath.json").write_text(json.dumps({
        "supercell": [SUPERCELL] * 3, "convergence_supercells": CONVERGENCE_SUPERCELLS, "dos_mesh": [DOS_MESH] * 3,
        "positions": positions, "labels": labels, "label_positions": label_positions, "qpoints_fractional": fractions,
        "units": "positions in 2 pi / a; q points in reciprocal-lattice coordinates"}))

    viewer = Viewer([supercell], height=420, look={"cell": True, "labels": False})
    viewer.write_spec(root / "figures" / "supercell.json", structure_path=root / "figures" / "supercell.extxyz")
    print("supercell atoms:", len(supercell), "q points on the path:", len(positions))


if __name__ == "__main__":
    main()
