#!/usr/bin/env python3
"""
eve-topos-bridge — Dual-Mode Tailscale HTTP (:8600) + SSH Bridge for EVE Live EEG
=================================================================================
Syncs live K1.1 EEG telemetry from `http://100.64.0.4:8600/embed/k1_1_live` (or SSH `topos`)
into both `~/.pi/agent/state/k1_1_live_eeg.json` and `/tmp/k1_1_live_eeg.json` (mode 0600),
and maintains localhost:8600 forwarding when needed.
"""
from __future__ import annotations

import argparse
import json
import os
import signal
import socket
import subprocess
import sys
import time
import urllib.request
from pathlib import Path

STATE_DIR = Path.home() / ".pi" / "agent" / "state"
PID_FILE = STATE_DIR / "eve_topos_bridge.pid"
LOG_FILE = STATE_DIR / "eve_topos_bridge.log"
LOCAL_EEG_FILE = STATE_DIR / "k1_1_live_eeg.json"
TMP_EEG_FILE = Path("/tmp/k1_1_live_eeg.json")
LOCAL_RING_FILE = STATE_DIR / "k1_1_live_ring.json"
TMP_RING_FILE = Path("/tmp/k1_1_live_ring.json")
CONFIG_FILE = Path.home() / ".pi" / "agent" / "eve_byollm_config.json"


def ensure_state_dir() -> None:
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    try:
        os.chmod(STATE_DIR, 0o700)
    except OSError:
        pass


def resolve_host(cli_host: str | None) -> str:
    if cli_host:
        return cli_host
    if os.environ.get("EVE_SSH_HOST"):
        return os.environ["EVE_SSH_HOST"].strip()
    if CONFIG_FILE.exists():
        try:
            cfg = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
            if isinstance(cfg.get("sshBridgeHost"), str) and cfg["sshBridgeHost"].strip():
                return cfg["sshBridgeHost"].strip()
        except Exception:
            pass
    return "topos"


def is_port_open(port: int, host: str = "127.0.0.1") -> bool:
    try:
        with socket.create_connection((host, port), timeout=0.6):
            return True
    except OSError:
        return False


def is_pid_alive(pid: int) -> bool:
    try:
        os.kill(pid, 0)
        return True
    except OSError:
        return False


def get_running_pid() -> int | None:
    if not PID_FILE.exists():
        return None
    try:
        pid = int(PID_FILE.read_text(encoding="utf-8").strip())
        if is_pid_alive(pid):
            return pid
    except Exception:
        pass
    return None


def atomic_write_eeg(raw_line: str) -> bool:
    raw_line = raw_line.strip()
    if not raw_line.startswith("{") or not raw_line.endswith("}"):
        return False
    try:
        parsed = json.loads(raw_line)
        if not isinstance(parsed, dict) or "embedding" not in parsed:
            return False
    except Exception:
        return False

    ensure_state_dir()
    for target in (LOCAL_EEG_FILE, TMP_EEG_FILE):
        tmp_path = target.parent / f".{target.name}.{os.getpid()}.tmp"
        try:
            fd = os.open(str(tmp_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
            with os.fdopen(fd, "w", encoding="utf-8") as f:
                f.write(raw_line + "\n")
            os.replace(str(tmp_path), str(target))
        except Exception:
            try:
                tmp_path.unlink(missing_ok=True)
            except Exception:
                pass
    return True


def sync_once(host: str) -> bool:
    for url in ("http://127.0.0.1:8600/embed/k1_1_live", "http://100.64.0.4:8600/embed/k1_1_live"):
        try:
            with urllib.request.urlopen(url, timeout=1.8) as resp:
                raw = resp.read().decode("utf-8").strip()
                if atomic_write_eeg(raw):
                    return True
        except Exception:
            continue
    cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=4", host, "cat /tmp/k1_1_live_eeg.json 2>/dev/null"]
    try:
        res = subprocess.run(cmd, capture_output=True, text=True, timeout=6)
        if res.returncode == 0 and res.stdout.strip():
            return atomic_write_eeg(res.stdout.strip())
    except Exception:
        pass
    return False


def main() -> int:
    ap = argparse.ArgumentParser(description="EVE Dual-Mode Tailscale/SSH Bridge (:8600 + Live EEG JSON)")
    ap.add_argument("action", nargs="?", default="once", choices=["start", "stop", "status", "once", "fg"])
    ap.add_argument("--host", default=None, help="SSH host alias (default: topos)")
    ap.add_argument("--interval", type=float, default=1.0, help="Sync poll interval in seconds")
    args = ap.parse_args()
    host = resolve_host(args.host)
    ensure_state_dir()

    if args.action == "once":
        return 0 if sync_once(host) else 1
    if args.action == "status":
        sync_once(host)
        eeg_age = (time.time() - LOCAL_EEG_FILE.stat().st_mtime) if LOCAL_EEG_FILE.exists() else None
        print(json.dumps({
            "running": get_running_pid() is not None,
            "host": host,
            "port_8600_local": is_port_open(8600, "127.0.0.1"),
            "port_8600_tailscale": is_port_open(8600, "100.64.0.4"),
            "eeg_file": str(LOCAL_EEG_FILE),
            "tmp_eeg_file": str(TMP_EEG_FILE),
            "eeg_age_sec": round(eeg_age, 1) if eeg_age is not None else None,
        }))
        return 0
    if args.action == "stop":
        pid = get_running_pid()
        if pid is not None:
            try:
                os.kill(pid, signal.SIGTERM)
            except OSError:
                pass
            PID_FILE.unlink(missing_ok=True)
        return 0
    if args.action == "fg":
        PID_FILE.write_text(f"{os.getpid()}\n", encoding="utf-8")
        while True:
            sync_once(host)
            time.sleep(max(0.5, args.interval))
    # start
    pid = get_running_pid()
    if pid is not None:
        sync_once(host)
        return 0
    log_fd = os.open(str(LOG_FILE), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
    subprocess.Popen(
        [sys.executable, os.path.abspath(__file__), "fg", "--host", host, "--interval", str(args.interval)],
        stdin=subprocess.DEVNULL,
        stdout=log_fd,
        stderr=log_fd,
        start_new_session=True,
    )
    os.close(log_fd)
    sync_once(host)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
