#!/usr/bin/env python3
"""Write the illustrative inputs of the command-line figure tutorial.

Usage: python make_inputs.py [OUTPUT_DIR]   (default: the current directory)

Every archive here is project-authored example input, not a calculation:

* diamond.qvf, rocksalt.qvf, zincblende.qvf: conventional cubic cells of C,
  MgO and ZnS with rounded literature lattice constants (3.567, 4.212 and
  5.409 Å). Illustrative geometries, not reference data.
* slab.qvf: three MgO(001) layers of a 2 x 2 surface cell, periodic in a and b.
* mgo-primitive.qvf: the two-atom primitive rocksalt cell, for Wigner-Seitz
  supercells and cyclic-cluster figures.
* model-bands.qvf: bands and DOS of a toy model, written so the chart
  commands have something to draw. Two nearest-neighbour s-like bands on an
  fcc lattice, E(k) = E0 - 4 t [cos(kx a/2) cos(ky a/2) + cos(ky a/2) cos(kz a/2)
  + cos(kz a/2) cos(kx a/2)], with (E0, t) = (0, 1) and (8, -0.5) eV and the
  Fermi energy at half filling of the lower band. It is a model, not a material.
* rods.qvf: carbon rods along c at the corners of a 6 x 6 x 10 Å cell, an
  open one-dimensional channel for the pore overlay.

Only the public ``vibeviewer.qvf_writer`` builder is used, so the files can
be regenerated with any recent vibe-viewer.
"""

from __future__ import annotations

import sys
from pathlib import Path

import numpy as np

from vibeviewer.qvf_writer import QVFArchiveBuilder, structure_archive

FCC = [(0, 0, 0), (0, .5, .5), (.5, 0, .5), (.5, .5, 0)]
Z = {"C": 6, "O": 8, "Mg": 12, "S": 16, "Zn": 30}
NOTE = "Illustrative example input from the vibe-viewer tutorial; not a calculation"


def _atoms(a: float, basis: list[tuple[str, tuple[float, float, float]]]) -> list[dict]:
    atoms = []
    for symbol, shift in basis:
        for f in FCC:
            frac = [(f[i] + shift[i]) % 1.0 for i in range(3)]
            atoms.append({"symbol": symbol, "atomic_number": Z[symbol],
                          "position": [round(x * a, 6) for x in frac]})
    return atoms


def _cubic(path: Path, a: float, basis: list[tuple[str, tuple[float, float, float]]]) -> None:
    structure_archive(_atoms(a, basis), [True] * 3, np.eye(3) * a,
                      calculation=NOTE).write(path)


def _slab(path: Path, a: float = 4.212, layers: int = 3) -> None:
    atoms = []
    for layer in range(layers):
        for i in range(4):
            for j in range(4):
                magnesium = (i + j + layer) % 2 == 0
                atoms.append({"symbol": "Mg" if magnesium else "O",
                              "atomic_number": 12 if magnesium else 8,
                              "position": [i * a / 2, j * a / 2, layer * a / 2]})
    lattice = [[2 * a, 0, 0], [0, 2 * a, 0], [0, 0, (layers - 1) * a / 2 + 15.0]]
    structure_archive(atoms, [True, True, False], lattice, calculation=NOTE).write(path)


def _primitive_mgo(path: Path, a: float = 4.212) -> None:
    lattice = [[0, a / 2, a / 2], [a / 2, 0, a / 2], [a / 2, a / 2, 0]]
    atoms = [{"symbol": "Mg", "atomic_number": 12, "position": [0.0, 0.0, 0.0]},
             {"symbol": "O", "atomic_number": 8, "position": [a / 2] * 3}]
    structure_archive(atoms, [True] * 3, lattice, calculation=NOTE).write(path)


def _band(k: np.ndarray, e0: float, t: float, a: float) -> np.ndarray:
    cx, cy, cz = (np.cos(k[..., i] * a / 2) for i in range(3))
    return e0 - 4 * t * (cx * cy + cy * cz + cz * cx)


def _model_bands(path: Path, a: float = 3.6) -> None:
    params = [(0.0, 1.0), (8.0, -0.5)]
    g = 2 * np.pi / a
    corners = {"Γ": (0, 0, 0), "X": (0, g, 0), "W": (g / 2, g, 0),
               "L": (g / 2, g / 2, g / 2), "K": (3 * g / 4, 3 * g / 4, 0)}
    path_labels = ["Γ", "X", "W", "L", "Γ", "K"]
    points, segments = [], []
    for start, end in zip(path_labels, path_labels[1:], strict=False):
        p0, p1 = np.array(corners[start]), np.array(corners[end])
        n = max(8, int(round(np.linalg.norm(p1 - p0) / g * 40)))
        points.append(p0 + np.linspace(0, 1, n, endpoint=False)[:, None] * (p1 - p0))
        segments.append({"label_start": start, "label_end": end, "n_points": n})
    points.append(np.array(corners[path_labels[-1]])[None])
    segments[-1]["n_points"] += 1
    kpts = np.vstack(points)
    # Fermi energy at half filling of the lower band, from a uniform k sample.
    grid = (np.arange(64) + 0.5) / 64 * 4 * np.pi / a
    mesh = np.stack(np.meshgrid(grid, grid, grid, indexing="ij"), axis=-1)
    sample = [_band(mesh, e0, t, a).ravel() for e0, t in params]
    fermi = float(np.median(sample[0]))
    eigen = np.stack([_band(kpts, e0, t, a) for e0, t in params], axis=-1)[None]
    energies = np.linspace(-14.0, 16.0, 601)
    sigma, dos = 0.25, np.zeros_like(energies)
    for values in sample:  # Gaussian-broadened histogram, 2 states per band (spin)
        hist, edges = np.histogram(values - fermi, bins=600, range=(-14.0, 16.0))
        centres = (edges[:-1] + edges[1:]) / 2
        weights = 2.0 * hist / values.size
        dos += np.exp(-0.5 * ((energies[:, None] - centres) / sigma) ** 2) @ weights / (
            sigma * np.sqrt(2 * np.pi))
    builder = QVFArchiveBuilder(calculation=NOTE + " (toy fcc tight-binding model)")
    lattice = [[0, a / 2, a / 2], [a / 2, 0, a / 2], [a / 2, a / 2, 0]]
    builder.add_json("structure", "structure", "structure", {
        "atoms": [{"symbol": "Cu", "atomic_number": 29, "position": [0.0, 0.0, 0.0]}],
        "pbc": [True] * 3, "dimensionality": 3, "lattice_vectors": lattice})
    builder.add_json("bands", "bands", "kpath", {"segments": segments, "fermi": fermi,
                                                  "title": "Toy fcc tight-binding model"})
    builder.add_binary("bands", "bands", "eigenvalues", eigen)
    builder.add_binary("dos", "dos.total", "energies", energies)
    builder.add_binary("dos", "dos.total", "dos", dos)
    builder.write(path)


def _rods(path: Path) -> None:
    atoms = [{"symbol": "C", "atomic_number": 6, "position": [0.0, 0.0, 1.25 * i]}
             for i in range(8)]
    structure_archive(atoms, [True] * 3, np.diag([6.0, 6.0, 10.0]),
                      calculation=NOTE).write(path)


def main(out: Path) -> None:
    out.mkdir(parents=True, exist_ok=True)
    _cubic(out / "diamond.qvf", 3.567, [("C", (0, 0, 0)), ("C", (.25, .25, .25))])
    _cubic(out / "rocksalt.qvf", 4.212, [("Mg", (0, 0, 0)), ("O", (.5, .5, .5))])
    _cubic(out / "zincblende.qvf", 5.409, [("Zn", (0, 0, 0)), ("S", (.25, .25, .25))])
    _slab(out / "slab.qvf")
    _primitive_mgo(out / "mgo-primitive.qvf")
    _model_bands(out / "model-bands.qvf")
    _rods(out / "rods.qvf")
    for name in sorted(p.name for p in out.glob("*.qvf")):
        print(f"wrote {out / name}")


if __name__ == "__main__":
    main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd())
