#!/usr/bin/env python3
"""Idempotent launcher for MixHub / Agent Session Hub (TUI, tmux workspace, handoff, sync-rules, notify, mobile-handoff, install-icons, and Web daemon)."""
import argparse
try:
    import fcntl
except ImportError:  # Windows native (win32) fallback
    fcntl = None
import json
import os
import signal
import subprocess
import sys
import time
import urllib.request

ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
URL = "http://127.0.0.1:" + os.environ.get("HUB_PORT", "8765")
PID_FILE = os.path.join(ROOT, ".hub.pid")


def health():
    try:
        with urllib.request.urlopen(URL + "/api/health", timeout=0.25) as response:
            value = json.load(response)
            return value if value.get("service") in ("agent-session-hub", "mixhub") else None
    except (OSError, ValueError):
        return None


def start():
    live = health()
    if live:
        print("running · pid %s · %s" % (live["pid"], URL))
        return
    log_path = os.path.join(ROOT, "hub.log")
    with open(log_path, "ab") as log:
        os.chmod(log_path, 0o600)
        python = os.environ.get("HUB_PYTHON", "/usr/bin/python3" if sys.platform == "darwin" else sys.executable)
        process = subprocess.Popen([python, "-S", os.path.join(ROOT, "server.py")], cwd=ROOT,
                                   stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
    with open(PID_FILE, "w") as f:
        f.write(str(process.pid))
    deadline = time.monotonic() + 5
    while time.monotonic() < deadline:
        if process.poll() is not None:
            raise RuntimeError("Hub exited; inspect " + log_path)
        if health():
            print("started · pid %s · %s" % (process.pid, URL))
            return
        time.sleep(0.025)
    process.terminate()
    raise RuntimeError("Hub did not become ready; inspect " + log_path)


def stop():
    live = health()
    if not live:
        print("stopped")
        return
    try:
        with open(PID_FILE) as f:
            pid = int(f.read().strip())
    except (OSError, ValueError):
        pid = int(live["pid"])
    command = subprocess.check_output(["ps", "-p", str(pid), "-o", "command="], text=True).strip()
    if pid != live["pid"] or os.path.join(ROOT, "server.py") not in command:
        raise RuntimeError("PID identity changed; refusing to signal another process")
    os.kill(pid, signal.SIGTERM)
    deadline = time.monotonic() + 3
    while health() and time.monotonic() < deadline:
        time.sleep(0.05)
    if health():
        raise RuntimeError("Hub is still stopping")
    if os.path.exists(PID_FILE):
        os.unlink(PID_FILE)
    print("stopped")


def run_slim(argv):
    sys.path.insert(0, ROOT)
    import slim_storage
    return slim_storage.main(argv)


def run_anchor(argv):
    parser = argparse.ArgumentParser(prog="hub anchor", description="Extract zero-token deterministic fact anchors from session transcripts")
    parser.add_argument("target", nargs="?", default="", help="Session ID (or prefix) to extract anchor for; omit to anchor all compacted/recent sessions")
    parser.add_argument("--tool", default="", help="Optional tool filter (claude|agy|codex)")
    opts = parser.parse_args(argv)
    sys.path.insert(0, ROOT)
    import server
    hub = server.Hub()
    res = hub.build_anchors(target=opts.target, tool_filter=opts.tool)
    if not res["anchors"]:
        print("未找到匹配的会话记录。")
        return 1
    for item in res["anchors"]:
        print(f"● [{item['tool']}] {item['title']} ({item['id'][:8]})")
        print(f"  - 锚点文件: {item['anchor_path']}")
        print(f"  - 提取统计: 用户指令 {item['user_count']} 条 · 修改文件 {item['file_count']} 个 · 命令 {item['cmd_count']} 条 · 压缩点 {item['compact_count']} 处")
    return 0


def run_handoff(argv):
    parser = argparse.ArgumentParser(prog="hub handoff", description="Generate 10-section cross-agent handoff bundle + handoff.yaml with QUIESCING -> SOURCE_FENCED write fence")
    parser.add_argument("target", help="Source session ID or prefix")
    parser.add_argument("--to", required=True, choices=("claude", "agy", "codex", "deepseek"), help="Target agent engine")
    parser.add_argument("--mode", default="auto", choices=("auto", "escalate", "delegate", "review"), help="Directional handoff mode (auto|escalate|delegate|review)")
    parser.add_argument("--provider", default="", help="Optional provider override (e.g. deepseek)")
    parser.add_argument("--from-tool", default="", help="Optional source tool filter (claude|agy|codex)")
    parser.add_argument("--note", default="", help="Optional handoff note")
    parser.add_argument("--dry-run", action="store_true", help="Preview bundle without writing state")
    parser.add_argument("--quiesce", action="store_true", help="Terminate live source processes before fencing")
    opts = parser.parse_args(argv)
    sys.path.insert(0, ROOT)
    import server
    hub = server.Hub()
    res = hub.handoff({
        "id": opts.target,
        "to": opts.to,
        "mode": opts.mode,
        "provider": opts.provider,
        "from_tool": opts.from_tool,
        "note": opts.note,
        "dry_run": opts.dry_run,
        "quiesce_live": opts.quiesce,
    })
    print(f"● Handoff [{res['from_tool']} -> {res['to_tool']}] · mode={res['mode']} · status={res['status']} · fence={res['fence_state']} (epoch {res['workspace_epoch']})")
    print(f"  - Bundle: {res['bundle_path']} (~{res['token_estimate']} tokens)")
    print(f"  - YAML  : {res['yaml_path']}")
    print(f"  - Chain : {' -> '.join(res['handoffChain'])}")
    print(f"  - Launch: {res['command']}")
    return 0 if res.get("ok") else 1


def run_sync_rules(argv):
    sys.path.insert(0, ROOT)
    import rules_sync
    return rules_sync.main(argv)


def run_notify(argv):
    sys.path.insert(0, ROOT)
    import channels
    return channels.main(argv)


def run_codex_release_lock(argv):
    parser = argparse.ArgumentParser(prog="hub codex-release-lock", description="Release terminal codex writer lock so ChatGPT.app / mobile app can take over")
    parser.add_argument("target", help="Codex session ID or prefix")
    parser.add_argument("--dry-run", action="store_true", help="Preview without terminating terminal process")
    opts = parser.parse_args(argv)
    sys.path.insert(0, ROOT)
    import server
    hub = server.Hub()
    res = hub.mobile_handoff("codex", opts.target, {"dry_run": opts.dry_run})
    print(f"● Codex lock released for {res['id']} -> {res['companionApp']} (controlMode={res['controlMode']})")
    print(f"  - Lock file: {res['lock_path']} (free={res['lock_released']})")
    return 0


def run_mobile_handoff(argv):
    parser = argparse.ArgumentParser(prog="hub mobile-handoff", description="Seamless first-party mobile app lock release & remote-control bridge")
    parser.add_argument("target", help="Session ID or prefix")
    parser.add_argument("--tool", default="", choices=("", "claude", "codex", "agy"), help="Optional tool filter")
    parser.add_argument("--relaunch", action="store_true", help="Relaunch Claude session with --remote-control")
    parser.add_argument("--dry-run", action="store_true", help="Preview without side effects")
    opts = parser.parse_args(argv)
    sys.path.insert(0, ROOT)
    import server
    hub = server.Hub()
    res = hub.mobile_handoff(opts.tool, opts.target, {"dry_run": opts.dry_run, "relaunch": opts.relaunch})
    print(json.dumps(res, ensure_ascii=False, indent=2))
    return 0


def run_install_icons(argv):
    sys.path.insert(0, ROOT)
    import icons_font
    return icons_font.main(argv)


def run_doctor(argv):
    sys.path.insert(0, ROOT)
    import protocols
    return protocols.main(argv)


def run_report(argv):
    sys.path.insert(0, ROOT)
    import cost_report
    return cost_report.main(argv)


def main():
    args = sys.argv[1:]
    command = args[0] if args else ("workspace" if (sys.stdin.isatty() and sys.stdout.isatty() and os.environ.get("HUB_NO_OPEN") != "1") else "open")

    if command == "agy":
        os.execvp(sys.executable, [sys.executable, os.path.join(ROOT, "agy_claude_filter.py"), *args[1:]])
    if command == "slim":
        return run_slim(args[1:])
    if command == "anchor":
        return run_anchor(args[1:])
    if command == "handoff":
        return run_handoff(args[1:])
    if command == "sync-rules":
        return run_sync_rules(args[1:])
    if command == "notify":
        return run_notify(args[1:])
    if command == "codex-release-lock":
        return run_codex_release_lock(args[1:])
    if command == "mobile-handoff":
        return run_mobile_handoff(args[1:])
    if command == "install-icons":
        return run_install_icons(args[1:])
    if command == "doctor":
        return run_doctor(args[1:])
    if command == "report":
        return run_report(args[1:])
    if command in ("tui", "sidebar", "reader", "workspace", "tmux"):
        extra = []
        if command == "sidebar":
            extra = ["--sidebar"]
        elif command == "reader":
            extra = ["--reader"]
        elif command in ("workspace", "tmux"):
            extra = ["--workspace"]
        os.execvp(sys.executable, [sys.executable, os.path.join(ROOT, "tui.py"), *extra, *args[1:]])

    if command not in ("web", "open", "start", "stop", "status") or len(args) > 1:
        print(
            "Usage: mixhub|hub [workspace|tui|sidebar|reader|handoff|sync-rules|notify|codex-release-lock|mobile-handoff|install-icons|doctor|report|agy|slim|anchor|web|start|stop|status]",
            file=sys.stderr,
        )
        return 2

    with open(os.path.join(ROOT, ".hub.lock"), "a") as lock:
        if fcntl is not None:
            fcntl.flock(lock, fcntl.LOCK_EX)
        if command == "status":
            live = health()
            print("running · pid %s · %s" % (live["pid"], URL) if live else "stopped · " + URL)
        elif command == "stop":
            stop()
        else:
            start()
            if command in ("open", "web") and os.environ.get("HUB_NO_OPEN") != "1":
                if sys.platform == "win32":
                    import webbrowser

                    webbrowser.open(URL)
                elif sys.platform == "darwin":
                    subprocess.run(["open", URL], check=True)
                else:
                    subprocess.run(["xdg-open", URL], check=False)
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (OSError, RuntimeError, subprocess.SubprocessError) as exc:
        print(str(exc), file=sys.stderr)
        sys.exit(1)
