#!/usr/bin/env python3
"""One-shot daemon refresh after all active turns finish; never prints chat data."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import socket
import signal
import struct
import subprocess
import time

CONTROL = Path.home() / ".codex/app-server-control/app-server-control.sock"
PID_RECORD = Path.home() / ".codex/app-server-daemon/daemon.pid"
UPDATER_RECORD = Path.home() / ".codex/app-server-daemon/daemon-updater.pid"
LOOPBACK = ("localhost", "127.0.0.1", "::1")


def receive_exact(stream, size):
    data = b""
    while len(data) < size:
        chunk = stream.recv(size - len(data))
        if not chunk:
            raise RuntimeError("IPC closed")
        data += chunk
    return data


class LocalRpc:
    def __init__(self, path=CONTROL):
        self.stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.stream.settimeout(5)
        self.stream.connect(str(path))
        key = base64.b64encode(os.urandom(16)).decode()
        request = ("GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n"
                   "Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n"
                   f"Sec-WebSocket-Key: {key}\r\n\r\n")
        self.stream.sendall(request.encode())
        header = b""
        while not header.endswith(b"\r\n\r\n"):
            header += receive_exact(self.stream, 1)
            if len(header) > 8192:
                raise RuntimeError("Invalid IPC handshake")
        expected = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest())
        if not header.startswith(b"HTTP/1.1 101") or expected.lower() not in header.lower():
            raise RuntimeError("IPC handshake rejected")
        self.ident = 0
        self.call("initialize", {"clientInfo": {"name": "kiln_daemon_refresh", "version": "1"}})
        self.send({"method": "initialized"})

    def frame(self, payload, opcode=1):
        mask = os.urandom(4)
        length = len(payload)
        header = bytes([128 | opcode])
        if length < 126:
            header += bytes([128 | length])
        elif length < 65536:
            header += bytes([128 | 126]) + struct.pack("!H", length)
        else:
            header += bytes([128 | 127]) + struct.pack("!Q", length)
        self.stream.sendall(header + mask + bytes(value ^ mask[i % 4] for i, value in enumerate(payload)))

    def send(self, value):
        self.frame(json.dumps(value).encode())

    def receive(self):
        message = b""
        while True:
            first, second = receive_exact(self.stream, 2)
            length = second & 127
            if length == 126:
                length = struct.unpack("!H", receive_exact(self.stream, 2))[0]
            elif length == 127:
                length = struct.unpack("!Q", receive_exact(self.stream, 8))[0]
            if length > 2 * 1024 * 1024:
                raise RuntimeError("IPC metadata response too large")
            mask = receive_exact(self.stream, 4) if second & 128 else None
            payload = receive_exact(self.stream, length)
            if mask:
                payload = bytes(value ^ mask[i % 4] for i, value in enumerate(payload))
            opcode = first & 15
            if opcode == 8:
                raise RuntimeError("IPC disconnected")
            if opcode == 9:
                self.frame(payload, 10)
                continue
            if opcode == 10:
                continue
            message += payload
            if first & 128:
                return json.loads(message)

    def call(self, method, params):
        self.ident += 1
        self.send({"id": self.ident, "method": method, "params": params})
        while True:
            result = self.receive()
            if result.get("id") == self.ident:
                if "error" in result:
                    raise RuntimeError("IPC metadata request failed")
                return result["result"]

    def close(self):
        self.stream.close()


def busy_turns():
    rpc = LocalRpc()
    try:
        cursor = None
        busy = 0
        while True:
            page = rpc.call("thread/loaded/list", {"cursor": cursor, "limit": 100})
            for ident in page["data"]:
                # Metadata only: no turns, messages, rollout files or auth.
                result = rpc.call("thread/read", {"threadId": ident, "includeTurns": False})
                status = result["thread"]["status"]["type"]
                if status == "active":
                    busy += 1
                elif status not in ("idle", "notLoaded", "systemError"):
                    raise RuntimeError("Unknown activity status; restart deferred")
            cursor = page.get("nextCursor")
            if not cursor:
                return busy
    finally:
        rpc.close()


def environment():
    env = dict(os.environ)
    for key in ("NO_PROXY", "no_proxy"):
        entries = [entry.strip() for entry in env.get(key, "").split(",") if entry.strip()]
        for host in LOOPBACK:
            if host not in entries:
                entries.append(host)
        env[key] = ",".join(entries)
    return env


def process_bypass(pid):
    values = dict(entry.split("=", 1) for entry in (Path("/proc") / str(pid) / "environ").read_bytes().decode().split("\0") if "=" in entry)
    return all(all(host in values.get(key, "").split(",") for host in LOOPBACK) for key in ("NO_PROXY", "no_proxy"))


def process_values(pid):
    return dict(entry.split("=", 1) for entry in (Path("/proc") / str(pid) / "environ").read_bytes().decode().split("\0") if "=" in entry)


def stop_stale_updater():
    if not UPDATER_RECORD.exists():
        return False
    pid = json.loads(UPDATER_RECORD.read_text())["pid"]
    if process_bypass(pid):
        return False
    path = Path("/proc") / str(pid)
    args = (path / "cmdline").read_bytes().decode().split("\0")
    if args[1:4] != ["app-server", "daemon", "pid-update-loop"]:
        raise RuntimeError("Updater identity changed; no signal sent")
    os.kill(pid, signal.SIGTERM)
    deadline = time.monotonic() + 5
    while path.exists():
        if time.monotonic() >= deadline:
            raise RuntimeError("Updater did not stop")
        time.sleep(0.1)
    return True


def mcp_status(thread_id):
    rpc = LocalRpc()
    try:
        result = rpc.call("mcpServerStatus/list", {"threadId": thread_id, "serverName": "codex_tui"})
        servers = result.get("data", [])
        server = next((item for item in servers if item.get("name") == "codex_tui"), {})
        count = len(server.get("tools", {}))
        return {"connected": count > 0 and not server.get("toolsError"), "tool_count": count}
    finally:
        rpc.close()


def refresh(timeout):
    deadline = time.monotonic() + timeout
    while busy_turns():
        if time.monotonic() >= deadline:
            return {"status": "deferred", "reason": "active_turns"}
        time.sleep(2)
    before = json.loads(PID_RECORD.read_text())["pid"]
    remote_disabled = process_values(before).get("CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED") == "true"
    updater_stopped = stop_stale_updater()
    bootstrap = None
    try:
        result = subprocess.run(["codex", "app-server", "daemon", "restart"], env=environment(),
                                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45)
    finally:
        # Restore durable management even if the restart command fails.
        if updater_stopped:
            command = ["codex", "app-server", "daemon", "bootstrap"]
            if not remote_disabled:
                command.append("--remote-control")
            bootstrap = subprocess.run(command, env=environment(), stdout=subprocess.DEVNULL,
                                       stderr=subprocess.DEVNULL, timeout=45)
    if result.returncode:
        return {"status": "failed", "reason": "restart_command", "exit_code": result.returncode}
    if bootstrap is not None and bootstrap.returncode:
        return {"status": "failed", "reason": "updater_bootstrap", "exit_code": bootstrap.returncode}
    after = json.loads(PID_RECORD.read_text())["pid"]
    bypass = process_bypass(after)
    updater = json.loads(UPDATER_RECORD.read_text())["pid"]
    updater_bypass = process_bypass(updater)
    result = {"status": "restarted" if bypass and updater_bypass else "failed", "pid_changed": before != after,
              "localhost_bypass_present": bypass, "updater_localhost_bypass_present": updater_bypass}
    thread_id = os.environ.get("CODEX_THREAD_ID")
    status = {"connected": False, "tool_count": 0}
    deadline = time.monotonic() + 25
    while thread_id and time.monotonic() < deadline:
        try:
            status = mcp_status(thread_id)
            if status["connected"]:
                break
        except (OSError, RuntimeError):
            pass
        time.sleep(1)
    result["codex_tui"] = status
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true")
    parser.add_argument("--delay", type=float, default=0)
    parser.add_argument("--timeout", type=float, default=600)
    parser.add_argument("--report", type=Path)
    args = parser.parse_args()
    if args.check:
        print(json.dumps({"busy_turns": busy_turns()}))
        return
    if args.report is None:
        parser.error("--report is required for a restart")
    args.report.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    os.umask(0o077)
    time.sleep(args.delay)
    try:
        result = refresh(args.timeout)
    except Exception as error:
        result = {"status": "failed", "reason": type(error).__name__}
    args.report.write_text(json.dumps(result, indent=2) + "\n")
    args.report.chmod(0o600)


if __name__ == "__main__":
    main()
