#!/opt/alfred-agent/.venv/bin/python
"""
Alfred <-> Hermes Persistent Agent Bridge (127.0.0.1:8788)
- Warm single AIAgent instance (preserves llama-server KV cache across turns)
- Clean single-source token streaming (zero duplicate deltas)
- Real-time tool progress SSE events + 2s keepalives
- Safe client disconnect handling (never crashes on BrokenPipe/ConnectionReset)
"""
import json
import os
import pwd
import queue
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

sys.path.insert(0, "/opt/alfred-agent")
_pw = pwd.getpwnam("alfred")
_uid = _pw.pw_uid
os.environ.setdefault("HERMES_HOME", "/home/alfred/.hermes")
os.environ.setdefault("DISPLAY", ":0")
os.environ.setdefault("XDG_RUNTIME_DIR", f"/run/user/{_uid}")
os.environ.setdefault("DBUS_SESSION_BUS_ADDRESS", f"unix:path=/run/user/{_uid}/bus")
os.environ.setdefault("TERMINAL_APPROVAL", "auto")
os.environ.setdefault("HERMES_YOLO", "1")

import run_agent

HOST = os.environ.get("ALFRED_HERMES_HOST", "127.0.0.1")
PORT = int(os.environ.get("ALFRED_HERMES_PORT", "8788"))
DEFAULT_BASE_URL = os.environ.get("ALFRED_HERMES_BASE_URL", "http://127.0.0.1:18090/v1")
DEFAULT_MODEL = os.environ.get("ALFRED_HERMES_MODEL", "qwen3.5-35b-a3b")
DEFAULT_API_KEY = os.environ.get("ALFRED_HERMES_API_KEY", "alfred-sovereign")

LEAN_TOOLSETS = ["terminal", "file", "web", "memory"]

_lock = threading.Lock()
_history = []
_session_id = f"oracle_{int(time.time())}"
_active_q = None
_active_tools = []
_cached_agent = None
_cached_key = None


def _safe_put(ev):
    q = _active_q
    if q is not None:
        try:
            q.put_nowait(ev)
        except Exception:
            pass


def _on_tool_start(*args):
    tname = "tool"
    detail = ""
    if len(args) >= 2 and isinstance(args[1], str) and len(str(args[0])) > 16:
        tname = str(args[1])
        if len(args) >= 3 and args[2]:
            detail = str(args[2])[:110]
    elif len(args) >= 1:
        tname = str(args[0])
        if len(args) >= 2 and args[1]:
            detail = str(args[1])[:110]
    # Clean pretty preview for terminal commands
    if isinstance(detail, str) and "'command':" in detail:
        try:
            import ast
            d = ast.literal_eval(detail)
            if isinstance(d, dict) and d.get("command"):
                detail = str(d["command"])[:90]
        except Exception:
            pass
    _active_tools.append({"name": tname, "detail": detail})
    _safe_put({"type": "tool", "name": tname, "detail": detail})


def _on_tool_progress(*args):
    tname = str(args[0]) if args else "tool"
    detail = str(args[1])[:100] if len(args) >= 2 and args[1] else ""
    _safe_put({"type": "tool_progress", "name": tname, "detail": detail})


def _get_agent(model_name, base_url):
    global _cached_agent, _cached_key
    key = (model_name, base_url, _session_id)
    if _cached_agent is not None and _cached_key == key:
        return _cached_agent
    req_overrides = {"extra_body": {"chat_template_kwargs": {"enable_thinking": False}}}
    # IMPORTANT: Do NOT set stream_delta_callback here if we pass stream_callback to run_conversation
    # (prevents duplicated token emissions!)
    agent = run_agent.AIAgent(
        base_url=base_url,
        api_key=DEFAULT_API_KEY,
        provider="custom",
        model=model_name,
        max_iterations=8,
        tool_delay=0.02,
        enabled_toolsets=LEAN_TOOLSETS,
        quiet_mode=True,
        load_soul_identity=True,
        skip_context_files=True,
        session_id=_session_id,
        tool_start_callback=_on_tool_start,
        tool_progress_callback=_on_tool_progress,
        reasoning_config={"enabled": False},
        request_overrides=req_overrides,
        max_tokens=900,
    )
    _cached_agent = agent
    _cached_key = key
    return agent


def _prewarm_kv():
    try:
        t0 = time.monotonic()
        with _lock:
            ag = _get_agent(DEFAULT_MODEL, DEFAULT_BASE_URL)
            ag.run_conversation(user_message="Reply with the single word: Ready.", conversation_history=[])
        print(f"[alfred-hermes-bridge] KV pre-warm complete in {time.monotonic()-t0:.2f}s", flush=True)
    except Exception as e:
        print(f"[alfred-hermes-bridge] KV pre-warm note: {e}", flush=True)


class BridgeHandler(BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        return

    def _send_json(self, code, obj):
        data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
        try:
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)
        except (BrokenPipeError, ConnectionResetError, OSError):
            pass

    def _write_sse(self, raw_bytes):
        try:
            self.wfile.write(raw_bytes)
            self.wfile.flush()
            return True
        except (BrokenPipeError, ConnectionResetError, OSError):
            return False

    def do_GET(self):
        if self.path in ("/health", "/status", "/"):
            self._send_json(200, {
                "ok": True,
                "engine": "hermes-agent",
                "model": DEFAULT_MODEL,
                "base_url": DEFAULT_BASE_URL,
                "toolsets": LEAN_TOOLSETS,
                "uid": _uid,
                "session_id": _session_id,
                "history_turns": len(_history),
            })
            return
        self._send_json(404, {"error": "not found"})

    def do_POST(self):
        global _history, _session_id, _cached_agent, _cached_key
        try:
            length = int(self.headers.get("Content-Length", "0"))
            raw = self.rfile.read(min(length, 512000))
            body = json.loads(raw.decode("utf-8")) if raw else {}
        except Exception as e:
            self._send_json(400, {"error": f"bad json: {e}"})
            return

        if self.path == "/v1/oracle/reset":
            with _lock:
                _history = []
                _session_id = f"oracle_{int(time.time())}"
                _cached_agent = None
                _cached_key = None
            self._send_json(200, {"ok": True, "session_id": _session_id})
            return

        if self.path != "/v1/oracle/chat":
            self._send_json(404, {"error": "not found"})
            return

        message = str(body.get("message") or "").strip()
        if not message:
            self._send_json(400, {"error": "empty message"})
            return

        model_name = str(body.get("model") or DEFAULT_MODEL).strip() or DEFAULT_MODEL
        base_url = str(body.get("base_url") or DEFAULT_BASE_URL).strip() or DEFAULT_BASE_URL
        want_stream = bool(body.get("stream", True))
        incoming_history = body.get("history")

        t0 = time.monotonic()
        event_q = queue.Queue()
        result_box = {"text": "", "error": None, "tools": []}

        def worker():
            global _history, _active_q, _active_tools
            with _lock:
                _active_q = event_q
                _active_tools = []
                try:
                    agent = _get_agent(model_name, base_url)
                    conv_hist = list(incoming_history[-8:]) if isinstance(incoming_history, list) else list(_history[-8:])
                    # Stream live tool progress events during execution and emit 100% clean final text in `done`
                    # (prevents pre-tool interim narration from leaking into chat/TTS!)
                    res = agent.run_conversation(
                        user_message=message,
                        conversation_history=conv_hist,
                    )
                    final_txt = ""
                    if isinstance(res, dict):
                        final_txt = str(res.get("final_response") or res.get("response") or res.get("content") or "").strip()
                        if isinstance(res.get("messages"), list):
                            _history = [m for m in res["messages"] if m.get("role") in ("user", "assistant") and isinstance(m.get("content"), str)][-12:]
                    else:
                        final_txt = str(res or "").strip()
                    result_box["text"] = final_txt or "Done."
                    result_box["tools"] = list(_active_tools)
                except Exception as exc:
                    result_box["error"] = str(exc)
                finally:
                    _active_q = None
                    try:
                        event_q.put_nowait(None)
                    except Exception:
                        pass

        th = threading.Thread(target=worker, daemon=True)
        th.start()

        if not want_stream:
            th.join(timeout=180)
            elapsed_ms = int((time.monotonic() - t0) * 1000)
            if result_box["error"]:
                self._send_json(500, {"ok": False, "error": result_box["error"], "elapsed_ms": elapsed_ms})
            else:
                self._send_json(200, {
                    "ok": True,
                    "content": result_box["text"],
                    "tools_used": result_box["tools"],
                    "elapsed_ms": elapsed_ms,
                    "model": model_name,
                })
            return

        try:
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream; charset=utf-8")
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Connection", "close")
            self.end_headers()
        except (BrokenPipeError, ConnectionResetError, OSError):
            return

        streamed_any_delta = False
        last_ping = time.monotonic()
        client_alive = True
        while client_alive:
            try:
                ev = event_q.get(timeout=0.5)
            except queue.Empty:
                if not th.is_alive():
                    break
                if time.monotonic() - last_ping >= 2.0:
                    last_ping = time.monotonic()
                    client_alive = self._write_sse(b": keepalive\n\n")
                continue
            if ev is None:
                break
            if ev.get("type") == "delta":
                streamed_any_delta = True
            last_ping = time.monotonic()
            client_alive = self._write_sse(f"data: {json.dumps(ev, ensure_ascii=False)}\n\n".encode("utf-8"))

        if not client_alive:
            return

        elapsed_ms = int((time.monotonic() - t0) * 1000)
        if result_box["error"]:
            done_ev = {"type": "error", "error": result_box["error"], "elapsed_ms": elapsed_ms}
        else:
            done_ev = {
                "type": "done",
                "content": result_box["text"],
                "streamed": streamed_any_delta,
                "tools_used": result_box["tools"],
                "elapsed_ms": elapsed_ms,
                "model": model_name,
            }
        self._write_sse(f"data: {json.dumps(done_ev, ensure_ascii=False)}\n\n".encode("utf-8"))


if __name__ == "__main__":
    print(f"[alfred-hermes-bridge] Starting on http://{HOST}:{PORT} (uid={_uid})...", flush=True)
    threading.Thread(target=_prewarm_kv, daemon=True).start()
    srv = ThreadingHTTPServer((HOST, PORT), BridgeHandler)
    srv.serve_forever()
