import csv
import io
from math import sin, sqrt
from komorebi_browser import show_plot, export_file

momentum = (1, 2, -1)
spacings = [0.5, 0.25, 0.125, 0.0625]
if any(h == 0 for h in spacings):
    raise ValueError("Use nonzero spacings; the bounded global operator has a separate zero-spacing convention.")
ks = [-4+j/20 for j in range(161)]
traces = [{"x": ks, "y": ks, "name": "Continuum k", "mode": "lines", "line": {"dash": "dash"}}]
for h in spacings[:2]:
    traces.append({"x": ks, "y": [sin(h*k)/h for k in ks], "name": f"Centered, h={h}", "mode": "lines"})
show_plot(traces, {"title": {"text": "Centered spatial symbol"},
    "xaxis": {"title": {"text": "Momentum coordinate k"}},
    "yaxis": {"title": {"text": "Symbol"}}},
    description="The continuum symbol is the line k. Centered symbols sin(h k)/h approach that line at each fixed k as the nonzero spacing tends to zero. This plot uses a fixed momentum window.")

moment = sqrt(sum(k**6 for k in momentum))
rows = [(h, sqrt(sum((sin(h*k)/h-k)**2 for k in momentum)), h*h*moment/6) for h in spacings]
show_plot([
    {"x": spacings, "y": [row[1] for row in rows], "name": "Modal symbol error", "mode": "lines+markers"},
    {"x": spacings, "y": [row[2] for row in rows], "name": "h squared times sqrt(66) / 6", "mode": "lines+markers", "line": {"dash": "dash"}},
], {"title": {"text": "Quadratic error at fixed momentum (1, 2, -1)"},
    "xaxis": {"title": {"text": "Nonzero spacing h"}, "type": "log"},
    "yaxis": {"title": {"text": "Error or envelope"}, "type": "log"}},
    description="Four fixed-momentum symbol errors lie below the h-squared envelope. This is a finite floating-point illustration, with values available as CSV. It does not test arbitrary infinite Fourier series or a changing finite lattice.")
stream = io.StringIO(newline="")
writer = csv.writer(stream, lineterminator="\n")
writer.writerow(["h", "modal_symbol_error", "quadratic_envelope"])
writer.writerows(rows)
export_file("centered-modal-errors.csv", stream.getvalue())
print("Fixed momentum:", momentum)
print("Spacings:", ", ".join(map(str, spacings)))
print("Exported 4 modal error comparisons.")
print("These floating-point samples illustrate the bound; the Lean source supplies the general theorem.")
