
#!/usr/bin/env python3
"""
Live convergence dashboard for discover_rc.py.

Reads:
    candidate_history.jsonl

Optionally reads:
    discoveries.jsonl

Does not modify either file.

Run:
    py rc_dashboard.py

Open:
    http://127.0.0.1:8765
"""

from __future__ import annotations

import json
import time
import threading
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse


HISTORY = Path("candidate_history.jsonl")
HOST = "127.0.0.1"
PORT = 8765
WINDOW = 500


class Monitor:
    def __init__(self):
        self.lock = threading.Lock()
        self.offset = 0
        self.partial = b""
        self.started = time.time()

        self.candidates = 0
        self.unique = 0
        self.duplicates = 0

        self.by_depth = defaultdict(int)
        self.by_height = defaultdict(int)

        self.points = []
        self.last_update = None
        self.error = None

    @staticmethod
    def rational_height(value):
        try:
            p, q = map(int, value.split("/"))
            return max(abs(p), abs(q))
        except Exception:
            return 0

    def consume(self, record):
        status = record.get("status", "")
        n = int(record.get("n", 0))
        rho = record.get("rho", "0/1")
        gamma = record.get("gamma", "0/1")

        height = max(
            self.rational_height(rho),
            self.rational_height(gamma),
        )

        self.candidates += 1

        if status == "NEW STRUCTURE":
            self.unique += 1
            self.by_depth[n] += 1
            self.by_height[height] += 1
        else:
            self.duplicates += 1

        # Keep a bounded chart history.
        if self.candidates == 1 or self.candidates % 25 == 0:
            self.points.append({
                "x": self.candidates,
                "unique": self.unique,
                "duplicates": self.duplicates,
            })

            if len(self.points) > 10000:
                self.points = self.points[::2]

        self.last_update = time.time()

    def scan(self):
        if not HISTORY.exists():
            return

        with self.lock:
            try:
                size = HISTORY.stat().st_size

                # Handle a file that was replaced or truncated.
                if size < self.offset:
                    self.offset = 0
                    self.partial = b""
                    self.candidates = 0
                    self.unique = 0
                    self.duplicates = 0
                    self.by_depth.clear()
                    self.by_height.clear()
                    self.points.clear()

                with HISTORY.open("rb") as f:
                    f.seek(self.offset)
                    data = f.read()
                    self.offset = f.tell()

                data = self.partial + data
                lines = data.split(b"\n")
                self.partial = lines.pop()

                for line in lines:
                    if not line.strip():
                        continue
                    try:
                        record = json.loads(line)
                        self.consume(record)
                    except Exception:
                        continue

                self.error = None

            except Exception as exc:
                self.error = str(exc)

    def snapshot(self):
        with self.lock:
            elapsed = max(time.time() - self.started, 0.001)
            return {
                "candidates": self.candidates,
                "unique": self.unique,
                "duplicates": self.duplicates,
                "yield": (
                    self.unique / self.candidates
                    if self.candidates else 0
                ),
                "elapsed": elapsed,
                "rate": self.candidates / elapsed,
                "last_update": self.last_update,
                "by_depth": dict(self.by_depth),
                "by_height": dict(self.by_height),
                "points": self.points[-2000:],
                "error": self.error,
            }


monitor = Monitor()


HTML = r"""
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Fractal Discovery — Live Convergence</title>
<style>
body {
    background:#10151c; color:#e6edf3;
    font:15px system-ui; margin:0; padding:24px;
}
h1 {font-size:23px;margin:0 0 5px}
.sub {color:#8b9aaa;margin-bottom:22px}
.metrics {
    display:grid;grid-template-columns:repeat(4,minmax(130px,1fr));
    gap:12px;margin-bottom:18px
}
.metric,.panel {
    background:#19232e;border:1px solid #2b3948;
    border-radius:10px;padding:16px
}
.value {font-size:30px;font-weight:650}
.label {color:#9aabba;font-size:12px}
.panels {
    display:grid;grid-template-columns:1fr 1fr;gap:14px
}
.panel h2 {font-size:15px;margin:0 0 12px}
canvas {width:100%;height:250px;display:block}
.status {color:#9aabba;font-size:12px;margin-top:16px}
@media(max-width:760px) {
    .metrics {grid-template-columns:1fr 1fr}
    .panels {grid-template-columns:1fr}
}
</style>
</head>
<body>
<h1>Fractal Discovery Engine</h1>
<div class="sub">Exact RC transfer structures · live convergence monitor</div>

<div class="metrics">
 <div class="metric"><div class="value" id="candidates">0</div>
 <div class="label">Candidates evaluated</div></div>
 <div class="metric"><div class="value" id="unique">0</div>
 <div class="label">Unique exact structures</div></div>
 <div class="metric"><div class="value" id="yield">0%</div>
 <div class="label">Unique discovery yield</div></div>
 <div class="metric"><div class="value" id="duplicates">0</div>
 <div class="label">Repeated structures</div></div>
</div>

<div class="panels">
 <div class="panel">
  <h2>Unique structures discovered</h2>
  <canvas id="growth"></canvas>
 </div>
 <div class="panel">
  <h2>Repeated structures</h2>
  <canvas id="duplicatesChart"></canvas>
 </div>
 <div class="panel">
  <h2>New structures by rational height</h2>
  <canvas id="height"></canvas>
 </div>
 <div class="panel">
  <h2>New structures by ladder depth</h2>
  <canvas id="depth"></canvas>
 </div>
</div>
<div class="status" id="status">Connecting…</div>

<script>
const $ = id => document.getElementById(id);
const fmt = n => Number(n).toLocaleString();

function plot(id, labels, values, title) {
    const canvas = $(id);
    const rect = canvas.getBoundingClientRect();
    const dpr = window.devicePixelRatio || 1;
    canvas.width = rect.width*dpr;
    canvas.height = rect.height*dpr;

    const ctx = canvas.getContext("2d");
    ctx.scale(dpr,dpr);

    const w=rect.width,h=rect.height;
    const L=48,R=12,T=12,B=30;
    const pw=w-L-R,ph=h-T-B;

    ctx.clearRect(0,0,w,h);
    const max=Math.max(1,...values);
    ctx.font="11px system-ui";
    ctx.fillStyle="#8b9aaa";
    ctx.strokeStyle="#354454";

    for(let i=0;i<=4;i++) {
        const y=T+ph*i/4;
        ctx.beginPath();
        ctx.moveTo(L,y);ctx.lineTo(w-R,y);ctx.stroke();
        ctx.fillText(
            Math.round(max*(1-i/4)).toLocaleString(),
            3,y+4
        );
    }

    if(values.length<1)return;

    ctx.strokeStyle="#65c7a2";
    ctx.lineWidth=2;
    ctx.beginPath();

    values.forEach((v,i)=>{
        const x=L+(values.length===1?0:pw*i/(values.length-1));
        const y=T+ph*(1-v/max);
        if(i===0)ctx.moveTo(x,y);else ctx.lineTo(x,y);
    });
    ctx.stroke();

    ctx.fillStyle="#8b9aaa";
    ctx.fillText("earlier",L,h-7);
    ctx.fillText("latest",w-R-35,h-7);
}

function bars(id, obj) {
    const keys=Object.keys(obj).map(Number).sort((a,b)=>a-b);
    const values=keys.map(k=>obj[k]);
    const canvas=$(id);
    const rect=canvas.getBoundingClientRect();
    const dpr=window.devicePixelRatio||1;
    canvas.width=rect.width*dpr;
    canvas.height=rect.height*dpr;
    const ctx=canvas.getContext("2d");
    ctx.scale(dpr,dpr);

    const w=rect.width,h=rect.height;
    const L=38,R=8,T=12,B=28;
    const pw=w-L-R,ph=h-T-B;
    const max=Math.max(1,...values);
    ctx.clearRect(0,0,w,h);
    ctx.font="11px system-ui";
    ctx.fillStyle="#8b9aaa";
    ctx.fillText("count",4,12);

    if(!keys.length)return;

    const step=pw/keys.length;
    keys.forEach((k,i)=>{
        const bh=ph*values[i]/max;
        const x=L+i*step+2;
        const y=T+ph-bh;
        ctx.fillStyle="#65c7a2";
        ctx.fillRect(x,y,Math.max(2,step-4),bh);
        ctx.fillStyle="#9aabba";
        ctx.fillText(String(k),x,h-8);
    });
}

let latest=null;

async function refresh() {
    try {
        const response=await fetch("/data?t="+Date.now());
        const d=await response.json();
        latest=d;

        $("candidates").textContent=fmt(d.candidates);
        $("unique").textContent=fmt(d.unique);
        $("duplicates").textContent=fmt(d.duplicates);
        $("yield").textContent=(100*d.yield).toFixed(2)+"%";

        const points=d.points;
        plot("growth",[],points.map(p=>p.unique));
        plot("duplicatesChart",[],points.map(p=>p.duplicates));
        bars("height",d.by_height);
        bars("depth",d.by_depth);

        $("status").textContent =
          "Monitoring candidate_history.jsonl · " +
          d.rate.toFixed(1)+" records/sec since dashboard start" +
          (d.error ? " · Error: "+d.error : "");

    } catch(e) {
        $("status").textContent="Waiting for discovery history file… "+e;
    }
}

setInterval(refresh,1000);
window.addEventListener("resize",()=>{if(latest)refresh()});
refresh();
</script>
</body>
</html>
"""


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        path = urlparse(self.path).path

        if path == "/":
            payload = HTML.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)
            return

        if path == "/data":
            monitor.scan()
            payload = json.dumps(monitor.snapshot()).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)
            return

        self.send_error(404)

    def log_message(self, *_):
        pass


def main():
    print("FRACTAL CONVERGENCE DASHBOARD")
    print(f"History: {HISTORY.resolve()}")
    print(f"Address: http://{HOST}:{PORT}")
    print("Reading existing history, then following new records.")
    print("Press Ctrl+C to stop.")

    monitor.scan()

    server = ThreadingHTTPServer((HOST, PORT), Handler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nDashboard stopped.")
    finally:
        server.server_close()


if __name__ == "__main__":
    main()
