import csv
import io
import json
from komorebi_browser import show_plot, export_file

if uploaded_files:
    name = sorted(uploaded_files)[0]
    text = uploaded_files[name]
    rows = json.loads(text) if name.lower().endswith(".json") else list(csv.DictReader(io.StringIO(text)))
    print("Using:", name)
else:
    rows = [{"x": 0, "y": 1}, {"x": 1, "y": 3}, {"x": 2, "y": 5}, {"x": 3, "y": 7}]
    print("Using sample data.")
x, y = [float(r["x"]) for r in rows], [float(r["y"]) for r in rows]
show_plot([{"x": x, "y": y, "mode": "lines+markers", "name": "Data"}],
          {"title": {"text": "Your x,y data"},
           "xaxis": {"title": {"text": "x"}}, "yaxis": {"title": {"text": "y"}}},
          description=f"A plot of {len(rows)} supplied x,y pairs. Inspect the data table for the numbers.")
export_file("processed-data.json", json.dumps([{"x": a, "y": b} for a,b in zip(x,y)], indent=2))
print(f"Plotted {len(rows)} rows.")
