#!/usr/bin/env python3
"""Fireplace v1: link the machines you already own.

Run on your main computer:      python fireplace.py
Run on each extra computer:     python fireplace.py --join "XXXX XXXX XXXX XXXX"
Link a phone:                   open fireplace.sh/heatcheck and type the link code

Standard library only. Models run through Ollama (https://ollama.com) on each computer.
"""
import argparse, base64, hashlib, hmac, json, os, platform, secrets, socket, subprocess, sys
import threading, time, urllib.error, urllib.request, webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

VERSION = "1.0.0"
PORT = 7411
HOME = Path(os.environ.get("FIREPLACE_HOME", Path.home() / ".fireplace"))
OLLAMA = os.environ.get("OLLAMA_HOST", "http://127.0.0.1:11434").rstrip("/")
JOB_LIMIT = int(os.environ.get("FIREPLACE_JOB_LIMIT", "120"))   # seconds before Timekeeper stops a job
CODE_LIFETIME = 600                                              # seconds a link code stays valid
ONLINE_WINDOW = 45                                               # seconds since last heartbeat

# Role and model for each size of device. Edit ~/.fireplace/models.json to change these
# without touching the code. Model names are Ollama tags: confirm them with `ollama list`.
DEFAULT_TIERS = [
    {"min_gb": 16, "gpu": True,  "role": "Think Tank", "model": "gpt-oss:20b", "job": "Research and long reasoning"},
    {"min_gb": 12, "gpu": True,  "role": "Vision",     "model": "gemma4:12b",  "job": "Detailed image analysis"},
    {"min_gb": 6,  "gpu": True,  "role": "Vision",     "model": "gemma4:e4b",  "job": "Image analysis and chat"},
    {"min_gb": 8,  "gpu": False, "role": "Clerk",      "model": "phi4-mini",   "job": "Sorting, routing and short summaries"},
    {"min_gb": 0,  "gpu": False, "role": "Scout",      "model": "",            "job": "Too small to run a model. Uses the fire."},
]
ROLE_RANK = {"Think Tank": 3, "Vision": 2, "Clerk": 1, "Scout": 0}

LOCK = threading.RLock()
STATE = {"devices": {}, "hub": None}      # linked devices, and the hub this node joined (if any)
CODES = {}                                # one time link secrets -> expiry time
JOBS = {}                                 # running and recent jobs, watched by Timekeeper
EVENTS = []                               # watch agent activity, newest first
AGENTS = {"timekeeper": "starting", "sentry": "starting", "paused": False, "pause_reason": ""}
ME = {}


# ---------------------------------------------------------------- hardware

def ram_gb():
    try:
        if sys.platform.startswith("linux"):
            for line in open("/proc/meminfo"):
                if line.startswith("MemTotal"):
                    return int(line.split()[1]) / 1048576
        if sys.platform == "darwin":
            return int(subprocess.check_output(["sysctl", "-n", "hw.memsize"])) / 2**30
        if sys.platform == "win32":
            import ctypes
            class MS(ctypes.Structure):
                _fields_ = [("len", ctypes.c_ulong), ("load", ctypes.c_ulong)] + [(n, ctypes.c_ulonglong) for n in
                            ("total", "avail", "tpage", "apage", "tvirt", "avirt", "aext")]
            m = MS(); m.len = ctypes.sizeof(MS); ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m))
            return m.total / 2**30
    except Exception:
        pass
    return 0.0


def gpu():
    """Return (name, vram_gb) for the largest dedicated GPU, or (None, 0)."""
    try:
        out = subprocess.check_output(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"],
                                      stderr=subprocess.DEVNULL, timeout=5).decode()
        cards = [(n.strip(), int(m) / 1024) for n, m in (l.rsplit(",", 1) for l in out.strip().splitlines() if "," in l)]
        if cards:
            return max(cards, key=lambda c: c[1])
    except Exception:
        pass
    if sys.platform == "darwin" and platform.machine() == "arm64":
        return ("Apple Silicon (shared memory)", ram_gb())
    return (None, 0.0)


def load_tiers():
    try:
        return json.loads((HOME / "models.json").read_text())
    except Exception:
        return DEFAULT_TIERS


def read_hardware():
    ram = round(ram_gb()); name, vram = gpu(); vram = round(vram)
    has_gpu = bool(name) and vram >= 4
    degrees = vram if has_gpu else ram          # 1 degree = 1 GB this device can put to work
    tier = next(t for t in load_tiers() if degrees >= t["min_gb"] and (has_gpu or not t["gpu"]))
    spec = f"{name}, {vram} GB" if has_gpu else f"{ram} GB RAM, CPU class"
    return {"degrees": degrees, "spec": spec, "role": tier["role"], "model": tier["model"], "job": tier["job"]}


def lan_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("10.255.255.255", 1)); return s.getsockname()[0]
    except Exception:
        return "127.0.0.1"
    finally:
        s.close()


# ---------------------------------------------------------------- keys and state

def load_identity():
    HOME.mkdir(parents=True, exist_ok=True)
    f = HOME / "device.json"
    if f.exists():
        return json.loads(f.read_text())
    ident = {"id": secrets.token_hex(6), "name": platform.node() or "This device", "key": secrets.token_hex(32)}
    f.write_text(json.dumps(ident)); os.chmod(f, 0o600)     # keys are made here and never leave
    return ident


def save_state():
    f = HOME / "state.json"
    f.write_text(json.dumps(STATE)); os.chmod(f, 0o600)


def load_state():
    try:
        STATE.update(json.loads((HOME / "state.json").read_text()))
    except Exception:
        pass


def event(agent, text, level="ok"):
    with LOCK:
        EVENTS.insert(0, {"t": int(time.time()), "agent": agent, "text": text, "level": level})
        del EVENTS[50:]
    print(f"[{agent}] {text}", flush=True)


def new_code():
    """A link code is 10 bytes in base32: this computer's home address (4), port (2), one time secret (4)."""
    secret = secrets.token_bytes(4)
    with LOCK:
        now = time.time()
        for k in [k for k, exp in CODES.items() if exp < now]:
            del CODES[k]
        CODES[secret.hex()] = now + CODE_LIFETIME
    raw = socket.inet_aton(ME["ip"]) + ME["port"].to_bytes(2, "big") + secret
    c = base64.b32encode(raw).decode()
    return " ".join(c[i:i + 4] for i in range(0, 16, 4))


def decode_code(code):
    c = "".join(ch for ch in code.upper() if ch.isalnum())
    if len(c) != 16:
        raise ValueError("A link code has 16 characters.")
    raw = base64.b32decode(c)
    return socket.inet_ntoa(raw[:4]), int.from_bytes(raw[4:6], "big"), raw[6:].hex()


def temperature():
    with LOCK:
        return ME["degrees"] + sum(d["degrees"] for d in STATE["devices"].values() if d["kind"] == "computer")


def online(d):
    return d["kind"] == "phone" or time.time() - d.get("last_seen", 0) < ONLINE_WINDOW


# ---------------------------------------------------------------- watch agents

def sentry():
    """Checks Fireplace's own file and key permissions. On any change it fails closed: no new jobs."""
    path = Path(__file__).resolve()
    digest = lambda: hashlib.sha256(path.read_bytes()).hexdigest()
    manifest = HOME / "manifest.json"
    known = json.loads(manifest.read_text()).get("fireplace.py") if manifest.exists() else None
    base = digest()
    if known and known != base:
        pause("Fireplace does not match its release manifest."); return
    event("Sentry", "Checked against the release manifest." if known else
          "No release manifest found, so this copy was recorded as the baseline (unsigned build).")
    AGENTS["sentry"] = "running"
    while True:
        time.sleep(float(os.environ.get("FIREPLACE_SENTRY_EVERY", "20")))
        try:
            if digest() != base:
                pause("Fireplace's own file changed while running.")
            elif os.name == "posix" and (HOME / "device.json").stat().st_mode & 0o077:
                pause("The key file can be read by other users on this computer.")
        except Exception as e:
            pause(f"Sentry could not read a file it guards ({e}).")
        if AGENTS["paused"]:
            return


def pause(reason):
    AGENTS.update(paused=True, pause_reason=reason, sentry="needs review")
    event("Sentry", reason + " New jobs are paused. Check the file, then restart Fireplace to resume.", "warn")


def timekeeper():
    """Watches every job. Past the limit it marks the job stopped so the device is free again."""
    AGENTS["timekeeper"] = "running"
    while True:
        time.sleep(1)
        now = time.time()
        with LOCK:
            for jid, j in list(JOBS.items()):
                if j["status"] == "running" and now - j["start"] > JOB_LIMIT:
                    j["status"] = "timed out"
                    event("Timekeeper", f"Job on {j['device']} ran past {JOB_LIMIT}s and was stopped.", "warn")
                if j["status"] != "running" and now - j["start"] > 600:
                    del JOBS[jid]


# ---------------------------------------------------------------- running jobs

def http_json(url, payload=None, headers=None, timeout=10):
    data = None if payload is None else json.dumps(payload).encode()
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json", **(headers or {})})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read() or b"{}")


def run_local(prompt):
    if not ME["model"]:
        raise RuntimeError("This device is too small to run a model.")
    try:
        out = http_json(f"{OLLAMA}/api/generate", {"model": ME["model"], "prompt": prompt, "stream": False}, timeout=JOB_LIMIT)
    except urllib.error.HTTPError as e:
        raise RuntimeError(f"Ollama does not have {ME['model']} yet. Run: ollama pull {ME['model']}") from e
    except (urllib.error.URLError, ConnectionError) as e:
        raise RuntimeError("Ollama is not running on this computer. Start Ollama and try again.") from e
    except (TimeoutError, socket.timeout) as e:
        event("Timekeeper", f"A job on {ME['name']} ran past {JOB_LIMIT}s and was stopped.", "warn")
        raise RuntimeError(f"The job ran past {JOB_LIMIT} seconds and Timekeeper stopped it.") from e
    return out.get("response", "")


def ask(prompt):
    """Send the job to the strongest device that is online. Remote nodes get a signed request."""
    if AGENTS["paused"]:
        raise RuntimeError("Sentry has paused this fire: " + AGENTS["pause_reason"])
    with LOCK:
        nodes = [d for d in STATE["devices"].values() if d["kind"] == "computer" and d.get("model") and online(d)]
    best = max(nodes, key=lambda d: (ROLE_RANK.get(d["role"], 0), d["degrees"]), default=None)
    mine = (ROLE_RANK.get(ME["role"], 0), ME["degrees"]) if ME["model"] else (-1, 0)
    remote = best is not None and (ROLE_RANK.get(best["role"], 0), best["degrees"]) > mine
    target = best if remote else None
    jid = secrets.token_hex(4)
    with LOCK:
        JOBS[jid] = {"start": time.time(), "device": target["name"] if target else ME["name"], "status": "running"}
    try:
        if target:
            body = {"prompt": prompt}
            sig = hmac.new(target["token"].encode(), json.dumps(body).encode(), hashlib.sha256).hexdigest()
            try:
                out = http_json(target["url"] + "/api/run", body, {"X-Fireplace-Sig": sig}, timeout=JOB_LIMIT + 5)
            except urllib.error.HTTPError as e:
                raise RuntimeError(target["name"] + ": " + json.loads(e.read() or b"{}").get("error", "refused the job.")) from e
            except Exception as e:
                raise RuntimeError(f"Could not reach {target['name']}.") from e
            text = out.get("response", "")
        else:
            text = run_local(prompt)
        with LOCK:
            if JOBS[jid]["status"] == "running":
                JOBS[jid]["status"] = "done"
        return {"response": text, "device": JOBS[jid]["device"], "model": (target or ME)["model"]}
    except Exception:
        with LOCK:
            if JOBS[jid]["status"] == "running":
                JOBS[jid]["status"] = "failed"
        raise


# ---------------------------------------------------------------- web server

class Handler(BaseHTTPRequestHandler):
    server_version = "Fireplace/" + VERSION

    def log_message(self, *a):
        pass

    def local(self):
        return self.client_address[0] in ("127.0.0.1", "::1", "::ffff:127.0.0.1")

    def device(self):
        token = self.headers.get("Authorization", "")[7:]
        with LOCK:
            for d in STATE["devices"].values():
                if token and hmac.compare_digest(d["token"], token):
                    return d
        return None

    def send(self, code, body, ctype="application/json"):
        data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
        self.send_response(code)
        self.send_header("Content-Type", ctype + "; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers(); self.wfile.write(data)

    def body(self):
        n = min(int(self.headers.get("Content-Length") or 0), 200000)
        raw = self.rfile.read(n) if n else b"{}"
        return raw, json.loads(raw or b"{}")

    def do_GET(self):
        path = self.path.split("?")[0].split("#")[0]
        if path == "/" and self.local():
            return self.send(200, PAGE.replace("__VIEW__", "dash"), "text/html")
        if path in ("/", "/heatcheck"):
            return self.send(200, PAGE.replace("__VIEW__", "phone"), "text/html")
        if path == "/api/state":
            dev = self.device()
            if not (self.local() or dev):
                return self.send(401, {"error": "Link this device first."})
            with LOCK:
                devs = [{"id": i, "name": d["name"], "kind": d["kind"], "degrees": d["degrees"], "spec": d["spec"],
                         "role": d["role"], "model": d.get("model", ""), "online": online(d)} for i, d in STATE["devices"].items()]
                out = {"me": {k: ME[k] for k in ("name", "degrees", "spec", "role", "model", "job")}, "devices": devs,
                       "temperature": temperature(), "agents": dict(AGENTS), "events": EVENTS[:12] if self.local() else [],
                       "hub": (STATE["hub"] or {}).get("name"), "version": VERSION}
            return self.send(200, out)
        self.send(404, {"error": "Not found."})

    def do_POST(self):
        path = self.path.split("?")[0]
        try:
            raw, data = self.body()
        except Exception:
            return self.send(400, {"error": "That request was not valid JSON."})
        try:
            if path == "/api/link":
                return self.link(data)
            if path == "/api/run":                      # the hub sending this node a job
                hub = STATE["hub"]
                sig = hmac.new(hub["token"].encode(), raw, hashlib.sha256).hexdigest() if hub else ""
                if not hub or not hmac.compare_digest(sig, self.headers.get("X-Fireplace-Sig", "")):
                    return self.send(401, {"error": "This job was not signed by the hub."})
                if AGENTS["paused"]:
                    return self.send(503, {"error": "Sentry has paused this device: " + AGENTS["pause_reason"]})
                return self.send(200, {"response": run_local(str(data.get("prompt", "")))})
            dev = self.device()
            if path == "/api/heartbeat" and dev:
                dev["last_seen"] = time.time()
                return self.send(200, {"ok": True})
            if path == "/api/ask" and (self.local() or dev):
                prompt = str(data.get("prompt", "")).strip()
                if not prompt:
                    return self.send(400, {"error": "Type something to ask."})
                return self.send(200, ask(prompt))
            if path in ("/api/ask", "/api/heartbeat"):
                return self.send(401, {"error": "Link this device first."})
            if not self.local():
                return self.send(403, {"error": "Only the computer running Fireplace can do that."})
            if path == "/api/code":
                return self.send(200, {"code": new_code(), "lifetime": CODE_LIFETIME})
            if path == "/api/remove":
                with LOCK:
                    gone = STATE["devices"].pop(str(data.get("id")), None); save_state()
                if gone:
                    event("Sentry", f"{gone['name']} was removed and its key no longer works.")
                return self.send(200, {"ok": bool(gone)})
            self.send(404, {"error": "Not found."})
        except RuntimeError as e:
            self.send(503, {"error": str(e)})

    def link(self, data):
        try:
            _, _, secret = decode_code(str(data.get("code", "")))
        except Exception:
            return self.send(400, {"error": "That link code is not valid."})
        with LOCK:
            exp = CODES.pop(secret, 0)                  # each code works once
        if exp < time.time():
            return self.send(403, {"error": "That link code has expired or was already used. Make a new one."})
        kind = "computer" if data.get("kind") == "computer" else "phone"
        dev = {"name": str(data.get("name") or "New device")[:40], "kind": kind, "token": secrets.token_urlsafe(32),
               "degrees": int(data.get("degrees") or 0) if kind == "computer" else 0,
               "spec": str(data.get("spec") or ("Phone" if kind == "phone" else ""))[:80],
               "role": str(data.get("role") or "Scout")[:20] if kind == "computer" else "Remote",
               "model": str(data.get("model") or "")[:60] if kind == "computer" else "",
               "url": str(data.get("url") or "")[:80], "last_seen": time.time()}
        with LOCK:
            STATE["devices"][secrets.token_hex(4)] = dev; save_state()
        event("Sentry", f"{dev['name']} linked with a one time code.")
        self.send(200, {"token": dev["token"], "hub": ME["name"], "temperature": temperature()})


def join(code):
    ip, port, _ = decode_code(code)
    hub = f"http://{ip}:{port}"
    out = http_json(hub + "/api/link", {"code": code, "kind": "computer", "name": ME["name"], "degrees": ME["degrees"],
                                        "spec": ME["spec"], "role": ME["role"], "model": ME["model"],
                                        "url": f"http://{ME['ip']}:{ME['port']}"})
    with LOCK:
        STATE["hub"] = {"url": hub, "token": out["token"], "name": out["hub"]}; save_state()
    print(f"Linked to {out['hub']}. The fire is now at {out['temperature']} degrees.")


def heartbeat():
    while True:
        hub = STATE["hub"]
        if hub:
            try:
                http_json(hub["url"] + "/api/heartbeat", {}, {"Authorization": "Bearer " + hub["token"]}, timeout=5)
            except Exception:
                pass
        time.sleep(15)


PAGE = r"""<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fireplace</title><style>
:root{--metal:linear-gradient(180deg,#eceef0 0%,#c6cacf 12%,#a2a8ae 38%,#b6bbc0 52%,#d2d6d9 64%,#a7adb3 86%,#959ba1 100%);color-scheme:dark}
*{box-sizing:border-box}body{margin:0;background:linear-gradient(180deg,#1b1e22,#121416 45%,#0d0f11);color:#c9ced3;font:16px/1.5 system-ui,sans-serif;min-height:100vh}
.wrap{width:min(980px,100% - 32px);margin:0 auto;padding:20px 0 40px;display:grid;gap:18px}
h1,h2,p{margin:0}.word{font-size:15px;letter-spacing:.3em;color:#e3e6e8}
.plate{position:relative;overflow:hidden;padding:20px;border-radius:12px;border:1px solid #0b0c0d;color:#14171a;background:radial-gradient(45% 26% at 64% 6%,rgba(255,255,255,.5),transparent 72%),radial-gradient(42% 22% at 20% 94%,rgba(92,78,60,.22),transparent 70%),repeating-linear-gradient(0deg,rgba(255,255,255,.05) 0 1px,transparent 1px 2px),var(--metal);box-shadow:inset 0 1px 0 rgba(255,255,255,.9),inset 0 -1px 0 rgba(0,0,0,.4),0 20px 34px -20px #000}
.brand{letter-spacing:.1em;color:#1c0f08;text-shadow:0 1px 0 rgba(255,255,255,.6),0 -1px 1px rgba(0,0,0,.55),0 0 2px rgba(255,110,30,.8),0 0 8px rgba(110,52,16,.6)}
.deg{font-size:clamp(56px,16vw,96px);line-height:1;font-weight:500}.small{font-size:12px;letter-spacing:.14em;text-transform:uppercase}
.panel{padding:16px 18px;border-radius:10px;border:1px solid #3a3f45;background:linear-gradient(180deg,#1f2327,#15181b)}
.panel h2{font-size:12px;letter-spacing:.14em;font-weight:400;color:#9aa0a6;text-transform:uppercase;margin-bottom:10px}
.row{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;padding:10px 0;border-top:1px solid #2c3136}.row:first-of-type{border-top:0}
.grow{flex:1 1 180px;min-width:0}.name{color:#f1f3f4;font-weight:600}.dim{color:#9aa0a6;font-size:13px}.ok{color:#8fd0a8}.warn{color:#e6b655}
button,.btn{min-height:46px;padding:0 16px;border-radius:8px;border:1px solid #6c7278;background:linear-gradient(180deg,#2b3035,#1c2024);color:#e3e6e8;font:600 15px system-ui,sans-serif;cursor:pointer}
button.main{border-color:#f4f5f6;color:#101214;background:linear-gradient(180deg,#f1f3f4,#b9bec3 42%,#dfe2e5 58%,#9aa0a6)}
textarea,input{width:100%;padding:12px;border-radius:8px;border:1px solid #6c7278;background:#0b0c0d;color:#f1f3f4;font:16px system-ui,sans-serif}
.code{font:500 clamp(24px,7vw,40px)/1.2 ui-monospace,monospace;letter-spacing:.06em}pre{white-space:pre-wrap;margin:10px 0 0;color:#e3e6e8;font:15px/1.5 system-ui,sans-serif}
.two{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:18px}[hidden]{display:none!important}
</style></head><body><div class="wrap">
<div class="word">FIREPLACE</div>
<div class="two">
 <div class="plate"><div class="small brand">Your temperature</div><div class="deg brand" id="temp">--</div><p id="tline"></p></div>
 <div class="plate" id="mecard"><div class="small brand" id="mename">This device</div><p id="mespec" style="margin-top:8px;font-weight:600"></p><p id="merole"></p></div>
</div>
<div class="panel" id="linkbox" hidden><h2>Link this phone</h2><p id="lmsg">Type the link code shown on your computer.</p>
 <input id="lcode" placeholder="XXXX XXXX XXXX XXXX" autocapitalize="characters" autocomplete="off" style="margin:10px 0"><button class="main" id="lgo">Link</button></div>
<div class="panel" id="codebox" hidden><h2>Add a device</h2><div class="code" id="code">---- ---- ---- ----</div>
 <p class="dim" style="margin:8px 0 12px">Phone: open fireplace.sh/heatcheck and type this code. Computer: run <b>python fireplace.py --join "CODE"</b>. Each code works once and lasts 10 minutes.</p><button id="newcode">New code</button></div>
<div class="panel" id="askbox"><h2>Ask your fire</h2><textarea id="q" rows="3" placeholder="Ask something. The strongest device that is online will answer."></textarea>
 <div style="margin-top:10px"><button class="main" id="go">Send</button> <span class="dim" id="who"></span></div><pre id="a"></pre></div>
<div class="panel"><h2>Devices</h2><div id="devs"></div></div>
<div class="panel" id="agentbox" hidden><h2>Watch agents</h2><div id="agents"></div><div id="events"></div></div>
</div><script>
var VIEW='__VIEW__',tok=null;try{tok=localStorage.getItem('fp_token')}catch(e){}
var $=function(i){return document.getElementById(i)};
function api(p,body){var h={'Content-Type':'application/json'};if(tok)h.Authorization='Bearer '+tok;
 return fetch(p,{method:body?'POST':'GET',headers:h,body:body?JSON.stringify(body):undefined}).then(function(r){return r.json().then(function(j){if(!r.ok)throw new Error(j.error||'Something went wrong.');return j})})}
function row(html){var d=document.createElement('div');d.className='row';d.innerHTML=html;return d}
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]})}
function draw(s){$('temp').textContent=s.temperature+'°';$('tline').textContent=s.temperature+' GB of memory across '+(1+s.devices.filter(function(d){return d.kind=='computer'}).length)+' computer(s). 1 degree is 1 GB.';
 $('mename').textContent=s.me.name;$('mespec').textContent=s.me.spec+' / +'+s.me.degrees+'°';$('merole').textContent=s.me.role+(s.me.model?': '+s.me.model:'')+'. '+s.me.job;
 var D=$('devs');D.innerHTML='';if(!s.devices.length)D.appendChild(row('<span class="dim">No other devices yet.</span>'));
 s.devices.forEach(function(d){var r=row('<div class="grow"><div class="name">'+esc(d.name)+'</div><div class="dim">'+esc(d.spec)+(d.model?' / '+esc(d.role)+': '+esc(d.model):' / '+esc(d.role))+'</div></div><div>'+(d.kind=='computer'?'+'+d.degrees+'°':'uses the fire')+'</div><div class="'+(d.online?'ok':'warn')+'">'+(d.online?'Linked':'Offline')+'</div>');
  if(VIEW=='dash'){var b=document.createElement('button');b.textContent='Remove';b.onclick=function(){api('/api/remove',{id:d.id}).then(poll)};r.appendChild(b)}D.appendChild(r)});
 if(VIEW=='dash'){var A=$('agents');A.innerHTML='';A.appendChild(row('<div class="grow name">Timekeeper</div><div class="ok">'+esc(s.agents.timekeeper)+'</div>'));
  A.appendChild(row('<div class="grow name">Sentry</div><div class="'+(s.agents.paused?'warn':'ok')+'">'+esc(s.agents.sentry)+'</div>'));
  A.appendChild(row('<div class="grow name">Jury</div><div class="dim">Not in version 1</div>'));
  var E=$('events');E.innerHTML='';s.events.forEach(function(e){E.appendChild(row('<div class="grow"><span class="'+(e.level=='warn'?'warn':'ok')+'">'+esc(e.agent)+'</span> <span class="dim">'+new Date(e.t*1000).toLocaleTimeString()+'</span><div>'+esc(e.text)+'</div></div>'))})}}
function poll(){return api('/api/state').then(draw).catch(function(){if(VIEW=='phone')needLink()})}
function needLink(){$('linkbox').hidden=false;$('askbox').hidden=true}
function link(code){$('lmsg').textContent='Linking...';var n=/iPhone|iPad/.test(navigator.userAgent)?'iPhone':/Android/.test(navigator.userAgent)?'Android phone':'Browser';
 api('/api/link',{code:code,name:n,kind:'phone'}).then(function(j){tok=j.token;try{localStorage.setItem('fp_token',tok)}catch(e){}history.replaceState(null,'','/heatcheck');$('linkbox').hidden=true;$('askbox').hidden=false;poll()})
 .catch(function(e){$('lmsg').textContent=e.message;needLink()})}
$('lgo').onclick=function(){link($('lcode').value)};
$('go').onclick=function(){$('a').textContent='Working...';$('who').textContent='';api('/api/ask',{prompt:$('q').value}).then(function(j){$('a').textContent=j.response;$('who').textContent='Answered by '+j.device+(j.model?' with '+j.model:'')}).catch(function(e){$('a').textContent=e.message})};
if(VIEW=='dash'){$('codebox').hidden=false;$('agentbox').hidden=false;$('newcode').onclick=function(){api('/api/code',{}).then(function(j){$('code').textContent=j.code})};$('newcode').onclick();poll()}
else{var h=location.hash.slice(1);if(h.length>=16&&!tok)link(h);else poll()}
setInterval(poll,4000);
</script></body></html>"""


def main():
    ap = argparse.ArgumentParser(description="Fireplace: link the machines you already own.")
    ap.add_argument("--join", metavar="CODE", help="link this computer to a fire using a link code")
    ap.add_argument("--port", type=int, default=PORT)
    ap.add_argument("--no-browser", action="store_true", help="do not open the setup page")
    args = ap.parse_args()

    ident = load_identity(); load_state()
    ME.update(read_hardware(), name=ident["name"], id=ident["id"], ip=lan_ip(), port=args.port)
    print(f"Fireplace {VERSION} on {ME['name']}: {ME['spec']}, +{ME['degrees']} degrees, best fit {ME['role']}"
          + (f" ({ME['model']})" if ME["model"] else ""))
    for agent in (timekeeper, sentry, heartbeat):
        threading.Thread(target=agent, daemon=True).start()
    server = ThreadingHTTPServer(("0.0.0.0", args.port), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    if args.join:
        try:
            join(args.join)
        except Exception as e:
            print(f"Could not link: {e}"); sys.exit(1)
    url = f"http://127.0.0.1:{args.port}/"
    print(f"Open {url} on this computer. Phones on your home network: fireplace.sh/heatcheck")
    if not args.no_browser:
        try:
            webbrowser.open(url)
        except Exception:
            pass
    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        print("\nFire banked. Goodbye.")


if __name__ == "__main__":
    main()
