"""Water orbital DOS, windowed to the valence region with the HOMO-LUMO gap marked.

PBE/def2-SVP at the relaxed geometry; writes the plot specs used by the docs.

    python water-dos.py --output ../../figures
"""
import argparse
from pathlib import Path

import numpy as np

from atomli.build import molecule
from atomli.calculators.qc import QC
from atomli.optimize import BFGS
from atomli.visualize import plot

WINDOW = (-27.0, 9.0)  # eV relative to the Fermi level (middle of the gap): above O 1s, below the high virtual orbitals
WIDTH = 0.3  # Gaussian width, eV


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    output = Path(parser.parse_args().output)
    atoms = molecule("H2O")
    atoms.calc = QC(xc="PBE", basis="def2-SVP")
    BFGS(atoms).run(fmax=0.003, steps=100)
    state = atoms.calc.get_electronic_state()
    levels = np.asarray(state["eigenvalues"])[0].ravel()
    occupied = int(round(state["electron_count"] / 2))
    homo, lumo = float(levels[occupied - 1]), float(levels[occupied])
    dos = atoms.calc.get_dos(width=WIDTH, window=WINDOW, npts=1200)
    energies = np.asarray(dos["energies"], dtype=float)
    values = np.asarray(dos["dos"], dtype=float)
    middle = float(dos["fermi_level"])  # get_dos returns energies relative to this level, the middle of the gap
    if abs(middle - (homo + lumo) / 2) > 1e-3:
        raise RuntimeError("Expected the reference level at the middle of the HOMO-LUMO gap")
    figure = plot.dos(energies, values, title="Water orbital DOS · PBE/def2-SVP", height=430)
    figure.set(layout={
        "shapes": [{"type": "rect", "xref": "x", "yref": "paper", "x0": homo - middle, "x1": lumo - middle,
                    "y0": 0, "y1": 1, "fillcolor": "rgba(220,75,75,.2)", "line": {"width": 0}, "layer": "below"}],
        "xaxis": {"title": {"text": "Energy relative to the middle of the gap (eV)"}},
        "annotations": [{"xref": "x", "yref": "paper", "x": 0, "y": 0.6, "showarrow": False,
                         "text": f"gap {lumo - homo:.2f} eV"}]})
    for target in ("plots/dos.json", "tutorials/water-dos.json"):
        figure.write_spec(output / target)
    print(f"HOMO {homo:.3f} eV, LUMO {lumo:.3f} eV, gap {lumo - homo:.3f} eV")


if __name__ == "__main__":
    main()
