"""Silicon bands and phonons, build stage: structures and sampling lists only.

Writes the diamond primitive cell, the k points that lie on the Brillouin-zone
path of an N x N x N Gamma-centred mesh, and the phonon q points. No calculator is attached and no energy is computed.

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

Then run silicon-bands-run.py with the same --output.
"""
import argparse
import itertools
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 in the run stage
SCF_MESH = 16  # k mesh of the band calculation; even, so X and L are on it
PHONON_SUPERCELL = 2  # responses on a 2 x 2 x 2 q mesh, which contains Gamma, X and L
# 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 fractional(corner, cell):
    """Reciprocal-lattice coordinates of a corner given in units of 2 pi / a."""
    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
    return np.asarray(corner, dtype=float) @ np.linalg.inv(reciprocal)


def mesh_path(mesh, cell, path=PATH, corners=CORNERS):
    """Points of the mesh that lie on the straight segments of the path.

    Returns (positions, labels, label_positions, fractional coordinates).
    Positions are cumulative distances in units of 2 pi / a. Every point is a
    mesh point up to a reciprocal-lattice vector; none is interpolated.
    """
    a = 2 * cell[0, 1]
    reciprocal = np.linalg.inv(cell).T * a
    grid = np.array(list(itertools.product(range(-mesh, mesh + 1), repeat=3))) / mesh
    cart = grid @ reciprocal
    positions, fractions, tick_labels, tick_positions, offset = [], [], [], [], 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)
        direction = p1 - p0
        length = np.linalg.norm(direction)
        t = (cart - p0) @ direction / length**2
        off = np.linalg.norm(cart - p0 - np.outer(t, direction), axis=1)
        keep = np.flatnonzero((off < 1e-9) & (t > -1e-9) & (t < 1 + 1e-9))
        order, seen = [], set()
        for i in keep[np.argsort(t[keep])]:
            key = round(float(t[i]), 6)
            if key not in seen:
                seen.add(key)
                order.append(i)
        ts = np.array([t[i] for i in order])
        if abs(ts[0]) > 1e-9 or abs(ts[-1] - 1) > 1e-9:
            raise ValueError(f"{start} or {stop} is not on the {mesh}x{mesh}x{mesh} mesh")
        if index == 0:
            tick_labels.append(start), tick_positions.append(0.0)
        for i, ti in zip(order, ts):
            if index and ti == 0:
                continue  # corner already placed by the previous segment
            positions.append(offset + ti * length)
            fractions.append(grid[i].tolist())
        offset += length
        tick_labels.append(stop), tick_positions.append(offset)
    return positions, tick_labels, tick_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)
    cell = np.asarray(primitive.cell)

    positions, labels, label_positions, fractions = mesh_path(SCF_MESH, cell)
    kpath_positions = positions
    (inputs / "kpath.json").write_text(json.dumps({
        "mesh": [SCF_MESH] * 3, "positions": positions, "labels": labels, "label_positions": label_positions,
        "kpoints_fractional": fractions, "units": "positions in 2 pi / a; k points in reciprocal-lattice coordinates",
        "convergence_meshes": [6, 8, 12, 16, 24]}, indent=1))

    # Phonon q points: those that a 2x2x2 q mesh contains. Each is a direct response, none is interpolated.
    qpoints = {"Γ": [0.0, 0.0, 0.0], "X": [0.0, 0.5, 0.5], "L": [0.5, 0.5, 0.5]}
    (inputs / "qpoints.json").write_text(json.dumps({
        "supercell": [PHONON_SUPERCELL] * 3, "labels": list(qpoints), "qpoints_fractional": list(qpoints.values()),
        "units": "reciprocal-lattice coordinates"}))

    # Conventional cubic cell of the same crystal, for the page's initial-model viewer.
    cubic = bulk("Si", "diamond", a=START_LATTICE, cubic=True)
    viewer = Viewer([cubic], height=420, look={"cell": True})
    centre = np.full(3, START_LATTICE / 2)
    viewer.set_camera(position=(centre + np.array([1.0, 0.6, 0.35]) * 3 * START_LATTICE).tolist(),
                      target=centre.tolist(), up=(0, 0, 1))  # an oblique direction that separates the atoms
    viewer.write_spec(root / "figures" / "cell.json", structure_path=root / "figures" / "cell.extxyz")
    print("k points on the path:", len(kpath_positions))


if __name__ == "__main__":
    main()
