#!/usr/bin/env python3
import json, pathlib, hashlib

INBOX = pathlib.Path("/var/lib/chronological/runtime/nova/inbox.jsonl")
OUT   = pathlib.Path("/var/lib/chronological/runtime/nova/actions.jsonl")
SEEN  = pathlib.Path("/var/lib/chronological/runtime/nova/router_seen.json")
DISPATCH = pathlib.Path("/var/lib/chronological/runtime/nova/room_dispatch.jsonl")
MODE = pathlib.Path("/var/lib/chronological/runtime/nova/dispatch_mode")

KNOWN = {
    "/observe": "ACK_OBSERVE", "observe": "ACK_OBSERVE",
    "/orient": "ACK_ORIENT",   "orient": "ACK_ORIENT",
    "/decide": "ACK_DECIDE",   "decide": "ACK_DECIDE",
    "/act":    "ACK_ACT",      "act":    "ACK_ACT",
    "/context":"ACK_CONTEXT",  "context":"ACK_CONTEXT",
}

def load_seen():
    try:
        return set(json.loads(SEEN.read_text()))
    except Exception:
        return set()

def save_seen(s):
    SEEN.write_text(json.dumps(list(s)))

def tail(p, n=200):
    try:
        return p.read_text().splitlines()[-n:]
    except Exception:
        return []

def key(e):
    raw = e.get("raw") or {}
    if "update_id" in raw:
        return f"tg:{raw['update_id']}"
    return hashlib.sha1(json.dumps(e, sort_keys=True).encode()).hexdigest()

OUT.parent.mkdir(parents=True, exist_ok=True)
seen = load_seen()
written = 0

for line in tail(INBOX):
    if not line.strip():
        continue
    try:
        e = json.loads(line)
    except Exception:
        continue

    k = key(e)
    if k in seen:
        continue

    text = (e.get("text") or "").strip()
    if not text:
        seen.add(k)
        continue

    cmd = text.split()[0].split("@", 1)[0]
    # --- UI ROOM DISPATCH (COMMAND MIRROR) ---
    try:
        room = Path(
            f"/sovereign/chronological270/ui/chronological_core/ROOMS/"
            f"{e.get('general','UNKNOWN')}/LANE_{str(e.get('lane','00')).zfill(2)}/feed.jsonl"
        )
        room.parent.mkdir(parents=True, exist_ok=True)
        room.open("a", encoding="utf-8").write(
            json.dumps({
                "ts": e.get("ts"),
                "source": e.get("source"),
                "general": e.get("general"),
                "lane": e.get("lane"),
                "command": cmd,
                "raw_text": text,
            }) + "\n"
        )
    except Exception:
        pass


    if cmd in KNOWN:
        action = {
            "ts": e.get("ts"),
            "source": e.get("source"),
            "general": e.get("general"),
            "lane": e.get("lane"),
            "command": cmd,
            "action": KNOWN[cmd],
            "chat_id": e.get("chat_id"),
            "text": text
        }
        with OUT.open("a", encoding="utf-8") as f:
            f.write(json.dumps(action) + "\n")

        written += 1
        # --- UI ROOM DISPATCH ---
        try:
            room = Path(
                f"/sovereign/chronological270/ui/chronological_core/ROOMS/"
                f"{e.get('general','UNKNOWN')}/LANE_{str(e.get('lane','00')).zfill(2)}/feed.jsonl"
            )
            room.parent.mkdir(parents=True, exist_ok=True)
            room.open("a", encoding="utf-8").write(
                json.dumps({
                    "ts": e.get("ts"),
                    "source": e.get("source"),
                    "general": e.get("general"),
                    "lane": e.get("lane"),
                    "command": cmd,
                    "action": KNOWN[cmd],
                }) + "\n"
            )
        except Exception:
            pass


        try:
            if MODE.exists() and MODE.read_text().strip() == "enabled":
                with DISPATCH.open("a", encoding="utf-8") as f:
                    f.write(json.dumps(action) + "\n")
        except Exception:
            pass

    seen.add(k)

save_seen(seen)
print(f"NOVA_ROUTER_OK written={written}")
