"""Generate the documentation's interactive fields, constraints, and workflows.

Run: python visual-tutorials.py --output visual-tutorials
Open the resulting HTML files in a browser; no notebook kernel is required.
Scientific values are calculated with public Atomli APIs. Nuclear derivatives
are analytical. Constraint examples use water adsorption at a finite LiF coordination site.
Adsorbate vibrational modes use the analytical partial Hessian.
"""
from __future__ import annotations

import argparse
import html
import json
from pathlib import Path
import time

import numpy as np

from atomli import Atoms
from atomli.build import add_adsorbate, bulk, fcc111, molecule
from atomli.calculators import QC
from atomli.constraints import (FixAtoms, FixBondLength, FixBondLengths, FixCartesian,
                                FixCom, FixScaled, FixSubsetCom, FixedLine, FixedMode,
                                FixedPlane, Hookean)
from atomli.io import write
from atomli.optimize import BFGS
from atomli.visualize import FieldViewer, Viewer, plot
from atomli.vibrations import Vibrations


LABEL_MAX_ATOMS = 30


def element_look(atoms, tagged=False):
    """Viewer options shared by every structure demo: element legend and axes
    gizmo always; per-atom element labels only for small, non-periodic
    structures that carry no per-atom tags. Mirrors
    docs-site/scripts/enable-viewer-legends.py."""
    labels = len(atoms) <= LABEL_MAX_ATOMS and not any(atoms.get_pbc()) and not tagged
    return {"axes": True, "legend": True, "labels": labels}


def molecular_pbe(**kwargs):
    """Consistent molecular model for all geometries, fields, and Hessians."""
    return QC(xc="PBE", basis="def2-svp", device="cpu",
              scf={"energy_tolerance": 1e-8}, maxiter=150, **kwargs)


STYLE = """<style>
*{box-sizing:border-box}body{margin:0;background:#fff;color:#20252c;font:14px/1.5 system-ui,sans-serif}
header{padding:14px 18px 8px}h1{font-size:17px;line-height:1.3;margin:0 0 5px}p{margin:4px 0;color:#535e6b}
.controls{display:flex;flex-wrap:wrap;align-items:center;gap:10px 20px;padding:8px 18px;border-top:1px solid #e5e7eb}
label{display:flex;align-items:center;gap:7px;font-size:12px}input[type=range]{width:110px;accent-color:#2563eb}
button,select{font:inherit;padding:4px 8px;border:1px solid #cbd5e1;border-radius:5px;background:white;color:#20252c}
button[aria-pressed=true]{background:#eaf2ff;border-color:#2563eb}.tab-panel[hidden]{display:none}
.note{padding:8px 18px;font-size:12px;border-top:1px solid #e5e7eb}.legend{display:flex;gap:16px;flex-wrap:wrap}
.legend span:before{content:'●';margin-right:5px;color:var(--color)}.stage{height:370px}
@media(max-width:440px){header{padding:10px 12px 6px}.controls{padding:7px 12px;gap:7px}input[type=range]{width:85px}}
</style>"""


def serial(value):
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, np.generic):
        return value.item()
    if isinstance(value, complex):
        return [value.real, value.imag]
    raise TypeError(type(value).__name__)


def save_json(path, value):
    path.write_text(json.dumps(value, default=serial, allow_nan=False, indent=2) + "\n")


def javascript(value):
    return json.dumps(value, default=serial, allow_nan=False, separators=(",", ":")).replace("<", "\\u003c")


class Tutorials:
    def __init__(self, output, runtime):
        self.output = output
        self.output.mkdir(parents=True, exist_ok=True)
        self.runtime = runtime.rstrip("/")
        self.records = []

    def publish(self, name, title, description, viewer, record, chart=None, legend="", chart_label="Geometry and force history"):
        viewer_html = viewer.to_html()
        content = '<div class="tab-panel" id="motion">' + viewer_html + '</div>'
        controls = ""
        if chart is not None:
            chart.script_url = self.runtime + "/tako-plot.js"
            content += '<div class="tab-panel" id="chart" hidden>' + chart.to_html() + '</div>'
            controls = ('<nav class="controls" aria-label="Figure view"><button aria-pressed="true" data-tab="motion">Structures</button>'
                        f'<button aria-pressed="false" data-tab="chart">{html.escape(chart_label)}</button></nav>'
                        '<script>document.querySelectorAll("[data-tab]").forEach(button=>button.addEventListener("click",()=>{'
                        'document.querySelectorAll(".tab-panel").forEach(panel=>panel.hidden=panel.id!==button.dataset.tab);'
                        'document.querySelectorAll("[data-tab]").forEach(other=>other.setAttribute("aria-pressed",String(other===button)));'
                        'window.dispatchEvent(new Event("resize"));}));</script>')
        page = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' + STYLE
        page += f'<header><h1>{html.escape(title)}</h1><p>{html.escape(description)}</p></header>' + controls + content
        if legend:
            page += '<div class="note">' + legend + '</div>'
        page += '</html>'
        (self.output / f"{name}.html").write_text(page)
        record = {"title": title, "description": description, **record}
        save_json(self.output / f"{name}.json", record)
        self.records.append({"id": name, "title": title, "kind": record["kind"],
                             "html": name+".html", "data": name+".json"})

    def structure(self, name, title, atoms, *, tags="index", description="", **look):
        viewer = Viewer([atoms], height=370, script_url=self.runtime+"/tako-viewer.js",
                        look={"background": "white", "tags": tags, **element_look(atoms, bool(tags)), **look})
        self.publish(name, title, description, viewer, {"kind": "structure", "formula": atoms.get_chemical_formula(),
                     "positions_angstrom": atoms.get_positions(), "cell_angstrom": np.asarray(atoms.cell),
                     "pbc": atoms.get_pbc(), "atom_count": len(atoms)})
        write(self.output / f"{name}.extxyz", atoms)

    def field(self, name, title, atoms, field, *, level, color_by=None, description="", **options):
        print("Field:", name, flush=True)
        viewer = FieldViewer(atoms, field, isovalue=level, color_by=color_by, title=title,
                             look={"background": "white", "atom_scale": 65, "bonds": True, **element_look(atoms), "cell": bool(np.any(atoms.pbc))},
                             script_url=self.runtime+"/tako-viewer.js", **options)
        snapshot = viewer.to_snapshot()
        center = np.mean(atoms.get_positions(), axis=0)
        snapshot["camera"].update(target=center.tolist(), position=(center+np.array([5, 4, 9])).tolist())
        cube = snapshot["cubeLayers"][0]["cube"]
        maxlevel = max(abs(cube["min"]), abs(cube["max"]))
        low, high = level/4, min(level*4, maxlevel*.9)
        signed = snapshot["cubeLayers"][0]["surfaceMode"] == "both"
        legend = ("Blue: positive orbital amplitude; orange: negative amplitude. Phase is not electrical charge."
                  if signed and field["kind"] == "orbital_amplitude" else
                  "Surface colors show lower (blue) to higher (red) ESP, autoscaled on this surface; this is not a charge partition."
                  if color_by is not None else f"Contour values use {field['value_unit']}. Drag to rotate; scroll to zoom.")
        controls = f'''<div class="controls">
<label>Contour <input aria-label="Isovalue" id="level" type="range" min="{low}" max="{high}" step="{(high-low)/80}" value="{level}"><output id="level-value">{level:g}</output></label>
<label>Opacity <input aria-label="Opacity" id="opacity" type="range" min="0.2" max="1" step="0.05" value="{snapshot['cubeLayers'][0]['opacity']}"></label>
<label><input aria-label="Clip surface" id="clip" type="checkbox"> Slice</label>
<label>Plane <select aria-label="Slice axis" id="axis"><option>x</option><option>y</option><option selected>z</option></select></label>
<label>Position <input aria-label="Slice position" id="position" type="range" min="0.1" max="0.9" step="0.05" value="0.5"></label>
</div>'''
        page = '<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">' + STYLE
        page += f'<header><h1>{html.escape(title)}</h1><p>{html.escape(description)}</p></header>{controls}<div class="stage" id="field-viewer"></div>'
        page += f'<div class="note">{html.escape(legend)}</div><script src="{html.escape(self.runtime)}/tako-viewer.js"></script>'
        page += '<script>const snapshot=' + javascript(snapshot) + ';\n'
        page += '''const viewer=window.Tako.viewer(document.getElementById('field-viewer'),{snapshot,height:'370px',camera:'snapshot',background:'white',axes:true,legend:true,labels:__LABELS__,atomScale:65,cell:snapshot.pbc.periodic.some(Boolean)});
window.fieldViewer=viewer;window.fieldSnapshot=snapshot;
let pending;
function update(){clearTimeout(pending);pending=setTimeout(async()=>{
 const layer=snapshot.cubeLayers[0]; const camera=viewer.camera();if(camera)snapshot.camera=camera;
 layer.isovalue=Number(document.getElementById('level').value);
 layer.opacity=Number(document.getElementById('opacity').value);
 layer.slice.enabled=document.getElementById('clip').checked;
 layer.slice.axis=document.getElementById('axis').value;
 layer.slice.position=Number(document.getElementById('position').value);
 layer.slice.style='both';
 document.getElementById('level-value').textContent=layer.isovalue.toPrecision(3);
 await viewer.load({snapshot});document.documentElement.dataset.contour=String(layer.isovalue);
},100);}
for(const id of ['level','opacity','clip','axis','position'])document.getElementById(id).addEventListener('input',update);
viewer.ready.then(()=>document.documentElement.dataset.ready='true');
</script></html>'''.replace("__LABELS__", str(element_look(atoms)["labels"]).lower())
        (self.output / f"{name}.html").write_text(page)
        save_json(self.output / f"{name}.snapshot.json", snapshot)
        record = {"kind": "volumetric_field", "title": title, "description": description,
                  "method": "PBE/def2-SVP" if not np.any(atoms.pbc) else "PBE/GTH-SZV (coarse grid)",
                  "evaluation": "native retained-state fields; no nuclear finite differences",
                  "grid": {key: field[key] for key in ("shape", "origin", "axes", "kind", "length_unit", "value_unit", "representation")},
                  "isovalue": level, "range": [cube["min"], cube["max"]], "color_by": color_by["kind"] if color_by is not None else None,
                  "surface_mode": snapshot["cubeLayers"][0]["surfaceMode"], "visualization_precision": "Float32"}
        save_json(self.output / f"{name}.json", record)
        self.records.append({"id": name, "title": title, "kind": record["kind"], "html": name+".html", "data": name+".json"})

    def fields(self):
        atoms = molecule("H2O")
        atoms.calc = molecular_pbe()
        opt = BFGS(atoms, logfile=None)
        if not opt.run(fmax=1e-4, steps=60):
            raise RuntimeError("PBE water relaxation did not converge")
        geometry = atoms.get_positions().copy()
        grid = {"shape": [41, 41, 41], "margin": 2.5}
        density = atoms.calc.get_field(atoms=atoms, kind="electron_density", **grid)
        self.field("water-density", "Water electron-density isosurface", atoms, density, level=.06,
                   description="PBE/def2-SVP at the relaxed geometry; density contour in electron/Å³. Contour, opacity, and section controls use the retained field.")
        self.field("water-density-section", "Water density: higher contour and section", atoms, density, level=.18,
                   description="The same retained density with a tighter contour. Enable Slice to inspect a cross-section.")
        potential = atoms.calc.get_field(kind="electrostatic_potential", **grid)
        self.field("water-esp", "Electrostatic potential on a density surface", atoms, density, level=.06,
                   color_by=potential, colormap="diverging", opacity=.85,
                   description="Geometry and colors carry different information: the surface follows density, while color samples ESP at each surface vertex.")
        state = atoms.calc.get_electronic_state(matrices=False)
        occupied = np.flatnonzero(np.asarray(state["occupations"])[0, 0] > 1e-6)
        for name, band in (("homo", int(occupied[-1])), ("lumo", int(occupied[-1]+1))):
            orbital = atoms.calc.get_field(kind="orbital_amplitude", band=band, **grid)
            self.field(f"water-{name}", f"Water {name.upper()} orbital phase", atoms, orbital, level=.12,
                       description=f"PBE/def2-SVP orbital {band}, with both signs shown at equal absolute amplitude. A global sign flip leaves the orbital physics unchanged.", surface="both", opacity=.8)
        np.testing.assert_array_equal(atoms.get_positions(), geometry)
        write(self.output / "water.extxyz", atoms)
        atoms.calc.write_wavefunction(self.output / "water.h5")
        self.water, self.water_state = atoms, state
        radical = molecule("OH")
        radical.calc = molecular_pbe(unpaired=1)
        spin = radical.calc.get_field(atoms=radical, kind="spin_density", **grid)
        self.field("oh-spin", "OH doublet spin density", radical, spin, level=.04,
                   description="Spin-polarized PBE/def2-SVP OH doublet at the builder geometry. This is alpha-minus-beta electron density, not total electron density.")
        crystal = bulk("Si", "diamond", a=5.43)
        crystal.calc = QC(xc="PBE", device="cpu", settings={"periodic": True, "basis": "gth-szv",
                     "pseudopotential": "gth-pbe", "mesh": [17,17,17], "kpoints": [1,1,1]}, maxiter=100)
        periodic = crystal.calc.get_field(atoms=crystal, kind="electron_density", shape=[33,33,33])
        self.field("silicon-density", "A periodic valence-density field", crystal, periodic, level=.12,
                   description="Two-atom primitive silicon cell; PBE/GTH-SZV, Gamma sampling, 17³ SCF grid. Valence density; quantitative results require basis, k-point, and grid convergence.")

    def constraints(self):
        # Frozen (LiF)2 cluster with water coordinated at its exposed Li site.
        # This finite molecular model has no periodic surface or coverage.
        initial = Atoms("LiFLiFOH2", positions=[
            [0,0,0], [1.7,0,0], [1.7,1.7,0], [0,1.7,0],
            [-.3,-.25,2.15], [-.3,.513,2.746], [-.3,-1.013,2.746],
        ])
        host, guest = [0,1,2,3], [4,5,6]
        collective = np.zeros((7,3)); collective[guest,0] = 1
        cases = [
            ("fixed-host", "Water adsorption with a frozen LiF cluster",
             lambda: FixAtoms(indices=host),
             "PBE/def2-SVP; (LiF)₂–H₂O. Four substrate atoms are fixed; all nine adsorbate coordinates relax."),
            ("cartesian", "Adsorption with fixed lateral O coordinates",
             lambda: [FixAtoms(indices=host), FixCartesian(4, mask=[True,True,False])],
             "O moves along z; the water hydrogens relax freely. The lateral O coordinates remain at their initial values."),
            ("line", "Adsorbate approach along a specified direction",
             lambda: [FixAtoms(indices=host), FixedLine(4, direction=[.25,.25,1])],
             "The O approach direction is constrained. The remaining adsorbate coordinates relax with analytical PBE forces."),
            ("plane", "Lateral relaxation at fixed adsorption height",
             lambda: [FixAtoms(indices=host), FixedPlane(4, direction=[0,0,1])],
             "The initial O height is held fixed; lateral O motion and hydrogen relaxation are allowed."),
            ("bond", "Adsorption with one O–H distance constrained",
             lambda: [FixAtoms(indices=host), FixBondLength(4,5)],
             "One O–H bond retains its initial length. The other bond, angle, and adsorption geometry can relax."),
            ("bonds", "Adsorption with both O–H distances constrained",
             lambda: [FixAtoms(indices=host), FixBondLengths([(4,5),(4,6)])],
             "Both O–H distances are constrained; the H–O–H angle and adsorption coordinates remain active."),
            ("subset-com", "Local substrate relaxation at fixed host center",
             lambda: FixSubsetCom(host),
             "The LiF cluster can deform while its mass-weighted center remains fixed. The water coordinates are free."),
            ("mode", "Adsorption with lateral adsorbate translation removed",
             lambda: [FixAtoms(indices=host), FixedMode(collective)],
             "The collective x displacement of the three water atoms is projected out; internal and remaining collective coordinates relax."),
            ("hookean", "A soft Li–O adsorption restraint",
             lambda: [Hookean(0,4,k=.8,rt=1.8), FixAtoms(indices=host)],
             "A 0.8 eV/Å² spring adds a restoring force above Li–O = 1.8 Å. The four host atoms remain fixed."),
        ]
        for key,title,factory,description in cases:
            print("Adsorption:", key, flush=True)
            atoms=initial.copy();atoms.set_constraint(factory());atoms.calc=molecular_pbe()
            frames,energies,raw,projected,distances=[],[],[],[],[]
            def collect():
                frames.append(atoms.copy());energies.append(atoms.get_potential_energy())
                raw.append(np.linalg.norm(atoms.get_forces(apply_constraint=False),axis=1).max())
                projected.append(np.linalg.norm(atoms.get_forces(),axis=1).max())
                distances.append([atoms.get_distance(0,4), atoms.get_distance(4,5), atoms.get_distance(4,6)])
            opt=BFGS(atoms,logfile=str(self.output/f"adsorption-{key}.log"),maxstep=.12)
            opt.attach(collect,interval=1)
            if not opt.run(fmax=.003,steps=160):
                raise RuntimeError(f"Adsorption relaxation did not converge: {key}")
            positions=np.asarray([frame.get_positions() for frame in frames])
            reference=initial.get_positions()
            if key!="subset-com":
                np.testing.assert_allclose(positions[:,host],np.broadcast_to(reference[host],positions[:,host].shape),atol=1e-12)
            if key=="cartesian":
                np.testing.assert_allclose(positions[:,4,:2],np.broadcast_to(reference[4,:2],(len(frames),2)),atol=1e-12)
            if key=="plane": np.testing.assert_allclose(positions[:,4,2],reference[4,2],atol=1e-12)
            if key=="line":
                direction=np.array([.25,.25,1.]);direction/=np.linalg.norm(direction)
                movement=positions[:,4]-reference[4]
                np.testing.assert_allclose(movement-np.outer(movement@direction,direction),0,atol=1e-12)
            if key in ("bond","bonds"):
                np.testing.assert_allclose(np.asarray(distances)[:,1],distances[0][1],atol=1e-8)
            if key=="bonds": np.testing.assert_allclose(np.asarray(distances)[:,2],distances[0][2],atol=1e-8)
            if key=="subset-com":
                com=np.average(positions[:,host],axis=1,weights=initial.get_masses()[host])
                np.testing.assert_allclose(com,np.broadcast_to(com[0],com.shape),atol=1e-12)
            if key=="mode": np.testing.assert_allclose(np.einsum('fij,ij->f',positions-reference,collective),0,atol=1e-12)
            x=list(range(len(frames)))
            traces=[{"x":x,"y":np.asarray(distances)[:,i].tolist(),"name":name,"mode":"lines"}
                    for i,name in enumerate(["Li–O","O–H1","O–H2"])]
            traces += [{"x":x,"y":projected,"name":"Projected fmax","mode":"lines","yaxis":"y2"},
                       {"x":x,"y":raw,"name":"Raw fmax","mode":"lines","yaxis":"y2","line":{"dash":"dot"}}]
            chart=plot.plotly({"data":traces,"layout":{"xaxis":{"title":{"text":"BFGS step"}},
                "yaxis":{"title":{"text":"Distance (Å)"}},"yaxis2":{"title":{"text":"fmax (eV/Å)"},"overlaying":"y","side":"right"},"legend":{"orientation":"h"}}})
            tags={0:"Li site",4:"O",5:"H1",6:"H2"}
            self.publish("adsorption-"+key,title,description,
                Viewer(frames,height=370,script_url=self.runtime+"/tako-viewer.js",look={"background":"white","tags":tags,**element_look(frames[0],True),
                    "atom_colors":["#a8aeb7"]*4+[None,None,None]}),
                {"kind":"constrained_adsorption_optimization","method":"PBE/def2-SVP","model":"finite (LiF)2–H2O cluster",
                 "constraint":key,"host_indices":host,"adsorbate_indices":guest,"converged":True,"fmax_tolerance_ev_per_angstrom":.003,
                 "energy_ev":energies,"raw_fmax_ev_per_angstrom":raw,"projected_fmax_ev_per_angstrom":projected,
                 "distance_labels":["Li–O","O–H1","O–H2"],"distances_angstrom":distances,
                 "positions_angstrom":positions,"initial_positions_angstrom":reference,"masses_amu":initial.get_masses(),"frame_count":len(frames)},
                chart,"Gray: substrate atoms · colored: adsorbate. Constrained optimization; analytical forces. Select Geometry and force history for the distance and residual traces.")
            write(self.output/f"adsorption-{key}.extxyz",frames)
            if key=="fixed-host": self.adsorption=atoms
        ads=self.adsorption
        field=ads.calc.get_field(atoms=ads,kind="electron_density",shape=[45,45,45],margin=2.5)
        self.field("adsorption-density","Density of water coordinated to the LiF cluster",ads,field,level=.05,
                   description="PBE/def2-SVP at the fixed-host adsorption minimum. The contour displays total density; it is not a density-difference or charge-transfer map.")

    def workflows(self):
        ads=self.adsorption
        active=[4,5,6]
        vibrations=Vibrations(ads,indices=active,method="analytical").run()
        frequencies=vibrations.get_frequencies();signed=frequencies.real-frequencies.imag
        if np.any(signed <= 0): raise RuntimeError("The fixed-host adsorbate Hessian is not positive definite")
        mode_data={"kind":"analytical_adsorbate_hessian","method":"PBE/def2-SVP",
                   "model":"finite (LiF)2–H2O cluster","derivatives":"analytical","fixed_host_indices":[0,1,2,3],
                   "active_indices":active,"frequencies_cm_inv":signed,
                   "hessian_ev_per_angstrom2":vibrations.get_hessian_2d(),"modes":vibrations.get_modes(),
                   "projected_fmax_ev_per_angstrom":float(np.linalg.norm(ads.get_forces(),axis=1).max()),
                   "note":"Nine adsorbate Cartesian coordinates; host response and host–adsorbate vibrational coupling are excluded."}
        save_json(self.output/"adsorbate-hessian.json",mode_data)
        for label,index in [("frustrated",0),("bend",6),("stretch",8)]:
            mode=vibrations.get_mode(index);mode*=.15/np.linalg.norm(mode,axis=1).max()
            frames=[]
            for phase in np.linspace(0,2*np.pi,32,endpoint=False):
                frame=ads.copy();frame.set_positions(ads.get_positions()+np.sin(phase)*mode);frames.append(frame)
            np.testing.assert_array_equal(np.asarray([frame.get_positions()[:4] for frame in frames]),np.broadcast_to(ads.get_positions()[:4],(32,4,3)))
            self.publish("adsorbate-mode-"+label,f"Adsorbate mode {index} · {signed[index]:.1f} cm⁻¹",
                "Fixed (LiF)₂ host; PBE/def2-SVP analytical adsorbate Hessian. Maximum displayed atom displacement: 0.15 Å.",
                Viewer(frames,height=370,script_url=self.runtime+"/tako-viewer.js",look={"background":"white",**element_look(frames[0]),"atom_colors":["#a8aeb7"]*4+[None,None,None]}),
                {"kind":"analytical_normal_mode","method":"PBE/def2-SVP","derivatives":"analytical","mode_index":index,
                 "frequency_cm_inv":float(signed[index]),"display_amplitude_angstrom":.15,"fixed_host_indices":[0,1,2,3]})
        spectrum=plot.vibration(signed.tolist(),title="(LiF)₂–H₂O adsorbate modes · analytical partial Hessian")
        spectrum.script_url=self.runtime+"/tako-plot.js";spectrum.write_html(self.output/"adsorbate-mode-spectrum.html")
        save_json(self.output/"adsorbate-mode-spectrum.json",{**mode_data,"weights":"Equal weights; IR intensities are not calculated"})
        self.records.append({"id":"adsorbate-mode-spectrum","title":"Fixed-host adsorbate spectrum","kind":"analytical_vibration_spectrum","html":"adsorbate-mode-spectrum.html","data":"adsorbate-mode-spectrum.json"})
        host=Atoms("LiFLiF",positions=ads.get_positions()[:4]);host.calc=molecular_pbe()
        water=self.water
        energy_terms={"complex_ev":ads.get_potential_energy(),"frozen_host_ev":host.get_potential_energy(),
                      "relaxed_gas_water_ev":water.get_potential_energy()}
        energy_terms["adsorption_energy_ev"]=energy_terms["complex_ev"]-energy_terms["frozen_host_ev"]-energy_terms["relaxed_gas_water_ev"]
        save_json(self.output/"adsorption-energy.json",{"method":"PBE/def2-SVP","energy_terms":energy_terms,
                  "reference":"Frozen LiF host + relaxed isolated water; zero-temperature electronic energy, no counterpoise correction"})
        energy_plot=plot.bar(["Frozen host + gas water","Adsorbed complex"],[0,energy_terms["adsorption_energy_ev"]],
                             y_label="Electronic energy relative to fragments (eV)",title="PBE/def2-SVP adsorption reference")
        energy_plot.script_url=self.runtime+"/tako-plot.js";energy_plot.write_html(self.output/"adsorption-energy.html")
        self.records.append({"id":"adsorption-energy","title":"Adsorption energy reference","kind":"electronic_energy_difference","html":"adsorption-energy.html","data":"adsorption-energy.json"})
        (self.output/"adsorption.h5").write_bytes(ads.calc.get_wavefunction(format="hdf5",atoms=ads))
        self.adsorption_scan()
        self.structure("water-indices","Atom indices and geometric measurements",water,tags="index",description="The atom order belongs to this structure: O is index 0, H atoms are 1 and 2.",measurements=[{"indices":[0,1]},{"indices":[1,0,2]}])
        for name,atoms in [("silicon-primitive",bulk("Si","diamond",a=5.43)),("silicon-cubic",bulk("Si","diamond",a=5.43,cubic=True)),("nacl-repeat",bulk("NaCl","rocksalt",a=5.64,cubic=True).repeat((2,2,1)))]:
            self.structure(name,name.replace("-"," ").title(),atoms,description="Native builder geometry. Inspect the cell, atom count, and periodic images before calculation.",cell=True,tags=False)
        slab=fcc111("Pt",size=(2,2,3),a=3.92,vacuum=6.0)
        co_bond=molecule("CO").get_distance(0,1)
        co=Atoms("CO",positions=[[0,0,0],[0,0,co_bond]])
        top=slab.get_positions()[np.argmax(slab.get_positions()[:,2]),:2]
        add_adsorbate(slab,co,height=1.8,position=top)
        self.structure("co-on-pt","A slab and its adsorbate",slab,tags={len(slab)-2:"C",len(slab)-1:"O"},description="Builder geometry only: Pt(111), three layers, CO at an ontop site. No adsorption energy or relaxed bond length is claimed.",cell=True)
        dos=water.calc.get_dos(width=.3,npts=501)
        chart=plot.dos(dos,title="Water orbital spectrum · PBE/def2-SVP");chart.script_url=self.runtime+"/tako-plot.js";chart.write_html(self.output/"water-dos.html")
        save_json(self.output/"water-dos.json",{"kind":"electronic_dos","method":"PBE/def2-SVP","energy_reference":dos.get("energy_reference"),"width_ev":.3,"data":dos})
        self.records.append({"id":"water-dos","title":"Water orbital spectrum","kind":"electronic_dos","html":"water-dos.html","data":"water-dos.json"})
        charges=water.calc.get_atomic_charges()
        self.structure("water-charges","Mulliken charge labels on a molecule",water,tags=[f"{s}: {q:+.3f} e" for s,q in zip(water.get_chemical_symbols(),charges)],description="PBE/def2-SVP Mulliken populations at the same geometry as the density. Net atomic charge is a basis-dependent partition, not a density contour.")

    def adsorption_scan(self):
        heights=np.array([1.5,1.8,2.1,2.4,2.7,3.0])
        frames,energies,forces,residuals=[],[],[],[]
        for height in heights:
            positions=np.vstack([self.adsorption.get_positions()[:4],self.water.get_positions()-self.water.get_positions()[0]])
            positions[4:,2]*=-1
            positions[4:]+=np.array([-.3,-.25,height])
            atoms=Atoms("LiFLiFOH2",positions=positions)
            atoms.set_constraint(FixAtoms(indices=[0,1,2,3,4]))
            atoms.calc=molecular_pbe()
            if not BFGS(atoms,logfile=None,maxstep=.12).run(fmax=.003,steps=100):
                raise RuntimeError("Constrained adsorption scan did not converge")
            frames.append(atoms.copy());energies.append(atoms.get_potential_energy())
            forces.append(atoms.get_forces(apply_constraint=False)[4,2])
            residuals.append(float(np.linalg.norm(atoms.get_forces(),axis=1).max()))
        relative=np.asarray(energies)-min(energies)
        chart=plot.reaction_profile(energies,coordinate=heights.tolist(),title="Fixed-site water adsorption coordinate")
        self.publish("adsorption-scan","Constrained water approach to the Li site",
            "PBE/def2-SVP; frozen host and fixed O x/y/z at each point. Only H coordinates relax. This is a constrained energy scan, not an NEB path.",
            Viewer(frames,height=370,script_url=self.runtime+"/tako-viewer.js",look={"background":"white","tags":{0:"Li site",4:"O"},**element_look(frames[0],True),"atom_colors":["#a8aeb7"]*4+[None,None,None]}),
            {"kind":"constrained_adsorption_scan","method":"PBE/def2-SVP","coordinate":"O z above host plane; O x/y fixed at -0.30/-0.25 angstrom",
             "heights_angstrom":heights,"energy_ev":energies,"relative_to_minimum_ev":relative,"oxygen_force_z_ev_per_angstrom":forces,
             "projected_fmax_ev_per_angstrom":residuals,"positions_angstrom":[frame.get_positions() for frame in frames]},chart,
             "Each frame is an independently relaxed constrained geometry. Recorded coordinate forces are analytical.",chart_label="Energy profile")
        write(self.output/"adsorption-scan.extxyz",frames)

    def finish(self):
        save_json(self.output/"manifest.json",{"schema":"atomli-visual-tutorials-v1","examples":self.records,
                  "nuclear_derivatives":"analytical only","field_renderer":"Tako snapshot cubeLayers / isosurfaces",
                  "constraint_motion":"Converged constrained PBE/def2-SVP optimizations of (LiF)2–H2O"})
        print(f"Wrote {len(self.records)} interactive tutorials to {self.output}")


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output",type=Path,default=Path("visual-tutorials"))
    parser.add_argument("--runtime",default="https://tako.atom.li/embed",help="Directory containing tako-viewer.js and tako-plot.js")
    args=parser.parse_args()
    started=time.monotonic();tutorials=Tutorials(args.output,args.runtime)
    tutorials.fields();tutorials.constraints();tutorials.workflows();tutorials.finish()
    print(f"Elapsed: {time.monotonic()-started:.2f} s")


if __name__=="__main__":
    main()
