#!/usr/bin/env python3
"""Noema mirror node (read-only, standard library only).

It downloads the blocks of the main server, re-computes EVERY hash itself, checks the links
between blocks and raises an alert if the main server ever rewrites history it already served.
It never issues puzzles and never measures time: only the main server does that.

  python3 node.py --upstream https://solve.vasko.blog --port 8081
  python3 node.py --once          # verify once, print the result and exit
"""
import argparse, hashlib, json, sqlite3, threading, time, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

ZERO = "0" * 64
state = {"status": "starting", "error": "", "last_sync": 0, "upstream_height": None}


def block_hash(b):
    return hashlib.sha256(f"{b['height']}|{b['prev_hash']}|{b['root']}|{int(b['ts'])}|{b['difficulty']}|"
                          f"{b['n_solves']}|{b['reward']}".encode()).hexdigest()


def get(url):
    req = urllib.request.Request(url, headers={"User-Agent": "noema-mirror/1"})
    with urllib.request.urlopen(req, timeout=20) as r:
        return json.load(r)


def alert(msg):
    state.update(status="ALERT", error=msg)
    return False


def sync(db, up):
    """Returns True when fully synced and valid, False on alert."""
    while True:
        tip = db.execute("SELECT height, hash FROM blocks ORDER BY height DESC LIMIT 1").fetchone()
        batch = get(f"{up}/api/chain/export?start={tip[0] if tip else 0}&limit=500")
        if tip:
            if not batch or batch[0]["hash"] != tip[1]:
                return alert(f"The main server's history differs from my copy at block {tip[0]}.")
            batch = batch[1:]
        prev, expected = (tip[1], tip[0] + 1) if tip else (None, 0)
        for b in batch:
            if b["height"] != expected:
                return alert(f"Missing or reordered block at height {expected}.")
            if block_hash(b) != b["hash"]:
                return alert(f"Block {b['height']} has an invalid hash.")
            if (prev is None and b["prev_hash"] != ZERO) or (prev is not None and b["prev_hash"] != prev):
                return alert(f"Block {b['height']} does not link to the previous block.")
            db.execute("INSERT INTO blocks VALUES(?,?,?,?,?,?,?,?,?)", (b["height"], b["hash"], b["prev_hash"], b["root"],
                       b["ts"], b["difficulty"], b["n_solves"], b["miners"], b["reward"]))
            prev, expected = b["hash"], expected + 1
        db.commit()
        if len(batch) < 499:
            state.update(status="OK", error="", last_sync=time.time())
            try:
                state["upstream_height"] = get(f"{up}/api/chain")["height"]
            except Exception:
                pass
            return True


def open_db(path):
    db = sqlite3.connect(path)
    db.execute("CREATE TABLE IF NOT EXISTS blocks(height INTEGER PRIMARY KEY, hash TEXT, prev_hash TEXT, root TEXT, "
               "ts INTEGER, difficulty INTEGER, n_solves INTEGER, miners INTEGER, reward INTEGER)")
    return db


def loop(path, up, interval):
    db = open_db(path)
    while True:
        try:
            if state["status"] == "ALERT" or not sync(db, up):
                return          # keep the evidence: stop syncing after an alert
        except Exception as e:
            state.update(status="OFFLINE", error=str(e)[:200])
        time.sleep(interval)


PAGE = """<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1">
<title>Noema mirror</title><body style="font:16px/1.5 system-ui;background:#0e1012;color:#e8eaec;max-width:860px;margin:30px auto;padding:0 16px">
<h2>Noema mirror node</h2><p>Status: <b style="color:%(color)s">%(status)s</b> %(error)s</p>
<p>Blocks verified: <b>%(n)s</b> &middot; Tip: <b>#%(tip)s</b> &middot; Main server tip: <b>%(up)s</b></p>
<p>Genesis hash: <code style="word-break:break-all">%(gen)s</code></p>
<table style="width:100%%;border-collapse:collapse;font-family:monospace;font-size:.85rem"><tr style="color:#8a949d"><td>Height<td>Hash<td>Solves<td>Reward (NOE)</tr>%(rows)s</table>
<p style="color:#8a949d">Every hash above was recomputed locally. This node never issues puzzles or measures time.</p>"""


def make_handler(path):
    class H(BaseHTTPRequestHandler):
        def log_message(self, *a):
            pass

        def do_GET(self):
            db = sqlite3.connect(path)
            n, tip = db.execute("SELECT COUNT(*), COALESCE(MAX(height),-1) FROM blocks").fetchone()
            if self.path.startswith("/api/status"):
                body, ctype = json.dumps(dict(state, blocks=n, tip=tip)), "application/json"
            else:
                gen = db.execute("SELECT hash FROM blocks WHERE height=0").fetchone()
                rows = "".join(f"<tr><td>#{h}<td>{x[:12]}…{x[-6:]}<td>{s}<td>{r / 100:.2f}</tr>" for h, x, s, r in db.execute(
                    "SELECT height,hash,n_solves,reward FROM blocks ORDER BY height DESC LIMIT 15"))
                color = {"OK": "#4cc38a", "ALERT": "#ef6b6b"}.get(state["status"], "#e08a3c")
                body, ctype = PAGE % {"color": color, "status": state["status"], "error": state["error"], "n": n, "tip": tip,
                                     "up": state["upstream_height"], "gen": gen[0] if gen else "-", "rows": rows}, "text/html"
            db.close()
            self.send_response(200); self.send_header("Content-Type", ctype + "; charset=utf-8"); self.end_headers()
            self.wfile.write(body.encode())
    return H


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--upstream", default="https://solve.vasko.blog")
    p.add_argument("--port", type=int, default=8081)
    p.add_argument("--db", default="noema-mirror.db")
    p.add_argument("--interval", type=int, default=60)
    p.add_argument("--once", action="store_true")
    a = p.parse_args()
    up = a.upstream.rstrip("/")
    if a.once:
        db = open_db(a.db)
        try:
            ok = sync(db, up)
        except Exception as e:
            raise SystemExit(f"Could not reach {up}: {e}")
        n = db.execute("SELECT COUNT(*) FROM blocks").fetchone()[0]
        print(f"{'OK' if ok else 'ALERT'}: {n} blocks verified. {state['error']}")
        raise SystemExit(0 if ok else 1)
    threading.Thread(target=loop, args=(a.db, up, a.interval), daemon=True).start()
    print(f"Mirror running on http://0.0.0.0:{a.port}  (upstream {up})")
    ThreadingHTTPServer(("0.0.0.0", a.port), make_handler(a.db)).serve_forever()
