"""
HeatDebt live dashboard - shows the current exposure score plus a live
chart of the score over time. Reads heatdebt_log.csv, the same file
heatdebt.py writes to.

Run alongside heatdebt.py:  python dashboard.py
Then visit http://<pi-ip>:5000 for a live demo (great for the writeup video).
"""

import csv
import os

from flask import Flask, jsonify, render_template_string

import config

app = Flask(__name__)

TEMPLATE = """
<!doctype html>
<title>HeatDebt</title>
<style>
  body { font-family: sans-serif; max-width: 600px; margin: 40px auto; text-align: center; }
  .level-OK { color: green; }
  .level-WARNING { color: goldenrod; }
  .level-BREAK { color: darkorange; }
  .level-DANGER { color: red; font-weight: bold; }
  .card { border: 1px solid #ccc; border-radius: 12px; padding: 20px; margin-top: 20px; }
  canvas { max-width: 100%; }
</style>
<h1>HeatDebt</h1>
{% if row %}
<div class="card">
  <p>Temp: {{ row.temp_c }}C</p>
  <p>Exposure score: <strong>{{ row.exposure_score }}</strong></p>
  <p class="level-{{ row.alert_level }}">Status: {{ row.alert_level }}</p>
  <p><small>Last updated: {{ row.timestamp }}</small></p>
</div>
<div class="card">
  <canvas id="chart" height="200"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
async function loadChart() {
  const res = await fetch('/data.json');
  const data = await res.json();
  new Chart(document.getElementById('chart'), {
    type: 'line',
    data: {
      labels: data.map(d => d.timestamp),
      datasets: [{
        label: 'Exposure score',
        data: data.map(d => d.exposure_score),
        borderColor: '#d9480f',
        tension: 0.2,
        pointRadius: 0,
      }]
    },
    options: {
      scales: { x: { display: false } },
      plugins: { legend: { display: false } }
    }
  });
}
loadChart();
setTimeout(() => location.reload(), 15000);
</script>
{% else %}
<p>No data yet - start heatdebt.py first.</p>
{% endif %}
"""


def read_rows(limit=200):
    if not os.path.exists(config.LOG_CSV_PATH):
        return []
    with open(config.LOG_CSV_PATH) as f:
        rows = list(csv.DictReader(f))
    return rows[-limit:]


@app.route("/")
def index():
    rows = read_rows()
    row = rows[-1] if rows else None
    return render_template_string(TEMPLATE, row=row)


@app.route("/data.json")
def data_json():
    rows = read_rows()
    return jsonify([
        {"timestamp": r["timestamp"], "exposure_score": float(r["exposure_score"])}
        for r in rows if r.get("exposure_score")
    ])


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=False)
