#!/usr/bin/env python3
"""Garp's local Hermes setup. Python standard library only; no owner bypass."""
import argparse
import ast
import getpass
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request

VERSION = "1.1.1"
ENDPOINT = "https://garp-mcp.fly.dev/mcp"
KEY_NAME = "GARP_MCP_KEY"
REQUIRED_TOOLS = {"garp_get_capabilities", "garp_get_current_project"}
BROWSER_CHECK_CODE = "new_tab('https://example.com'); print(page_info())"
AGENT_CHECK_PROMPT = (
    "Run two read-only setup checks. First call garp_get_capabilities. Then call "
    "browser_exec with this exact Python code:\n```python\n" + BROWSER_CHECK_CODE + "\n```\n"
    "Use available tools; do not just describe a plan. Do not use terminal commands, "
    "change configuration, inspect private projects, sign into websites or send anything. "
    "Report the observed page title and which calls succeeded."
)


class SetupError(Exception):
    pass


def endpoint_url(value):
    u = urllib.parse.urlsplit(value)
    local = u.hostname in {"localhost", "127.0.0.1", "::1"}
    if (u.username or u.password or u.query or u.fragment
            or not re.fullmatch(r"/mcp(?:/p/[A-Za-z0-9_-]{22})?", u.path)
            or not ((u.scheme == "https" and u.hostname == "garp-mcp.fly.dev")
                    or (local and u.scheme == "http"))):
        raise SetupError("Use your Garp project MCP URL, without a key in the URL.")
    return value


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None  # Never forward a customer credential to a redirect destination.


def probe(endpoint, key):
    """Exercise the normal authenticated protocol before saving credentials."""
    opener = urllib.request.build_opener(NoRedirect)
    def rpc(method, params):
        body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
        req = urllib.request.Request(endpoint, body, {
            "Authorization": "Bearer " + key, "X-Garp-Client": "hermes",
            "Content-Type": "application/json", "Accept": "application/json, text/event-stream",
        })
        try:
            with opener.open(req, timeout=30) as response:
                value = json.loads(response.read(2_000_000))
        except urllib.error.HTTPError as exc:
            try:
                code = json.loads(exc.read(8192)).get("code")
            except (ValueError, AttributeError):
                code = None
            if code == "access_inactive":
                raise SetupError("Garp recognized the key, but its access is inactive or expired. Ask the account owner to check access.") from None
            if code == "project_unavailable":
                raise SetupError("Garp recognized the key, but its project needs restoring or completing. Ask the account owner to check the project.") from None
            if exc.code == 401:
                raise SetupError("Garp did not accept the saved key. Check the active Hermes profile and its existing Garp credential. This is not a payment request.") from None
            if exc.code == 402:
                raise SetupError("Garp returned an ambiguous access error. Check the existing key and account access before attempting any payment.") from None
            if exc.code == 403:
                raise SetupError("This key cannot access that project URL. Use the matching URL and key from Garp.") from None
            raise SetupError(f"Garp connection returned HTTP {exc.code}; nothing was installed.") from None
        except (OSError, ValueError):
            raise SetupError("Could not read a Garp MCP response. Check connectivity and retry.") from None
        if value.get("error") or "result" not in value:
            raise SetupError("Garp returned a protocol error; configuration has not been verified.")
        return value["result"]
    rpc("initialize", {"protocolVersion": "2025-03-26", "capabilities": {},
                       "clientInfo": {"name": "garp-hermes-setup", "version": VERSION}})
    tools = rpc("tools/list", {})
    names = {t["name"] for t in tools.get("tools", [])}
    if not REQUIRED_TOOLS <= names:
        raise SetupError("This endpoint is missing required Garp tools.")
    project = None
    for name in sorted(REQUIRED_TOOLS):
        result = rpc("tools/call", {"name": name, "arguments": {}})
        if result.get("isError"):
            raise SetupError(f"Connected, but {name} failed. Resolve project access before setup.")
        if name == "garp_get_current_project":
            project = result.get("structuredContent", {})
    # Return no project body or private capability tokens to the installer log.
    return {"tools": len(names), "projectConfigured": bool(project and project.get("projectToken") and project.get("brief"))}


def secure_write(path, data):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp = tempfile.mkstemp(prefix=".garp-", dir=path.parent)
    try:
        with os.fdopen(fd, "wb") as f:
            f.write(data)
        os.chmod(tmp, 0o600)
        os.replace(tmp, path)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


def env_key(text):
    values = re.findall(r"^\s*(?:export\s+)?GARP_MCP_KEY\s*=\s*([^\r\n]*)", text, re.M)
    if not values:
        return ""
    return values[-1].strip().strip("\"'").strip()


def put_env_key(text, key):
    # Garp keys have no quotes or whitespace; never interpret dotenv expansions.
    lines = [line for line in text.splitlines()
             if not re.match(r"^\s*(?:export\s+)?GARP_MCP_KEY\s*=", line)]
    return "\n".join(lines + [f"{KEY_NAME}={key}", ""])


def normalize_key(value):
    if not isinstance(value, str):
        return ""
    key = re.sub(r"^(?:Bearer\s+)+", "", value.strip(), flags=re.I).strip()
    return key if re.fullmatch(r"garp_[A-Za-z0-9_-]{20,95}", key) else ""


def existing_key(hermes):
    """Reuse this Garp connection's credential locally, never in console output."""
    result = hermes.run("config", "get", "mcp_servers.garp.headers.Authorization", "--json", "--raw", required=False)
    if result.returncode:
        return ""
    try:
        header = json.loads(result.stdout)
    except ValueError:
        return ""
    if not isinstance(header, str):
        return ""
    key = re.sub(r"^(?:Bearer\s+)+", "", header.strip(), flags=re.I).strip()
    placeholder = re.fullmatch(r"\$\{([A-Z_][A-Z0-9_]*)\}", key)
    if placeholder:
        result = hermes.run("config", "get", placeholder[1], "--json", "--raw", required=False)
        try:
            key = json.loads(result.stdout) if not result.returncode else ""
        except ValueError:
            key = ""
    return normalize_key(key)


def resolve_key(hermes, env, key_file=None):
    # Explicit input wins. Otherwise repair the credential actually used by this
    # connection before considering a stale GARP_MCP_KEY left by an old install.
    if key_file:
        return normalize_key(key_file.read_text())
    if os.environ.get(KEY_NAME):
        return normalize_key(os.environ[KEY_NAME])
    return existing_key(hermes) or normalize_key(env_key(env.read_text() if env.exists() else ""))


def agent_evidence(stdout):
    """Count actual tool events, never an assistant's claim or process exit code."""
    pending = {}
    passed = {"garpToolCall": False, "browserAction": False}
    for line in stdout.splitlines():
        try:
            event = json.loads(line)
        except ValueError:
            continue
        if not isinstance(event, dict):
            continue
        name = event.get("name", "")
        identity = event.get("tool_call_id") or name
        if event.get("type") == "tool_use":
            pending[identity] = event
        elif event.get("type") == "tool_result" and not event.get("is_error"):
            call = pending.pop(identity, None)
            if not call or call.get("name") != name:
                continue
            output = event.get("output", "")
            if name in {"garp_get_capabilities", "mcp_garp_garp_get_capabilities"} and "workflows" in str(output) and "networks" in str(output):
                passed["garpToolCall"] = True
            if name == "browser_exec" and "Example Domain" in str(output):
                try:
                    code = call.get("input", {}).get("code", "")
                    passed["browserAction"] |= ast.dump(ast.parse(code)) == ast.dump(ast.parse(BROWSER_CHECK_CODE))
                except (TypeError, SyntaxError):
                    pass
    return passed


def check_agent(hermes):
    result = hermes.run("chat", "--oneshot", "--max-turns", "5", "--run-budget", "120",
                        "--format", "stream-json", "-q", AGENT_CHECK_PROMPT,
                        timeout=180, required=False)
    return agent_evidence(result.stdout)


class Hermes:
    def __init__(self, executable="hermes", profile=None):
        self.command = [executable] + (["--profile", profile] if profile else [])

    def run(self, *args, timeout=90, required=True):
        try:
            result = subprocess.run(self.command + list(args), capture_output=True,
                                    text=True, timeout=timeout)
        except FileNotFoundError:
            raise SetupError("Hermes was not found. Run this on the machine with Hermes installed, or supply --hermes /path/to/hermes.") from None
        except subprocess.TimeoutExpired:
            raise SetupError(f"Hermes {args[0]} timed out. Rerun after checking Hermes.") from None
        if required and result.returncode:
            # Do not echo config, headers or exception output containing credentials.
            raise SetupError(f"Hermes {' '.join(args[:2])} failed (exit {result.returncode}). Check that command in Hermes, then rerun setup.")
        return result

    def get(self, key, default=None):
        result = self.run("config", "get", key, "--json", required=False)
        if result.returncode:
            return default
        try:
            return json.loads(result.stdout)
        except ValueError:
            raise SetupError("This Hermes version lacks machine-readable configuration. Update Hermes and retry.") from None

    def set(self, key, value):
        self.run("config", "set", key, json.dumps(value) if not isinstance(value, str) else value)


def configure(hermes, endpoint, key, surfaces, use_profile=True, connection_only=False):
    config = Path(hermes.run("config", "path").stdout.strip()).expanduser()
    env = Path(hermes.run("config", "env-path").stdout.strip()).expanduser()
    if not env.is_absolute():
        raise SetupError("Hermes did not return an absolute secret-file path.")
    if not config.is_absolute() or not env.is_absolute():
        raise SetupError("Hermes did not return absolute configuration paths.")
    backup_root = config.parent / "backups"
    backup_root.mkdir(parents=True, exist_ok=True, mode=0o700)
    backup = Path(tempfile.mkdtemp(prefix="garp-" + time.strftime("%Y%m%d-%H%M%S") + "-", dir=backup_root))
    before = {path: path.read_bytes() if path.exists() else None for path in (config, env)}
    for path, data in before.items():
        if data is not None:
            secure_write(backup / path.name, data)
    old_model = hermes.get("model")
    servers = hermes.get("mcp_servers", {}) or {}
    enabled_servers = {name for name, cfg in servers.items() if isinstance(cfg, dict) and cfg.get("enabled", True)}
    selections = {surface: hermes.get("platform_toolsets." + surface, []) or [] for surface in surfaces}
    try:
        secure_write(env, put_env_key((before[env] or b"").decode(), key).encode())
        hermes.set("mcp_servers.garp", {
            "url": endpoint, "headers": {"Authorization": "Bearer ${GARP_MCP_KEY}", "X-Garp-Client": "hermes"},
            "connect_timeout": 60, "timeout": 120,
        })
        if not connection_only:
            hermes.set("browser.cloud_provider", "local")
            hermes.set("browser.backend", "browser-use")
            hermes.set("browser.use_real_profile", use_profile)
            hermes.set("browser.headed", True)
            # A stale CDP URL would override the selected local browser.
            if hermes.get("browser.cdp_url"):
                hermes.run("config", "unset", "browser.cdp_url")
            # Do not redirect a deliberately sandboxed terminal to the host.
            backend = hermes.get("terminal.backend", "local")
            if backend != "local":
                raise SetupError("Hermes uses a sandboxed terminal. Select a local Hermes profile for desktop controls, then rerun setup.")
        for surface in surfaces:
            selected = selections[surface]
            if not connection_only:
                hermes.run("tools", "enable", "terminal", "browser", "computer_use", "--platform", surface)
                selected = hermes.get("platform_toolsets." + surface, [])
                if not {"terminal", "browser", "computer_use"} <= set(selected):
                    raise SetupError(f"Hermes did not enable local tools for {surface}.")
            # Keep any existing MCP allowlist, while making Garp available here.
            original = selections[surface]
            explicit_servers = set(original) & enabled_servers
            keep_servers = explicit_servers if explicit_servers or "no_mcp" in original else enabled_servers
            hermes.set("platform_toolsets." + surface, sorted((set(selected) - {"no_mcp"}) | keep_servers | {"garp"}))
        if hermes.get("model") != old_model:
            raise SetupError("Hermes changed model settings unexpectedly; restoring the original configuration.")
    except Exception:
        for path, data in before.items():
            if data is None:
                path.unlink(missing_ok=True)
            else:
                secure_write(path, data)
        raise
    return config, backup


def main(argv=None):
    parser = argparse.ArgumentParser(description="Connect normal Garp access and local Hermes controls.")
    parser.add_argument("action", choices=["setup", "connect", "check"], nargs="?", default="setup")
    parser.add_argument("--endpoint", type=endpoint_url)
    parser.add_argument("--key-file", type=Path, help="Read the private Garp key from a local file; never use a key in command arguments.")
    parser.add_argument("--hermes", default="hermes")
    parser.add_argument("--profile")
    parser.add_argument("--surface", action="append", choices=["cli", "api_server", "telegram", "discord", "slack", "whatsapp", "signal"])
    parser.add_argument("--fresh-browser", action="store_true", help="Use a clean browser instead of Hermes's supported real-profile mode.")
    parser.add_argument("--skip-agent-test", action="store_true", help="Skip the bounded read-only test using your configured model.")
    args = parser.parse_args(argv)
    hermes = Hermes(args.hermes, args.profile)
    env = Path(hermes.run("config", "env-path").stdout.strip()).expanduser()
    endpoint = endpoint_url(args.endpoint or hermes.get("mcp_servers.garp.url") or ENDPOINT)
    key = resolve_key(hermes, env, args.key_file)
    if not key and sys.stdin.isatty():
        key = normalize_key(getpass.getpass("Garp private connection key (hidden): "))
    if not key:
        raise SetupError("Provide your Garp connection key using the hidden prompt, GARP_MCP_KEY, or --key-file. Do not paste it into chat.")
    print("Checking Garp access and calling its tools…", flush=True)
    access = probe(endpoint, key)
    print(f"Garp connected: {access['tools']} tools; project loaded: {access['projectConfigured']}.", flush=True)
    if args.action in {"setup", "connect"}:
        surfaces = args.surface or ["cli", "api_server"]
        config, backup = configure(hermes, endpoint, key, surfaces, not args.fresh_browser, connection_only=args.action == "connect")
        print(f"Configured {', '.join(surfaces)} in {config}. Backup: {backup}", flush=True)
    if args.action == "setup":
        print("Installing Hermes's pinned local browser and desktop driver…", flush=True)
        hermes.run("pm", "install", "agent-browser", timeout=900)
        hermes.run("computer-use", "install", timeout=900)
    hermes.run("mcp", "test", "garp", timeout=120)
    print("Hermes MCP connection: passed.", flush=True)
    if args.action == "connect":
        print("Garp connection saved and tested. Reload the MCP connection or start a fresh Hermes chat. Browser, desktop and model tool calling were not tested.")
        return 0
    doctor = hermes.run("computer-use", "doctor", "--json", timeout=120, required=False)
    if doctor.returncode:
        try:
            checks = json.loads(doctor.stdout).get("checks", [])
        except (ValueError, AttributeError):
            checks = []
        names = {check.get("name") for check in checks if check.get("status") == "fail"}
        missing = [label for name, label in [("tcc_accessibility", "Accessibility"), ("tcc_screen_recording", "Screen Recording")] if name in names]
        if missing:
            print("Desktop: grant " + " and ".join(missing) + " to CuaDriver in macOS System Settings → Privacy & Security.")
        else:
            print("Desktop: needs attention. Run `hermes computer-use doctor` in this profile for the specific repair.")
    else:
        print("Desktop driver health: passed. An agent desktop action still needs to be tested.")
    agent = {"garpToolCall": False, "browserAction": False}
    if args.skip_agent_test:
        print("Model and browser actions: skipped, not verified.")
    else:
        print("Testing actual model tool calls and browser navigation (up to 2 minutes, using your current model)…", flush=True)
        try:
            agent = check_agent(hermes)
        except SetupError:
            pass
        print("Model called Garp: " + ("passed" if agent["garpToolCall"] else "not verified"))
        print("Model drove the browser: " + ("passed" if agent["browserAction"] else "not verified"))
        if not all(agent.values()):
            print("The model did not complete both tool checks. Check its tool-call support, actual loaded context and browser availability. Do not treat installation alone as a working agent.")
    print("Start a fresh Hermes chat to use the configured tools. You can ask it to check Garp, browser and desktop access again.")
    print("Use the local browser for X; an X Developer API key is not required for this workflow. Browser sign-in remains a user step.")
    return 0 if not doctor.returncode and all(agent.values()) else 3


if __name__ == "__main__":
    try:
        sys.exit(main())
    except (SetupError, OSError) as exc:
        print(f"Garp setup: {exc}", file=sys.stderr)
        sys.exit(1)
