"""TokenGuard Windows connector. No third-party Python dependencies."""

from contextlib import contextmanager
import socket
import tempfile
import argparse
import base64
import ctypes
from ctypes import wintypes
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise RuntimeError("Redirecionamento recusado. Use o endereço final do TokenGuard.")


def origin(value):
    url = urllib.parse.urlsplit(value)
    if url.username or url.password or url.query or url.fragment or url.path not in ("", "/"):
        raise ValueError("Informe somente a origem do TokenGuard, sem senha ou caminho.")
    if url.scheme != "https" and not (url.scheme == "http" and url.hostname in ("127.0.0.1", "localhost")):
        raise ValueError("Conexão exige HTTPS; HTTP permitido apenas no piloto local.")
    if not url.hostname:
        raise ValueError("Endereço inválido.")
    return value.rstrip("/")


def request(base, path, body=None, key=None):
    headers = {"Content-Type": "application/json"}
    if key:
        headers["Authorization"] = "Bearer " + key
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(base + path, data=data, headers=headers)
    try:
        with urllib.request.build_opener(NoRedirect()).open(req, timeout=25) as response:
            payload = response.read(2 * 1024 * 1024 + 1)
            if len(payload) > 2 * 1024 * 1024:
                raise RuntimeError("Resposta acima do limite.")
            return json.loads(payload)
    except urllib.error.HTTPError as exc:
        raise RuntimeError(
            f"TokenGuard respondeu HTTP {exc.code}. Confira conexão, aprovação e assinatura."
        ) from None


class Blob(ctypes.Structure):
    _fields_ = [("size", wintypes.DWORD), ("data", ctypes.POINTER(ctypes.c_ubyte))]


def protect(data, decrypt=False):
    if os.name != "nt":
        raise RuntimeError("Este iniciador usa proteção do Windows; outras plataformas ainda não suportadas.")
    buf = ctypes.create_string_buffer(data)
    source = Blob(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_ubyte)))
    result = Blob()
    library = ctypes.WinDLL("crypt32", use_last_error=True)
    method = library.CryptUnprotectData if decrypt else library.CryptProtectData
    method.argtypes = [
        ctypes.POINTER(Blob),
        ctypes.c_void_p,
        ctypes.c_void_p,
        ctypes.c_void_p,
        ctypes.c_void_p,
        wintypes.DWORD,
        ctypes.POINTER(Blob),
    ]
    method.restype = wintypes.BOOL
    if not method(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(result)):
        raise RuntimeError("Falha na proteção de credenciais do Windows.")
    try:
        return ctypes.string_at(result.data, result.size)
    finally:
        free = ctypes.WinDLL("kernel32").LocalFree
        free.argtypes = [ctypes.c_void_p]
        free.restype = ctypes.c_void_p
        free(ctypes.cast(result.data, ctypes.c_void_p))


def profile_path(base, client):
    folder = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "TokenGuard" / "connections"
    folder.mkdir(parents=True, exist_ok=True)
    name = hashlib.sha256((base + "/" + client).encode()).hexdigest()[:24]
    return folder / (name + ".json")


def connect(base, client):
    flow = request(base, "/v1/connections/start", {"client": client})
    print("Abra o TokenGuard, entre e confirme somente se iniciou esta conexão.")
    print("Código a digitar na página:", flow["user_code"])
    url = base + "/?connect=" + urllib.parse.quote(flow["request_id"])
    print("Página de autorização:", url)
    webbrowser.open(url)
    deadline = time.monotonic() + flow["expires_in"]
    while time.monotonic() < deadline:
        time.sleep(3)
        result = request(
            base,
            "/v1/connections/poll",
            {
                "request_id": flow["request_id"],
                "device_secret": flow["device_secret"],
            },
        )
        if result["status"] == "approved":
            encrypted = base64.b64encode(protect(json.dumps(result).encode())).decode()
            path = profile_path(base, client)
            temporary = path.with_suffix(".tmp")
            temporary.write_text(json.dumps({"protected": encrypted}), encoding="utf-8")
            temporary.replace(path)
            print(
                "Conexão autorizada. Credencial protegida no Windows; revogue em Chaves de integração se necessário."
            )
            return result
    raise RuntimeError("Código expirou. Inicie a conexão novamente.")


def build_command(executable, base, client, model, credentials, extra):
    env = os.environ.copy()
    if client == "codex":
        env["TOKENGUARD_API_KEY"] = credentials["api_key"]
        config = '{name="TokenGuard",base_url=' + json.dumps(base + "/v1")
        config += ',env_key="TOKENGUARD_API_KEY",wire_api="responses",request_max_retries=0,stream_max_retries=0,http_headers={"X-Session-Id"='
        config += json.dumps(credentials["session_id"]) + "}}"
        args = [
            executable,
            "-c",
            'model_provider="tokenguard"',
            "-c",
            'web_search="disabled"',
            "-c",
            "model_providers.tokenguard=" + config,
            "-m",
            model,
        ]
    else:
        for field in (
            "ANTHROPIC_API_KEY",
            "CLAUDE_CODE_OAUTH_TOKEN",
            "CLAUDE_CODE_USE_BEDROCK",
            "CLAUDE_CODE_USE_VERTEX",
            "CLAUDE_CODE_USE_FOUNDRY",
        ):
            env.pop(field, None)
        env.update(
            ANTHROPIC_BASE_URL=base,
            ANTHROPIC_AUTH_TOKEN=credentials["api_key"],
            ANTHROPIC_CUSTOM_HEADERS="X-Session-Id: " + credentials["session_id"],
        )
        args = [executable, "--model", model]
    return args + extra, env


@contextmanager
def local_bili(base, package, node, session_id):
    """Owned, isolated pilot process. No credentials are written to its configuration."""
    package = Path(package).resolve(strict=True)
    node = Path(node).resolve(strict=True)
    metadata = json.loads((package / "package.json").read_text(encoding="utf-8"))
    if metadata.get("name") != "billion-context" or metadata.get("version") != "0.1.215":
        raise RuntimeError("Bili version not validated. This pilot requires 0.1.215.")
    entry = package / "dist" / "index.js"
    if not entry.is_file() or node.suffix.lower() != ".exe":
        raise RuntimeError("Invalid local runtime.")
    # The caller explicitly selects installed executables; no downloads or global changes.
    with socket.socket() as sock:
        sock.bind(("127.0.0.1", 0))
        port = sock.getsockname()[1]
    endpoint = f"http://127.0.0.1:{port}"
    with tempfile.TemporaryDirectory(prefix="tokenguard-local-") as folder:
        root = Path(folder)
        env = {k: v for k, v in os.environ.items() if not k.startswith(("BILI_", "ACP_"))}
        for name in (
            "XDG_DATA_HOME",
            "XDG_STATE_HOME",
            "XDG_CONFIG_HOME",
            "XDG_CACHE_HOME",
            "BILI_SESSIONS_DIR",
        ):
            target = root / name
            target.mkdir()
            env[name] = str(target)
        env["ACP_UPSTREAM"] = base
        env["ACP_SESSION_HEADER"] = "x-session-id"
        config = root / "config.json"
        config.write_text(
            json.dumps(
                {
                    "host": "127.0.0.1",
                    "port": port,
                    "upstream": base,
                    "sessionHeader": "x-session-id",
                    "autoUpdate": False,
                }
            ),
            encoding="utf-8",
        )
        process = subprocess.Popen(
            [
                str(node),
                str(entry),
                "start",
                "--config",
                str(config),
                "--host",
                "127.0.0.1",
                "--port",
                str(port),
                "--no-auto-update",
            ],
            env=env,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
        )
        try:
            for _ in range(100):
                if process.poll() is not None:
                    raise RuntimeError("Local bili stopped before becoming ready.")
                try:
                    req = urllib.request.Request(endpoint + "/__bili/health")
                    with urllib.request.build_opener(NoRedirect()).open(req, timeout=1) as response:
                        health = json.loads(response.read(65536))
                    if health.get("upstream") == base:
                        break
                except (OSError, ValueError):
                    pass
                time.sleep(0.2)
            else:
                raise RuntimeError("Local bili startup could not be verified.")
            yield endpoint
        finally:
            if process.poll() is None:
                process.terminate()
                try:
                    process.wait(timeout=10)
                except subprocess.TimeoutExpired:
                    process.kill()
                    process.wait(timeout=5)


MCP_TOOLS = frozenset(("compress", "decompress", "search_context", "acp_status", "acp_cache"))


def mcp_bridge():
    endpoint = origin(os.environ["TOKENGUARD_MCP_PROXY"])
    if urllib.parse.urlsplit(endpoint).hostname != "127.0.0.1":
        raise RuntimeError("MCP bridge requires loopback.")
    session = os.environ["TOKENGUARD_MCP_SESSION"]
    initialized = False
    while True:
        line = sys.stdin.buffer.readline(2 * 1024 * 1024 + 1)
        if not line:
            return
        if len(line) > 2 * 1024 * 1024:
            return
        message_id = None
        try:
            message = json.loads(line)
            message_id = message.get("id")
            method = message.get("method")
            params = message.get("params") or {}
            if method == "initialize":
                initialized = True
                result = {
                    "protocolVersion": "2024-11-05",
                    "capabilities": {"tools": {}},
                    "serverInfo": {"name": "TokenGuard Context", "version": "0.1.0"},
                }
            elif method.startswith("notifications/"):
                continue
            elif method == "ping":
                result = {}
            elif not initialized:
                raise ValueError("MCP not initialized")
            elif method == "tools/list":
                manifest = request(endpoint, "/__bili/plugin/manifest")
                result = {
                    "tools": [
                        {
                            "name": t["name"],
                            "description": t.get("description", ""),
                            "inputSchema": t["input_schema"],
                        }
                        for t in manifest["tools"]["anthropic"]
                        if t["name"] in MCP_TOOLS
                    ]
                }
            elif method == "tools/call":
                name = params.get("name")
                args = dict(params.get("arguments") or {})
                if name not in MCP_TOOLS or args.get("conversation_id", session) != session:
                    raise ValueError("Tool or session not authorized")
                args.pop("conversation_id", None)
                answer = request(
                    endpoint, "/__bili/plugin/tool", {"conversationId": session, "tool": name, "args": args}
                )
                result = {
                    "content": [{"type": "text", "text": answer.get("result", "")}],
                    "isError": not answer.get("ok", False) or answer.get("outcome") in ("failure", "refused"),
                }
            else:
                raise ValueError("Unsupported MCP method")
            output = {"jsonrpc": "2.0", "id": message_id, "result": result}
        except (ValueError, TypeError, AttributeError, KeyError, RuntimeError, OSError):
            output = {
                "jsonrpc": "2.0",
                "id": message_id,
                "error": {
                    "code": -32602,
                    "message": "TokenGuard context request failed or was not authorized.",
                },
            }
        if message_id is not None:
            print(json.dumps(output), flush=True)


def build_local_command(executable, endpoint, model, credentials, extra):
    command, env = build_command(executable, endpoint, "codex", model, credentials, [])
    config = (
        "{command="
        + json.dumps(sys.executable)
        + ",args="
        + json.dumps([str(Path(__file__).resolve()), "--mcp-bridge"])
    )
    config += ",env={TOKENGUARD_MCP_PROXY=" + json.dumps(endpoint)
    config += ",TOKENGUARD_MCP_SESSION=" + json.dumps(credentials["session_id"]) + "}}"
    return command + ["-c", "mcp_servers.tokenguard_context=" + config] + extra, env


def main():
    parser = argparse.ArgumentParser(
        description="Conectar Codex/Claude Code ao TokenGuard sem copiar chaves."
    )
    parser.add_argument("--url", required=True)
    parser.add_argument("--client", choices=["codex", "claude"], required=True)
    parser.add_argument(
        "--local-bili", action="store_true", help="Experimental local pilot; server authorization required"
    )
    parser.add_argument("--bili-package", help="Installed billion-context 0.1.215 directory")
    parser.add_argument("--node-exe", help="Installed node.exe path")
    parser.add_argument("--connect-only", action="store_true")
    parser.add_argument("--reconnect", action="store_true")
    parser.add_argument("client_args", nargs=argparse.REMAINDER)
    args = parser.parse_args()
    base = origin(args.url)
    if os.name != "nt":
        raise RuntimeError("Primeira versão disponível somente para Windows.")
    capabilities = request(base, "/v1/connections/capabilities")
    path = profile_path(base, args.client)
    if args.reconnect or not path.exists():
        credentials = connect(base, args.client)
    else:
        credentials = json.loads(protect(base64.b64decode(json.loads(path.read_text())["protected"]), True))
    if args.connect_only:
        return
    mode = request(base, "/v1/connections/mode", key=credentials["api_key"])
    local_mode = mode.get("compression_location") == "client"
    if local_mode != args.local_bili:
        raise RuntimeError("Local/server mode does not match the operator authorization.")
    if local_mode and (args.client != "codex" or not args.bili_package or not args.node_exe):
        raise RuntimeError("Local pilot requires Codex, --bili-package and --node-exe.")
    model = capabilities[args.client + "_model"]
    if not capabilities["inference_enabled"] or not model:
        raise RuntimeError(
            "Conexão salva. Operador ainda precisa habilitar inferência e configurar o modelo desta ferramenta."
        )
    executable = shutil.which(args.client + ".exe")
    if not executable:
        raise RuntimeError(
            "Instale o cliente nativo "
            + args.client
            + " e abra novamente. Nenhum aplicativo foi instalado automaticamente."
        )
    credentials["session_id"] = request(base, "/v1/connections/session", {}, credentials["api_key"])[
        "session_id"
    ]
    extra = args.client_args[1:] if args.client_args[:1] == ["--"] else args.client_args
    command, env = build_command(executable, base, args.client, model, credentials, extra)
    # No shell; provider key never appears in command arguments or global config.
    if local_mode:
        with local_bili(base, args.bili_package, args.node_exe, credentials["session_id"]) as endpoint:
            command, env = build_local_command(executable, endpoint, model, credentials, extra)
            print("TokenGuard local pilot: transport enabled; compression is not yet certified.")
            result = subprocess.call(command, env=env)
        raise SystemExit(result)
    raise SystemExit(subprocess.call(command, env=env))


if __name__ == "__main__":
    try:
        if sys.argv[1:] == ["--mcp-bridge"]:
            mcp_bridge()
        else:
            main()
    except (RuntimeError, ValueError, OSError, KeyError) as error:
        print("TokenGuard:", str(error), file=sys.stderr)
        sys.exit(1)
