#!/usr/bin/env python3
"""ANKLE OS command line, v1.

Sign in with your browser (OAuth 2.1 + PKCE), then list Worlds, search SURF,
read and build pages, and call any ANKLE MCP tool. Python 3.9+, standard
library only. Plain text by default; add --json to any command.

Auth: `ankle login` stores a scoped key at ~/.config/ankle/credentials.json
(mode 0600) and refreshes it automatically. Or set ANKLE_AGENT_KEY to an ak_
key created at https://ankle.studio/developers (it takes precedence).
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import http.server
import json
import os
import re
import secrets
import shutil
import socket
import subprocess
import sys
import time
import webbrowser
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, urlencode, urlsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener

ANKLE_CLI_ID = "ankle-os-cli"  # install.sh uses this marker to recognise its own install
VERSION = "1.0.0"
DEFAULT_ORIGIN = "https://ankle.studio"  # the developer home: CLI, MCP, keys
FIRST_PARTY = ("https://aleqth.com", "https://ankle.studio", "https://ankle.website")
FIRST_PARTY_HOSTS = {"aleqth.com", "www.aleqth.com", "ankle.website", "www.ankle.website",
                     "ankle.studio", "www.ankle.studio"}
DEFAULT_WORLD_ORIGIN = "https://{word}.ankle.website"
CALLBACK_PORTS = tuple(range(53682, 53692))  # registered once; first free port is used
MCP_PROTOCOL = "2025-11-25"
READ_SCOPES = ["worlds.list", "builder.list", "builder.get", "surf.search", "credits.balance"]
DRAFT_SCOPES = READ_SCOPES + ["worlds.found", "builder.create", "builder.patch", "builder.attach"]
SCOPE_PRESETS = {
    "read": READ_SCOPES,
    "draft": DRAFT_SCOPES,
    "build": DRAFT_SCOPES + ["pages.generate"],
    "settings": ["settings.get", "settings.update"],
}
WORD_RE = re.compile(r"^[a-z](?:[a-z0-9-]{0,39}[a-z0-9])?$")
MAX_REQUEST = 6 * 1024 * 1024
MAX_RESPONSE = 12 * 1024 * 1024
MAX_FILE_ARG = 5 * 1024 * 1024
USER_AGENT = "ankle-cli/" + VERSION
DESK_COMMANDS = {"tui", "harness", "open", "spin", "status", "--tui", "--harness", "--spin", "--status", "--check"}

EXIT_OK, EXIT_ERR, EXIT_USAGE, EXIT_AUTH, EXIT_NOTFOUND = 0, 1, 2, 3, 4


def _prog() -> str:
    name = os.path.basename(sys.argv[0] or "ankle")
    if name.endswith(".py"):
        return "python3 " + name
    return name if name.startswith("ankle") else "ankle"


PROG = _prog()


# -- errors and output -------------------------------------------------------

class CliError(Exception):
    def __init__(self, message: str, code: int = EXIT_ERR, status: int | None = None, hint: str | None = None):
        super().__init__(message)
        self.message, self.code, self.status, self.hint = message, code, status, hint


class DryRun(Exception):
    pass


class Out:
    json = False


def emit(obj, text: str | None = None) -> None:
    if Out.json or text is None:
        print(json.dumps(obj, ensure_ascii=False))
    else:
        print(text)


def note(msg: str) -> None:
    print(msg, file=sys.stderr)


def _cell(value, width: int | None) -> str:
    if value is None or value == "":
        text = "-"
    elif isinstance(value, bool):
        text = "yes" if value else "no"
    else:
        text = " ".join(str(value).split())
    if width and len(text) > width:
        text = text[: max(1, width - 3)] + "..."
    return text


def table(headers, rows, widths=None) -> str:
    """Aligned ASCII table. The last column is never truncated (often a URL)."""
    widths = widths or [48] * len(headers)
    cells = [[_cell(v, widths[i] if i < len(headers) - 1 else None) for i, v in enumerate(r)] for r in rows]
    cols = [max([len(h)] + [len(r[i]) for r in cells]) for i, h in enumerate(headers)]
    line = lambda vals: "  ".join(v.ljust(cols[i]) for i, v in enumerate(vals)).rstrip()
    return "\n".join([line(headers), line(["-" * c for c in cols])] + [line(r) for r in cells])


def kv_block(pairs) -> str:
    pairs = [(k, _cell(v, None)) for k, v in pairs]
    w = max(len(k) for k, _ in pairs) if pairs else 0
    return "\n".join(k.ljust(w) + "  " + v for k, v in pairs)


# -- HTTP ----------------------------------------------------------------------

class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


_OPENER = build_opener(ProxyHandler({}), _NoRedirect())


class Response:
    def __init__(self, status: int, headers, body: bytes, url: str):
        self.status, self.headers, self.body, self.url = status, headers, body, url

    def json(self):
        try:
            return json.loads(self.body.decode("utf-8"))
        except (ValueError, UnicodeDecodeError):
            raise CliError(f"HTTP {self.status}: expected JSON from {_host_of(self.url)}, got a non-JSON response",
                           status=self.status) from None

    def is_json(self) -> bool:
        ctype = (self.headers.get("Content-Type") or "") if self.headers else ""
        if "json" in ctype:
            return True
        try:
            json.loads(self.body.decode("utf-8"))
            return True
        except (ValueError, UnicodeDecodeError):
            return False


def _host_of(url: str) -> str:
    p = urlsplit(url)
    return f"{p.scheme}://{p.netloc}"


def http_request(method: str, url: str, *, body=None, form=None, headers=None, token: str | None = None,
                 timeout: float = 120) -> Response:
    hdrs = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    data = None
    if form is not None:
        data = urlencode(form).encode()
        hdrs["Content-Type"] = "application/x-www-form-urlencoded"
    elif body is not None:
        data = json.dumps(body, ensure_ascii=False).encode("utf-8")
        if len(data) > MAX_REQUEST:
            raise CliError("Request exceeds 6 MiB.", EXIT_USAGE)
        hdrs["Content-Type"] = "application/json"
    hdrs.update(headers or {})
    if token:
        hdrs["Authorization"] = "Bearer " + token
    req = Request(url, data=data, headers=hdrs, method=method)
    try:
        with _OPENER.open(req, timeout=timeout) as r:
            raw = r.read(MAX_RESPONSE + 1)
            status, rh = r.status, r.headers
    except HTTPError as exc:
        status, rh = exc.code, exc.headers
        try:
            raw = exc.read(MAX_RESPONSE + 1)
        except Exception:
            raw = b""
    except (socket.timeout, TimeoutError):
        raise CliError(f"Timed out waiting for {_host_of(url)}. A write may have committed; "
                       "read the current state, then retry with the identical idempotency key.") from None
    except URLError as exc:
        reason = getattr(exc, "reason", exc)
        raise CliError(f"Cannot reach {_host_of(url)}: {reason}") from None
    except OSError as exc:
        raise CliError(f"Connection to {_host_of(url)} failed: {exc.__class__.__name__}") from None
    if len(raw) > MAX_RESPONSE:
        raise CliError("Response exceeds 12 MiB; check the outcome before retrying.")
    return Response(status, rh, raw, url)


def server_message(resp: Response) -> str:
    """The server's own words, compacted. Never includes request headers."""
    try:
        data = json.loads(resp.body.decode("utf-8"))
    except (ValueError, UnicodeDecodeError):
        text = resp.body.decode("utf-8", "replace").strip()
        if not text:
            return "(empty response)"
        if text[:1] == "<":
            m = re.search(r"<h1[^>]*>(.*?)</h1>", text, re.I | re.S) or re.search(r"<title[^>]*>(.*?)</title>", text, re.I | re.S)
            return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", m.group(1))).strip() if m else "(non-JSON HTML response)"
        return " ".join(text.split())[:300]
    return _describe(data)


def _describe(data) -> str:
    if isinstance(data, str):
        return data
    if not isinstance(data, dict):
        return json.dumps(data)[:300]
    if "error_description" in data:
        return f"{data.get('error', 'error')}: {data['error_description']}"
    err = data.get("error")
    if isinstance(err, dict):
        return str(err.get("message") or err)
    detail = data.get("detail", data.get("message", err))
    if isinstance(detail, dict):
        msg = str(detail.get("message") or "")
        fields = detail.get("fields") or []
        parts = [f"{f.get('field')}: {f.get('message')}" for f in fields if isinstance(f, dict)]
        return (msg + (" (" + "; ".join(parts) + ")" if parts else "")).strip() or json.dumps(detail)[:300]
    if isinstance(detail, list):
        return "; ".join(_describe(d) for d in detail)[:300]
    return str(detail) if detail is not None else json.dumps(data)[:300]


def _hint_for(msg: str, status: int | None) -> str | None:
    m = re.search(r"missing scope: ([a-z_.]+)", msg or "")
    if m:
        return f"This key lacks {m.group(1)}. Run: {PROG} login --scopes +{m.group(1)}"
    if status == 409:
        return "Read the current revision and reconcile; never overwrite newer edits."
    if status == 429:
        return "Rate limited (60 requests/minute per key). Wait and retry."
    return None


def http_error(resp: Response, prefix: str = "") -> CliError:
    msg = server_message(resp)
    return CliError(f"{prefix}HTTP {resp.status}: {msg}", status=resp.status, hint=_hint_for(msg, resp.status))


# -- origins and files -----------------------------------------------------------

def _is_loopback_origin(origin: str) -> bool:
    try:
        p = urlsplit(origin)
        p.port  # noqa: B018 - raises on a bad port
    except ValueError:
        return False
    return p.scheme == "http" and (p.hostname or "") in {"127.0.0.1", "localhost", "::1"} and p.path in ("", "/") \
        and not p.query and not p.fragment and not p.username


def resolve_origin(arg: str | None) -> str:
    origin = (arg or os.environ.get("ANKLE_ORIGIN") or DEFAULT_ORIGIN).rstrip("/")
    if origin in FIRST_PARTY or _is_loopback_origin(origin):
        return origin
    raise CliError("ANKLE_ORIGIN must be https://aleqth.com, https://ankle.studio or https://ankle.website "
                   "(or an http://127.0.0.1 test server).", EXIT_USAGE)


def world_origin(word: str) -> str:
    word = (word or "").strip().lower()
    if not WORD_RE.match(word):
        raise CliError(f"'{word}' is not a World word (lowercase letters, digits, hyphens; 1-41 chars).", EXIT_USAGE)
    template = os.environ.get("ANKLE_WORLD_ORIGIN") or DEFAULT_WORLD_ORIGIN
    url = template.replace("{word}", word).rstrip("/")
    p = urlsplit(url)
    host = p.hostname or ""
    if p.scheme == "https" and host == f"{word}.ankle.website" and not p.path:
        return url
    if p.scheme == "http" and host in {"127.0.0.1", "localhost", "::1"}:
        return url
    raise CliError("ANKLE_WORLD_ORIGIN must resolve to https://<word>.ankle.website (or a loopback test server).", EXIT_USAGE)


def _same_realm(a: str | None, b: str) -> bool:
    return bool(a) and (a == b or (a in FIRST_PARTY and b in FIRST_PARTY))


def config_dir() -> Path:
    if os.environ.get("ANKLE_CONFIG_DIR"):
        return Path(os.environ["ANKLE_CONFIG_DIR"]).expanduser()
    base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(os.path.expanduser("~"), ".config")
    return Path(base) / "ankle"


def creds_path() -> Path:
    return config_dir() / "credentials.json"


def client_path() -> Path:
    return config_dir() / "client.json"


def _write_private(path: Path, data: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    try:
        os.chmod(path.parent, 0o700)
    except OSError:
        pass
    tmp = path.with_name(f".{path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp")
    fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as fh:
            json.dump(data, fh, indent=2)
            fh.write("\n")
            fh.flush()
            os.fsync(fh.fileno())
        os.chmod(tmp, 0o600)
        os.replace(tmp, path)
    finally:
        if tmp.exists():
            tmp.unlink()


def _read_private(path: Path) -> dict | None:
    try:
        raw = path.read_text(encoding="utf-8")
    except FileNotFoundError:
        return None
    except OSError as exc:
        raise CliError(f"Cannot read {path}: {exc.strerror}") from None
    try:
        mode = path.stat().st_mode & 0o777
        if os.name == "posix" and mode & 0o077:
            os.chmod(path, 0o600)
            note(f"warning: {path} was readable by other users; permissions reset to 0600.")
    except OSError:
        pass
    try:
        data = json.loads(raw)
    except ValueError:
        raise CliError(f"{path} is not valid JSON. Delete it and run: {PROG} login") from None
    return data if isinstance(data, dict) else None


def load_creds() -> dict | None:
    c = _read_private(creds_path())
    if c:
        return c
    if not os.environ.get("ANKLE_CONFIG_DIR") and not os.environ.get("XDG_CONFIG_HOME"):
        legacy = Path(os.path.expanduser("~")) / ".ankle" / "credentials.json"
        c2 = _read_private(legacy)
        if c2:
            if not c2.get("access_token") and c2.get("api_key"):
                c2 = dict(c2, access_token=c2["api_key"], origin=c2.get("origin") or DEFAULT_ORIGIN)
            return c2
    return None


class _FileLock:
    """Serialises refresh-token rotation across concurrent CLI processes (POSIX)."""

    def __enter__(self):
        self.fh = None
        try:
            import fcntl
            config_dir().mkdir(parents=True, exist_ok=True)
            self.fh = open(config_dir() / ".lock", "a")
            fcntl.flock(self.fh.fileno(), fcntl.LOCK_EX)
        except (ImportError, OSError):
            self.fh = None
        return self

    def __exit__(self, *exc):
        if self.fh:
            self.fh.close()


def _valid_token(tok: str) -> bool:
    return bool(tok) and len(tok) <= 512 and all(33 <= ord(c) < 127 for c in tok)


# -- auth + API ------------------------------------------------------------------------

class Auth:
    def __init__(self, origin: str):
        self.origin = origin
        self.creds = None
        env = os.environ.get("ANKLE_AGENT_KEY", "").strip()
        if env:
            if not _valid_token(env):
                raise CliError("ANKLE_AGENT_KEY contains whitespace or invalid characters.", EXIT_USAGE)
            self.token, self.source = env, "env"
            return
        creds = load_creds()
        if creds and creds.get("access_token") and _same_realm(creds.get("origin"), origin):
            self.creds, self.token, self.source = creds, creds["access_token"], "oauth"
        else:
            self.token, self.source = None, None

    def require(self) -> None:
        if not self.token:
            raise CliError(f"Not signed in. Run: {PROG} login   (or set ANKLE_AGENT_KEY)", EXIT_AUTH)

    def adopt_disk(self) -> bool:
        """Another process may have rotated the token; pick it up instead of refreshing again."""
        disk = load_creds()
        if disk and disk.get("access_token") and disk["access_token"] != self.token \
                and _same_realm(disk.get("origin"), self.origin):
            self.creds, self.token = disk, disk["access_token"]
            return True
        return False

    def refresh(self) -> None:
        c = self.creds or {}
        if not c.get("refresh_token") or not c.get("token_endpoint"):
            raise CliError(f"Session expired and no refresh token is stored. Run: {PROG} login", EXIT_AUTH)
        with _FileLock():
            if self.adopt_disk():
                return
            resp = http_request("POST", c["token_endpoint"], form={
                "grant_type": "refresh_token", "refresh_token": c["refresh_token"], "client_id": c.get("client_id", "")})
            if resp.status != 200:
                if self.adopt_disk():
                    return
                raise CliError(f"Session refresh failed: HTTP {resp.status}: {server_message(resp)}. Run: {PROG} login",
                               EXIT_AUTH, status=resp.status)
            tok = resp.json()
            access = tok.get("access_token") if isinstance(tok, dict) else None
            if not isinstance(access, str) or not _valid_token(access):
                raise CliError("Session refresh returned no usable access token. Run: " + PROG + " login", EXIT_AUTH)
            c = dict(c)
            c["access_token"] = access
            c["refresh_token"] = tok.get("refresh_token") or c["refresh_token"]
            c["scope"] = tok.get("scope", c.get("scope", ""))
            c["refreshed_at"] = int(time.time())
            _write_private(creds_path(), c)
            self.creds, self.token = c, access


class Api:
    def __init__(self, origin: str, dry_run: bool = False):
        self.origin = origin
        self.dry_run = dry_run
        self.auth = Auth(origin)
        self._rpc_id = 0
        self._tools = None

    def _dry(self, method: str, url: str, body) -> None:
        print(json.dumps({"method": method, "url": url, "request": body}, ensure_ascii=False))
        raise DryRun()

    def authed(self, method: str, url: str, body=None, headers=None) -> Response:
        self.auth.require()
        resp = http_request(method, url, body=body, headers=headers, token=self.auth.token)
        if resp.status == 401 and self.auth.source == "oauth":
            msg = server_message(resp)
            retry = False
            if self.auth.adopt_disk():
                retry = True
            elif "revoked" in msg.lower():
                raise CliError(f"HTTP 401: {msg}. This key was revoked (for example at /developers); "
                               f"it is not silently renewed. Run: {PROG} login", EXIT_AUTH, status=401)
            elif (self.auth.creds or {}).get("refresh_token"):
                self.auth.refresh()
                retry = True
            if retry:
                resp = http_request(method, url, body=body, headers=headers, token=self.auth.token)
        if resp.status == 401:
            msg = server_message(resp)
            fix = "ANKLE_AGENT_KEY was rejected; replace it or unset it." if self.auth.source == "env" else f"Run: {PROG} login"
            raise CliError(f"HTTP 401: {msg}. {fix}", EXIT_AUTH, status=401)
        return resp

    # MCP (stateless Streamable HTTP, JSON responses)
    def mcp(self, method: str, params: dict | None = None):
        self._rpc_id += 1
        msg = {"jsonrpc": "2.0", "id": self._rpc_id, "method": method, "params": params or {}}
        url = self.origin + "/api/mcp"
        if self.dry_run:
            self._dry("POST", url, msg)
        resp = self.authed("POST", url, body=msg, headers={"Accept": "application/json", "MCP-Protocol-Version": MCP_PROTOCOL})
        if resp.status != 200:
            raise http_error(resp)
        data = resp.json()
        if not isinstance(data, dict):
            raise CliError("MCP server returned an unexpected payload.")
        if data.get("error"):
            err = data["error"]
            raise CliError(f"MCP error {err.get('code')}: {err.get('message')}")
        return data.get("result") or {}

    def tools(self) -> list:
        if self._tools is None:
            self._tools = self.mcp("tools/list").get("tools") or []
        return self._tools

    def tool(self, name: str):
        name = name.replace(".", "_")
        return next((t for t in self.tools() if t.get("name") == name), None)

    def call(self, name: str, arguments: dict, check: bool = True):
        name = name.replace(".", "_")
        if check and not self.dry_run and not self.tool(name):
            scope = name.replace("_", ".", 1)
            available = ", ".join(t.get("name", "") for t in self.tools()) or "none"
            raise CliError(f"Tool '{name}' is not available to this key (tools: {available}).",
                           hint=f"If it needs scope {scope}, run: {PROG} login --scopes +{scope}")
        res = self.mcp("tools/call", {"name": name, "arguments": arguments})
        value = res.get("structuredContent")
        if value is None:
            texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
            try:
                value = json.loads(texts[0]) if texts else {}
            except ValueError:
                value = {"text": "\n".join(texts)}
        if res.get("isError"):
            raise tool_error(value)
        return value

    def act(self, action: str, payload: dict):
        url = self.origin + "/api/agent-bridge/act"
        body = {"action": action, "payload": payload}
        if self.dry_run:
            self._dry("POST", url, body)
        resp = self.authed("POST", url, body=body)
        if resp.status != 200:
            raise http_error(resp)
        return resp.json()

    def me(self):
        url = self.origin + "/api/agent-bridge/me"
        if self.dry_run:
            self._dry("GET", url, None)
        resp = self.authed("GET", url)
        if resp.status != 200:
            raise http_error(resp)
        return resp.json()


def tool_error(value) -> CliError:
    value = value if isinstance(value, dict) else {"detail": value}
    status = value.get("http_status")
    detail = _describe({"detail": value.get("detail")})
    state = value.get("status") or "rejected"
    if state == "unknown":
        return CliError("Outcome unknown: " + detail, hint="Read the draft; retry mutations with the identical idempotency key.")
    prefix = f"{state}: HTTP {status}: " if status else f"{state}: "
    return CliError(prefix + detail, status=status, hint=_hint_for(detail, status))


# -- OAuth login -----------------------------------------------------------------------

def _b64url(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def _trusted_endpoint(url, origin: str) -> bool:
    if not isinstance(url, str):
        return False
    p = urlsplit(url)
    if p.scheme == "https" and (p.hostname or "") in FIRST_PARTY_HOSTS:
        return True
    return _is_loopback_origin(origin) and url.startswith(origin + "/")


def discover(origin: str) -> dict:
    resp = http_request("GET", origin + "/.well-known/oauth-authorization-server")
    if resp.status != 200:
        raise http_error(resp, "OAuth discovery failed: ")
    meta = resp.json()
    if not isinstance(meta, dict):
        raise CliError("OAuth discovery returned an unexpected document.")
    for key in ("authorization_endpoint", "token_endpoint", "registration_endpoint"):
        if not _trusted_endpoint(meta.get(key), origin):
            raise CliError(f"OAuth discovery: {key} is missing or not a first-party ANKLE URL; refusing to continue.")
    for key in ("revocation_endpoint",):
        if meta.get(key) and not _trusted_endpoint(meta[key], origin):
            meta.pop(key)
    if "S256" not in (meta.get("code_challenge_methods_supported") or ["S256"]):
        raise CliError("OAuth server does not advertise PKCE S256; refusing to continue.")
    return meta


def resolve_scopes(raw: str | None, supported) -> list:
    if not raw:
        return []  # let the server apply its default read-mostly set
    tokens = [t for t in re.split(r"[\s,]+", raw.strip()) if t]
    out = list(READ_SCOPES) if any(t.startswith("+") for t in tokens) else []
    for t in tokens:
        t = t.lstrip("+")
        for s in SCOPE_PRESETS.get(t, [t]):
            if s not in out:
                out.append(s)
    if supported:
        bad = [s for s in out if s not in supported]
        if bad:
            raise CliError(f"Unknown scope(s): {', '.join(bad)}. Valid: {', '.join(sorted(supported))}; "
                           f"presets: {', '.join(SCOPE_PRESETS)}.", EXIT_USAGE)
    return out


def get_client(meta: dict, reregister: bool = False) -> dict:
    reg = meta["registration_endpoint"]
    cache = _read_private(client_path()) or {}
    entry = cache.get(reg)
    if entry and not reregister and entry.get("client_id") and entry.get("redirect_uris"):
        return entry
    uris = [f"http://127.0.0.1:{p}/callback" for p in CALLBACK_PORTS]
    resp = http_request("POST", reg, body={
        "client_name": "ANKLE CLI", "redirect_uris": uris, "grant_types": ["authorization_code", "refresh_token"],
        "response_types": ["code"], "token_endpoint_auth_method": "none"})
    if resp.status not in (200, 201):
        raise http_error(resp, "Client registration failed: ")
    data = resp.json()
    if not isinstance(data, dict) or not data.get("client_id"):
        raise CliError("Client registration returned no client_id.")
    entry = {"client_id": data["client_id"], "redirect_uris": data.get("redirect_uris") or uris,
             "registered_at": int(time.time())}
    cache[reg] = entry
    _write_private(client_path(), cache)
    return entry


def _forget_client(meta: dict) -> None:
    cache = _read_private(client_path()) or {}
    if cache.pop(meta["registration_endpoint"], None) is not None:
        _write_private(client_path(), cache)


_DONE_PAGE = ("<!doctype html><meta charset=utf-8><title>ANKLE CLI</title>"
              "<body style=\"font:15px monospace;background:#e8e8e8;color:#000;padding:32px\">"
              "<b>ANKLE CLI</b><p>{msg}</p><p>You can close this tab and return to the terminal.</p></body>")


class _CallbackServer(http.server.HTTPServer):
    allow_reuse_address = False
    result = None
    expected_state = ""


class _CallbackHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):  # noqa: N802
        p = urlsplit(self.path)
        if p.path != "/callback":
            self.send_response(404)
            self.end_headers()
            return
        q = {k: v[0] for k, v in parse_qs(p.query).items()}
        good = q.get("state") == self.server.expected_state
        if good:
            self.server.result = q
        if good and q.get("code"):
            msg = "Signed in. The terminal is finishing up."
        elif good:
            msg = "Sign-in did not complete: " + str(q.get("error", "unknown error"))
        else:
            msg = "This sign-in link does not match the waiting terminal session. Start again with ankle login."
        body = _DONE_PAGE.format(msg=msg.replace("<", "&lt;")).encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass


def _bind_callback(redirect_uris: list):
    for uri in redirect_uris:
        p = urlsplit(uri)
        if p.hostname != "127.0.0.1" or not p.port:
            continue
        try:
            srv = _CallbackServer(("127.0.0.1", p.port), _CallbackHandler)
        except OSError:
            continue
        return srv, uri
    raise CliError(f"No free loopback port among {CALLBACK_PORTS[0]}-{CALLBACK_PORTS[-1]} for the sign-in callback. "
                   "Close the program using them, or set ANKLE_AGENT_KEY instead.")


def cmd_login(api: Api, args) -> int:
    origin = api.origin
    if os.environ.get("ANKLE_AGENT_KEY"):
        note("note: ANKLE_AGENT_KEY is set and takes precedence over this login until you unset it.")
    meta = discover(origin)
    scopes = resolve_scopes(args.scopes, meta.get("scopes_supported"))
    client = get_client(meta, reregister=args.reregister)
    srv = None
    if args.paste:
        redirect_uri = client["redirect_uris"][0]
    else:
        srv, redirect_uri = _bind_callback(client["redirect_uris"])
    verifier = _b64url(secrets.token_bytes(48))
    challenge = _b64url(hashlib.sha256(verifier.encode()).digest())
    state = secrets.token_urlsafe(24)
    params = {"response_type": "code", "client_id": client["client_id"], "redirect_uri": redirect_uri,
              "code_challenge": challenge, "code_challenge_method": "S256", "state": state,
              "resource": origin + "/api/mcp"}
    if scopes:
        params["scope"] = " ".join(scopes)
    url = meta["authorization_endpoint"] + "?" + urlencode(params)
    note("Sign in to ANKLE OS in your browser. If it does not open, visit:\n\n  " + url + "\n")
    try:
        if args.paste:
            note("After approving, your browser will fail to load a 127.0.0.1 page. Copy that page's full address")
            note("from the address bar and paste it here:")
            line = sys.stdin.readline().strip()
            q = {k: v[0] for k, v in parse_qs(urlsplit(line).query).items()}
            if q.get("state") != state:
                raise CliError("That address does not belong to this sign-in (state mismatch). Run login again.")
        else:
            if not args.no_browser:
                try:
                    webbrowser.open(url)
                except Exception:
                    pass
            note(f"Waiting for the browser on {redirect_uri} (Ctrl-C to cancel)...")
            srv.expected_state = state
            srv.timeout = 0.5
            deadline = time.time() + args.timeout
            while srv.result is None and time.time() < deadline:
                srv.handle_request()
            q = srv.result
            if q is None:
                raise CliError(f"Timed out after {args.timeout}s waiting for the browser sign-in.")
    except KeyboardInterrupt:
        raise CliError("Login cancelled.") from None
    finally:
        if srv:
            srv.server_close()
    if q.get("error"):
        desc = q.get("error_description") or ""
        raise CliError("Authorization not granted: " + q["error"] + (f" ({desc})" if desc else ""), EXIT_AUTH)
    if not q.get("code"):
        raise CliError("The browser returned no authorization code.", EXIT_AUTH)
    resp = http_request("POST", meta["token_endpoint"], form={
        "grant_type": "authorization_code", "code": q["code"], "redirect_uri": redirect_uri,
        "client_id": client["client_id"], "code_verifier": verifier})
    if resp.status == 401 and b"invalid_client" in resp.body:
        _forget_client(meta)
        raise CliError("The server no longer recognises this CLI's client registration; cache cleared. "
                       f"Run: {PROG} login", EXIT_AUTH, status=401)
    if resp.status != 200:
        raise http_error(resp, "Token exchange failed: ")
    tok = resp.json()
    access = tok.get("access_token") if isinstance(tok, dict) else None
    if not isinstance(access, str) or not _valid_token(access):
        raise CliError("Token exchange returned no usable access token.")
    creds = {"version": 1, "origin": origin, "issuer": meta.get("issuer"), "client_id": client["client_id"],
             "token_endpoint": meta["token_endpoint"], "revocation_endpoint": meta.get("revocation_endpoint"),
             "access_token": access, "refresh_token": tok.get("refresh_token"),
             "token_type": tok.get("token_type", "Bearer"), "scope": tok.get("scope", " ".join(scopes)),
             "created_at": int(time.time())}
    _write_private(creds_path(), creds)
    granted = creds["scope"].split()
    who = None
    if not os.environ.get("ANKLE_AGENT_KEY"):
        try:
            api.auth = Auth(origin)
            who = api.me()
        except CliError as exc:
            note(f"warning: signed in, but could not read your identity ({exc.message}).")
    owner = (who or {}).get("owner") or {}
    emit({"ok": True, "origin": origin, "username": owner.get("username"), "scopes": granted,
          "credentials_path": str(creds_path())},
         f"Signed in{' as @' + owner['username'] if owner.get('username') else ''} on {origin}.\n"
         f"Scopes: {' '.join(granted) or '(server default)'}\n"
         f"Credentials saved to {creds_path()} (0600).")
    return EXIT_OK


def cmd_logout(api: Api, args) -> int:
    creds = load_creds()
    env_note = ("ANKLE_AGENT_KEY is still set in your environment; logout does not touch it. "
                "Revoke that key at https://ankle.studio/developers if needed.") if os.environ.get("ANKLE_AGENT_KEY") else None
    if not creds:
        emit({"ok": True, "signed_in": False, "note": env_note}, "Not signed in (no stored credentials)." +
             ("\n" + env_note if env_note else ""))
        return EXIT_OK
    errors = []
    rev = creds.get("revocation_endpoint")
    if rev and _trusted_endpoint(rev, creds.get("origin") or api.origin):
        for hint, tok in (("refresh_token", creds.get("refresh_token")), ("access_token", creds.get("access_token"))):
            if not tok:
                continue
            try:
                resp = http_request("POST", rev, form={"token": tok, "token_type_hint": hint,
                                                       "client_id": creds.get("client_id", "")})
                if resp.status != 200:
                    errors.append(f"HTTP {resp.status}: {server_message(resp)}")
            except CliError as exc:
                errors.append(exc.message)
    else:
        errors.append("no revocation endpoint stored")
    try:
        creds_path().unlink()
    except FileNotFoundError:
        pass
    if errors:
        text = (f"Deleted {creds_path()}, but server revocation failed ({'; '.join(errors)}). "
                "Revoke the key at https://ankle.studio/developers.")
    else:
        text = f"Signed out. The CLI key was revoked on the server and {creds_path()} was deleted."
    if env_note:
        text += "\n" + env_note
    emit({"ok": not errors, "revoked": not errors, "errors": errors, "deleted": str(creds_path())}, text)
    return EXIT_ERR if errors else EXIT_OK


def cmd_whoami(api: Api, args) -> int:
    data = api.me()
    agent, owner = data.get("agent") or {}, data.get("owner") or {}
    source = "ANKLE_AGENT_KEY (environment)" if api.auth.source == "env" else f"login ({creds_path()})"
    if Out.json:
        emit({**data, "source": api.auth.source, "origin": api.origin})
        return EXIT_OK
    print(kv_block([("user", "@" + str(owner.get("username") or "")), ("user_id", owner.get("user_id")),
                    ("credits", owner.get("credits")), ("key", f"{agent.get('name')} ({agent.get('key_prefix')}...)"),
                    ("scopes", " ".join(agent.get("scopes") or [])), ("source", source), ("origin", api.origin)]))
    return EXIT_OK


# -- tools / call -------------------------------------------------------------------------

def _schema_types(prop: dict) -> set:
    types = set()
    for p in [prop] + list(prop.get("anyOf") or []) + list(prop.get("oneOf") or []):
        t = p.get("type")
        if isinstance(t, list):
            types.update(t)
        elif t:
            types.add(t)
        if p.get("items") is not None or p.get("$ref"):
            types.add("array" if p.get("items") is not None else "object")
    return types


def _coerce(key: str, value: str, prop: dict):
    types = _schema_types(prop or {})
    if not types or "string" in types:
        return value
    try:
        if "integer" in types:
            return int(value)
        if "number" in types:
            return float(value) if any(c in value for c in ".eE") else int(value)
        if "boolean" in types:
            low = value.lower()
            if low in {"true", "1", "yes", "on"}:
                return True
            if low in {"false", "0", "no", "off"}:
                return False
            raise ValueError
        if types & {"array", "object", "null"}:
            return json.loads(value)
    except ValueError:
        raise CliError(f"{key}: '{value}' is not a valid {'/'.join(sorted(types))}.", EXIT_USAGE) from None
    return value


def _read_file_arg(key: str, path: str) -> str:
    p = Path(path).expanduser()
    try:
        if p.stat().st_size > MAX_FILE_ARG:
            raise CliError(f"{key}: {path} exceeds 5 MiB.", EXIT_USAGE)
        return p.read_text(encoding="utf-8")
    except OSError as exc:
        raise CliError(f"{key}: cannot read {path}: {exc.strerror}", EXIT_USAGE) from None


def parse_arguments(pairs: list, schema: dict | None, base: str | None) -> dict:
    out = {}
    if base:
        try:
            out = json.loads(base)
        except ValueError as exc:
            raise CliError(f"--args is not valid JSON: {exc}", EXIT_USAGE) from None
        if not isinstance(out, dict):
            raise CliError("--args must be a JSON object.", EXIT_USAGE)
    props = (schema or {}).get("properties") or {}
    for pair in pairs:
        m = re.match(r"^([A-Za-z_][A-Za-z0-9_.-]*)(:=|=)(.*)$", pair, re.S)
        if not m:
            raise CliError(f"Argument '{pair}' must look like key=value, key:=<json> or key=@file.", EXIT_USAGE)
        key, op, value = m.groups()
        if op == ":=":
            try:
                out[key] = json.loads(value)
            except ValueError:
                raise CliError(f"{key}:= expects JSON, got: {value}", EXIT_USAGE) from None
        elif value.startswith("@") and len(value) > 1:
            out[key] = _read_file_arg(key, value[1:])
        else:
            out[key] = _coerce(key, value, props.get(key) or {})
    return out


def _args_summary(schema: dict) -> str:
    props = (schema or {}).get("properties") or {}
    req = set((schema or {}).get("required") or [])
    return ", ".join(k if k in req else k + "?" for k in props) or "-"


def _mode(tool: dict) -> str:
    a = tool.get("annotations") or {}
    if a.get("destructiveHint"):
        return "destructive"
    return "read" if a.get("readOnlyHint") else "write"


def cmd_tools(api: Api, args) -> int:
    tools = api.tools()
    if Out.json:
        emit({"tools": tools})
        return EXIT_OK
    if not tools:
        print("This key can see no tools. Check its scopes with: " + PROG + " whoami")
        return EXIT_OK
    rows = [(t.get("name"), _mode(t), _args_summary(t.get("inputSchema")), t.get("title") or "") for t in tools]
    print(table(["TOOL", "MODE", "ARGS (? = optional)", "TITLE"], rows, [32, 12, 60, 0]))
    print(f"\n{len(tools)} tools. Call one: {PROG} call <tool> key=value ...")
    return EXIT_OK


def cmd_call(api: Api, args) -> int:
    name = args.tool.replace(".", "_")
    schema = None
    if not api.dry_run:
        tool = api.tool(name)
        if tool:
            schema = tool.get("inputSchema")
    arguments = parse_arguments(args.pairs, schema, args.args)
    value = api.call(name, arguments)
    emit(value, json.dumps(value, indent=2, ensure_ascii=False))
    return EXIT_OK


# -- friendly verbs -------------------------------------------------------------------------

def cmd_worlds(api: Api, args) -> int:
    value = api.call("worlds_list", {})
    worlds = value.get("worlds") or []
    if Out.json:
        emit(value)
        return EXIT_OK
    if not worlds:
        print(f"No Worlds yet. Found one: {PROG} call worlds_found word=<word> idempotency_key=<unique-id>")
        return EXIT_OK
    rows = [(w.get("word"), "founder" if w.get("founder") else "contributor", w.get("name"), w.get("url")) for w in worlds]
    print(table(["WORD", "ROLE", "NAME", "URL"], rows, [41, 12, 32, 0]))
    return EXIT_OK


def cmd_surf(api: Api, args, query: str, legacy: bool = False) -> int:
    if not query.strip():
        raise CliError(f"Usage: {PROG} surf <query>", EXIT_USAGE)
    limit = max(1, min(50, args.limit))
    if legacy:
        emit(api.act("surf.search", {"query": query, "limit": limit}))
        return EXIT_OK
    value = api.call("surf_search", {"query": query, "limit": limit})
    items = value.get("items") or []
    if Out.json:
        emit(value)
        return EXIT_OK
    if not items:
        print(f"No SURF results for '{query}'.")
        return EXIT_OK
    rows = [(i + 1, it.get("name") or (it.get("meta") or {}).get("title"), it.get("ext") or it.get("mime"),
             it.get("layer"), it.get("url")) for i, it in enumerate(items)]
    print(table(["#", "NAME", "TYPE", "LAYER", "URL"], rows, [4, 40, 8, 12, 0]))
    print("\nSearch results do not verify availability or rights. Use the url field exactly.")
    return EXIT_OK


def cmd_pages(api: Api, args) -> int:
    value = api.call("builder_list", {"limit": max(1, min(100, args.limit)), "after_id": max(0, args.after)})
    pages = value.get("pages") or []
    if Out.json:
        emit(value)
        return EXIT_OK
    if not pages:
        print("No pages yet.")
        return EXIT_OK
    rows = [(p.get("page_id"), p.get("draft_revision"), p.get("visibility"), p.get("is_published"),
             p.get("word"), p.get("title")) for p in pages]
    print(table(["ID", "REV", "VISIBILITY", "LIVE", "WORLD", "TITLE"], rows, [10, 6, 10, 4, 24, 0]))
    if value.get("next_after_id"):
        print(f"\nMore: {PROG} pages --after {value['next_after_id']}")
    return EXIT_OK


def _page_id(raw: str) -> int:
    try:
        pid = int(raw)
    except (TypeError, ValueError):
        raise CliError(f"Page id must be a positive integer, got '{raw}'.", EXIT_USAGE) from None
    if pid < 1:
        raise CliError("Page id must be a positive integer.", EXIT_USAGE)
    return pid


def cmd_page(api: Api, args, page_id: int) -> int:
    value = api.call("builder_get", {"page_id": page_id})
    html = value.get("raw_html") or ""
    if args.output:
        Path(args.output).expanduser().write_text(html, encoding="utf-8")
    if Out.json:
        emit(value)
        return EXIT_OK
    if args.html:
        sys.stdout.write(html if html.endswith("\n") or not html else html + "\n")
        return EXIT_OK
    world = value.get("word_community") or ""
    editor = f"https://ankle.studio/builder?page={value.get('id')}&world={world}" if api.origin in FIRST_PARTY else None
    pairs = [("id", value.get("id")), ("title", value.get("title")), ("slug", value.get("slug")), ("world", world),
             ("visibility", value.get("visibility")), ("published", value.get("is_published")),
             ("revision", value.get("draft_revision")), ("html", f"{len(html.encode('utf-8'))} bytes")]
    if editor:
        pairs.append(("editor", editor))
    if args.output:
        pairs.append(("saved", args.output))
    print(kv_block(pairs))
    if not args.output:
        print(f"\nPrint the HTML: {PROG} page {value.get('id')} --html")
    return EXIT_OK


def cmd_build(api: Api, args) -> int:
    prompt = " ".join(args.prompt).strip()
    if not prompt:
        raise CliError(f"Usage: {PROG} build <prompt>", EXIT_USAGE)
    payload = {"prompt": prompt}
    if args.page:
        payload["page_id"] = args.page
    note("Generating with ANKLE's page builder (may take up to a minute; may use credits)...")
    data = api.act("pages.generate", payload)
    res = data.get("result") or {}
    created = None
    html = res.get("html") or ""
    if args.output and html:
        Path(args.output).expanduser().write_text(html, encoding="utf-8")
    if args.save and html:
        key = "cli-build-" + hashlib.sha256((prompt + html).encode("utf-8")).hexdigest()[:24]
        create = {"title": (args.title or prompt)[:120], "raw_html": html, "idempotency_key": key}
        if args.world:
            create["word"] = args.world.lower()
        created = api.call("builder_create", create)
    if Out.json:
        emit({**data, "created": created} if created else data)
        return EXIT_OK
    receipt = f"{res.get('bytes')} bytes via {res.get('provider')}/{res.get('model')}"
    if res.get("mode") == "saved":
        print(f"Saved to page {res.get('page_id')} ({receipt}).")
        return EXIT_OK
    if created:
        print(kv_block([("generated", receipt), ("page_id", created.get("page_id")), ("visibility", created.get("visibility")),
                        ("editor", created.get("editor_url")), ("replayed", created.get("replayed"))]))
        return EXIT_OK
    if args.output:
        print(f"Generated {receipt}. Preview written to {args.output} (not saved to your account; add --save).")
    else:
        note(f"Generated {receipt}. Preview only, not saved (use -o FILE or --save).")
        sys.stdout.write(html if html.endswith("\n") else html + "\n")
    return EXIT_OK


def cmd_credits(api: Api, args) -> int:
    try:
        res = (api.act("credits.balance", {}) or {}).get("result") or {}
        credits, user = res.get("credits"), res.get("username")
    except CliError as exc:
        if exc.status != 403:
            raise
        owner = (api.me() or {}).get("owner") or {}  # /me reports credits without the scope
        credits, user = owner.get("credits"), owner.get("username")
    emit({"credits": credits, "username": user}, kv_block([("credits", credits), ("user", "@" + str(user or ""))]))
    return EXIT_OK


def _format_settings_kv(data: dict) -> str:
    raw_notif = data.get("notifications")
    notif: dict = raw_notif if isinstance(raw_notif, dict) else {}
    pairs = [
        ("user", "@" + str(data.get("username") or "")),
        ("user_id", data.get("user_id")),
        ("theme", data.get("theme")),
        ("locale", data.get("locale")),
        ("color_mode", data.get("color_mode")),
        ("site_theme_takeover", data.get("site_theme_takeover")),
        ("display_name", data.get("display_name")),
        ("bio", data.get("bio")),
        ("avatar_url", data.get("avatar_url")),
        ("telegram_notifications", notif.get("telegram_notifications", data.get("telegram_notifications"))),
        ("sms_notifications", notif.get("sms_notifications", data.get("sms_notifications"))),
        ("in_app_notifications", notif.get("in_app_notifications", data.get("in_app_notifications"))),
        ("email_notifications", notif.get("email_notifications", data.get("email_notifications"))),
    ]
    if data.get("updated_fields") is not None:
        pairs.insert(0, ("updated_fields", ", ".join(data.get("updated_fields") or []) or "none"))
    return kv_block(pairs)


def cmd_settings(api: Api, args) -> int:
    rest = list(getattr(args, "rest", None) or [])
    sub = "get"
    pairs: list[str] = []
    if rest:
        if rest[0] in {"get", "read", "show"}:
            sub = "get"
            pairs = rest[1:]
        elif rest[0] in {"set", "update"}:
            sub = "set"
            pairs = rest[1:]
        elif "=" in rest[0]:
            sub = "set"
            pairs = rest
        else:
            raise CliError(f"Usage: {PROG} settings [get | set [key=value ...] [--theme SLUG] [--locale CODE] ...]", EXIT_USAGE)

    flag_updates = {}
    for attr, field in (
        ("theme", "theme"),
        ("locale", "locale"),
        ("color_mode", "color_mode"),
        ("site_theme_takeover", "site_theme_takeover"),
        ("display_name", "display_name"),
        ("bio", "bio"),
        ("avatar_url", "avatar_url"),
        ("telegram_notifications", "telegram_notifications"),
        ("sms_notifications", "sms_notifications"),
        ("in_app_notifications", "in_app_notifications"),
        ("email_notifications", "email_notifications"),
    ):
        val = getattr(args, attr, None)
        if val is not None:
            if (field.endswith("_notifications") or field == "site_theme_takeover") and isinstance(val, str):
                low = val.strip().lower()
                if low in {"true", "1", "yes", "on"}:
                    val = True
                elif low in {"false", "0", "no", "off"}:
                    val = False
                else:
                    raise CliError(f"--{attr.replace('_', '-')} must be true or false.", EXIT_USAGE)
            flag_updates[field] = val

    if flag_updates:
        sub = "set"

    if sub == "get":
        if pairs:
            raise CliError(f"Unexpected arguments for settings get: {' '.join(pairs)}", EXIT_USAGE)
        url = api.origin + "/api/agent-bridge/settings"
        if api.dry_run:
            api._dry("GET", url, None)
        resp = api.authed("GET", url)
        if resp.status != 200:
            raise http_error(resp)
        data = resp.json()
        emit(data, _format_settings_kv(data))
        return EXIT_OK

    schema = {
        "properties": {
            "theme": {"type": "string"},
            "locale": {"type": "string"},
            "color_mode": {"type": "string"},
            "site_theme_takeover": {"type": "boolean"},
            "display_name": {"type": "string"},
            "bio": {"type": "string"},
            "avatar_url": {"type": "string"},
            "telegram_notifications": {"type": "boolean"},
            "sms_notifications": {"type": "boolean"},
            "in_app_notifications": {"type": "boolean"},
            "email_notifications": {"type": "boolean"},
            "notifications": {"type": "object"},
        }
    }
    payload = parse_arguments(pairs, schema, getattr(args, "args", None))
    payload.update(flag_updates)
    if not payload:
        raise CliError(
            f"Usage: {PROG} settings set [--theme SLUG] [--locale CODE] [--color-mode MODE] "
            "[--display-name NAME] [--bio TEXT] [--avatar-url URL] [key=value ...]",
            EXIT_USAGE,
        )
    url = api.origin + "/api/agent-bridge/settings"
    if api.dry_run:
        api._dry("PATCH", url, payload)
    resp = api.authed("PATCH", url, body=payload)
    if resp.status != 200:
        raise http_error(resp)
    data = resp.json()
    emit(data, _format_settings_kv(data))
    return EXIT_OK


def _world_request(api: Api, method: str, word: str, path: str, body=None, use_auth: bool = False):
    base = world_origin(word)
    url = base + path
    token = None
    if use_auth:
        api.auth.require()
        token = api.auth.token
    if api.dry_run:
        api._dry(method, url, body)
    resp = http_request(method, url, body=body, token=token, timeout=120)
    if resp.status in (404, 405, 410) or (resp.status == 200 and not resp.is_json()):
        said = server_message(resp) if resp.status != 200 else "non-JSON page"
        raise CliError(f"This world has no agent yet ({word}: HTTP {resp.status} from {url}; server said: {said}).",
                       EXIT_NOTFOUND, status=resp.status)
    if resp.status != 200:
        raise http_error(resp, f"{word}: ")
    return resp.json(), url


def cmd_world(api: Api, args, word: str) -> int:
    data, url = _world_request(api, "GET", word, "/api/agent", use_auth=args.auth)
    if Out.json or not isinstance(data, dict):
        emit(data)
        return EXIT_OK
    agent = data.get("agent") if isinstance(data.get("agent"), dict) else data
    pairs = [("world", agent.get("word") or word)]
    for key in ("name", "title", "description", "greeting", "persona", "model", "status", "url", "ask_url"):
        if agent.get(key) not in (None, "", [], {}):
            pairs.append((key, agent[key]))
    for key in ("tools", "skills", "capabilities", "topics"):
        vals = agent.get(key)
        if isinstance(vals, list) and vals:
            pairs.append((key, ", ".join(v.get("name", json.dumps(v)) if isinstance(v, dict) else str(v) for v in vals)))
    print(kv_block(pairs))
    print(f"\nAsk it: {PROG} ask {word} \"your question\"")
    return EXIT_OK


def cmd_ask(api: Api, args, word: str) -> int:
    question = " ".join(args.question).strip()
    if not question:
        raise CliError(f"Usage: {PROG} ask <word> \"question\"", EXIT_USAGE)
    data, _ = _world_request(api, "POST", word, "/api/agent/ask", body={"question": question}, use_auth=args.auth)
    if Out.json or not isinstance(data, dict):
        emit(data)
        return EXIT_OK
    answer = next((data[k] for k in ("answer", "reply", "text", "message", "content") if isinstance(data.get(k), str)), None)
    print(answer if answer is not None else json.dumps(data, indent=2, ensure_ascii=False))
    sources = data.get("sources") or data.get("citations")
    if isinstance(sources, list) and sources:
        print("\nSources:")
        for s in sources[:10]:
            print("  " + (s.get("url") or s.get("title") or json.dumps(s) if isinstance(s, dict) else str(s)))
    return EXIT_OK


def cmd_talk(api: Api, args, agent: str) -> int:
    msg = " ".join(args.message).strip()
    if not msg:
        raise CliError(f"Usage: {PROG} talk <agent> \"message\"", EXIT_USAGE)
    try:
        res = api.call("agent_talk", {"agent": agent, "message": msg})
    except Exception:
        resp = api.authed("POST", f"{api.origin}/api/agents/{agent}/talk", body={"message": msg})
        res = resp.json()
    if Out.json or not isinstance(res, dict):
        emit(res)
        return EXIT_OK
    if not res.get("ok"):
        err = res.get("detail") or res.get("error") or "Talk failed"
        raise CliError(str(err), EXIT_ERR)
    reply = res.get("reply") or ""
    name = res.get("agent_name") or agent
    print(f"[{name}] {reply}")
    cits = res.get("citations")
    if isinstance(cits, list) and cits:
        print("\nCitations:")
        for c in cits:
            print(f"  [{c}]")
    return EXIT_OK


def cmd_brief(api: Api, args, agent: str) -> int:
    try:
        res = api.call("agent_brief", {"agent": agent})
    except Exception:
        resp = api.authed("GET", f"{api.origin}/api/agents/{agent}/brief")
        res = resp.json()
    if Out.json or not isinstance(res, dict):
        emit(res)
        return EXIT_OK
    name = res.get("agent_name") or agent
    raw_hw = res.get("home_world")
    hw = raw_hw if isinstance(raw_hw, dict) else {}
    raw_kd = res.get("knowledge_digest")
    kd = raw_kd if isinstance(raw_kd, dict) else {}
    print(f"Agent: {name} (slug: {agent})")
    print(f"Home World: {hw.get('word')} ({'unclaimed' if hw.get('unclaimed_home') else 'founded'})")
    if hw.get("reason"):
        print(f"Origin: {hw.get('reason')}")
    print(f"\nKnowledge Digest:\n{kd.get('summary', 'No summary.')}")
    cits = kd.get("citations")
    if isinstance(cits, list) and cits:
        print("\nCitations:")
        for c in cits:
            print(f"  [{c}]")
    ps = res.get("private_state")
    if isinstance(ps, dict):
        print(f"\nPrivate Rolodex ({ps.get('contacts_count', 0)} contacts, {ps.get('memory_count', 0)} memories):")
        for ct in (ps.get("contacts") or [])[:5]:
            if isinstance(ct, dict):
                print(f"  {ct.get('handle')}: {ct.get('note') or 'contact'}")
    vs = res.get("visitor_state")
    if isinstance(vs, dict):
        print(f"\nNotice: {vs.get('notice')}")
    return EXIT_OK


# -- legacy (v0 ankle.py / hermes-skill-ankle) compatibility -----------------------------------

def _read_json_file(path: str):
    raw = Path(path).expanduser().read_bytes()
    if len(raw) > MAX_REQUEST:
        raise CliError("Input exceeds 6 MiB.", EXIT_USAGE)
    try:
        return json.loads(raw)
    except ValueError as exc:
        raise CliError(f"{path} is not valid JSON: {exc}", EXIT_USAGE) from None


def _need(args, *names):
    missing = [n for n in names if not getattr(args, n.replace("-", "_"), None)]
    if missing:
        raise CliError("Missing " + ", ".join("--" + n for n in missing), EXIT_USAGE)


def cmd_discover(api: Api, args) -> int:
    url = api.origin + "/api/manifest.json"
    if api.dry_run:
        api._dry("GET", url, None)
    resp = http_request("GET", url)
    if resp.status != 200:
        raise http_error(resp)
    emit(resp.json())
    return EXIT_OK


def cmd_status(api: Api, args) -> int:
    if api.dry_run:
        api._dry("GET", "https://aleqth.com/api/status", None)
    st_resp = http_request("GET", "https://aleqth.com/api/status", timeout=8)
    st = st_resp.json() if st_resp.status == 200 and st_resp.is_json() else {}
    ankl_resp = http_request("GET", "https://aleqth.com/api/ankl/price", timeout=8)
    ankl = ankl_resp.json() if ankl_resp.status == 200 and ankl_resp.is_json() else {}
    local_nodes = {}
    for name, u in (("ankle_app", "http://127.0.0.1:18484/health"),
                    ("execution_desk", "http://127.0.0.1:8098/api/status"),
                    ("trace_desk", "http://127.0.0.1:6007/api/overview")):
        try:
            r = http_request("GET", u, timeout=1.2)
            local_nodes[name] = "online" if r.status == 200 else f"http_{r.status}"
        except Exception:
            local_nodes[name] = "offline"
    owner_info = {}
    if api.auth.token:
        try:
            me = api.me()
            owner_info = (me or {}).get("owner") or {}
        except Exception:
            pass
    payload = {
        "ok": True,
        "origin": api.origin,
        "account": owner_info.get("username") or owner_info.get("user_id") or ("signed_in" if api.auth.token else "anonymous"),
        "credits": owner_info.get("credits"),
        "archive_images": ((st.get("archive") or {}).get("images")),
        "community_users": ((st.get("community") or {}).get("users")),
        "feed_posts": ((st.get("community") or {}).get("feed_posts")),
        "ankl_index_level": ((ankl.get("index") or {}).get("level")),
        "ankl_constituents": ((ankl.get("index") or {}).get("listed")),
        "local_nodes": local_nodes,
    }
    if Out.json:
        emit(payload)
        return EXIT_OK
    rows = [
        ("Origin", payload["origin"]),
        ("Account", "@" + str(payload["account"]) if payload["account"] not in ("anonymous", "signed_in") else payload["account"]),
        ("Credits", payload["credits"] if payload["credits"] is not None else "-"),
        ("SURF Archive", f"{payload['archive_images']:,} images" if isinstance(payload["archive_images"], int) else "-"),
        ("Community", f"{payload['community_users']} members / {payload['feed_posts']} posts" if payload["community_users"] else "-"),
        ("$ANKL Index", f"{payload['ankl_index_level']} ({payload['ankl_constituents']} coins)" if payload["ankl_index_level"] else "-"),
        ("ANKLE.app (:18484)", local_nodes["ankle_app"]),
        ("Execution Desk (:8098)", local_nodes["execution_desk"]),
        ("Trace Desk (:6007)", local_nodes["trace_desk"]),
    ]
    emit(payload, "ANKLE OS // SYSTEM STATUS\n" + kv_block(rows))
    return EXIT_OK


def cmd_ankl(api: Api, args) -> int:
    url = "https://aleqth.com/api/ankl/price"
    if api.dry_run:
        api._dry("GET", url, None)
    resp = http_request("GET", url, timeout=10)
    if resp.status != 200:
        raise http_error(resp)
    d = resp.json()
    if Out.json:
        emit(d)
        return EXIT_OK
    idx = d.get("index") or {}
    mkt = d.get("market") or {}
    burn = d.get("burn") or {}
    posture = d.get("posture") or {}
    idx_level = idx.get("level")
    idx_kind = idx.get("level_kind")
    idx_str = f"{idx_level} ({idx_kind})" if idx_level is not None and idx_kind else (str(idx_level) if idx_level is not None else "not set")
    idx_listed = idx.get("listed")
    const_str = f"{idx_listed} verified culture/community coins" if idx_listed is not None else "not set"
    burn_destroyed = burn.get("total_destroyed")
    burn_events = burn.get("events")
    if burn_destroyed is not None:
        burn_str = f"{burn_destroyed} ANKL destroyed" + (f" across {burn_events} events" if burn_events is not None else "")
    else:
        burn_str = "not set"
    rows = [
        ("Mint", mkt.get("mint") or "not set"),
        ("Streamflow Lock", d.get("streamflow_lock") or mkt.get("streamflow_lock") or "not set"),
        ("Index Level", idx_str),
        ("Constituents", const_str),
        ("Market Priced", f"priced={mkt.get('priced')} price_usd={mkt.get('price_usd')} fdv_usd={mkt.get('fdv_usd')}"),
        ("Burn Ledger", burn_str),
        ("Buyback Execution", "not set" if posture.get("buyback_execution") is None else f"enabled={bool(posture.get('buyback_execution'))}"),
        ("Surfaces", "https://aleqth.com/ankl  https://aleqth.com/index  https://aleqth.com/reciprocity"),
    ]
    emit(d, "ANKLE OS // $ANKL RESERVE ORACLE\n" + kv_block(rows))
    return EXIT_OK


def cmd_index(api: Api, args) -> int:
    url = "https://aleqth.com/api/ankl/index"
    if api.dry_run:
        api._dry("GET", url, None)
    resp = http_request("GET", url, timeout=10)
    if resp.status != 200:
        raise http_error(resp)
    d = resp.json()
    if Out.json:
        emit(d)
        return EXIT_OK
    items = d.get("constituents") or d.get("items") or []
    limit = max(1, min(100, int(getattr(args, "limit", 15) or 15)))
    rows = []
    for c in items[:limit]:
        rows.append([
            c.get("rank") or "-",
            c.get("symbol") or c.get("word") or "-",
            c.get("name") or c.get("word") or "-",
            c.get("weight_bps") or c.get("weight") or "-",
            c.get("world_url") or (f"https://{c['word']}.ankle.website" if c.get("word") else "-"),
        ])
    level = d.get("level")
    level_str = str(level) if level is not None and level != "" else "not set"
    hdr = f"ANKLE CULTURAL INDEX — Level {level_str} ({len(items)} constituents)\n"
    emit(d, hdr + (table(["RANK", "SYMBOL", "NAME", "WEIGHT", "WORLD"], rows, [6, 12, 24, 10, None]) if rows else "No constituents returned."))
    return EXIT_OK


def cmd_reciprocity(api: Api, args) -> int:
    url = "https://aleqth.com/api/reciprocity/protocol"
    if api.dry_run:
        api._dry("GET", url, None)
    resp = http_request("GET", url, timeout=10)
    if resp.status != 200:
        raise http_error(resp)
    d = resp.json()
    if Out.json:
        emit(d)
        return EXIT_OK
    burn = d.get("burn") or {}
    exec_enabled = d.get("execution_enabled")
    rows = [
        ("Schema", d.get("schema") or "not set"),
        ("Mode", d.get("mode") or "not set"),
        ("Execution Enabled", "not set" if exec_enabled is None else f"enabled={bool(exec_enabled)}"),
        ("Reserve Share", d.get("reserve_share") or "not set"),
        ("Treasury Wallet", d.get("treasury") or d.get("treasury_wallet") or "not set"),
        ("$ANKL Mint", d.get("mint") or "not set"),
        ("Burn Disposition", f"enabled={bool(burn.get('enabled', False))}" if "enabled" in burn else "not set"),
        ("Surface", ((d.get("entrypoints") or {}).get("economy")) or "https://aleqth.com/reciprocity"),
    ]
    emit(d, "ANKLE OS // RECIPROCITY SETTLEMENT RAIL\n" + kv_block(rows))
    return EXIT_OK


def cmd_dada(api: Api, args) -> int:
    q = " ".join(getattr(args, "query", None) or []).strip()
    limit = max(1, min(50, int(getattr(args, "limit", 12) or 12)))
    if q:
        url = f"https://ankle.website/api/search?q={urlencode({'q': q})[2:]}&limit={limit}"
    else:
        url = f"https://ankle.website/api/search?q=dada&limit={limit}"
    if api.dry_run:
        api._dry("GET", url, None)
    resp = http_request("GET", url, timeout=10)
    if resp.status != 200:
        raise http_error(resp)
    d = resp.json()
    dada_items = d.get("dada") or d.get("results") or []
    if Out.json:
        emit({"ok": True, "query": q, "dada": dada_items})
        return EXIT_OK
    rows = []
    for item in dada_items[:limit]:
        rows.append([
            item.get("id") or "-",
            item.get("L0") or item.get("title") or "-",
            item.get("L1") or item.get("summary") or "-",
            item.get("author") or "-",
            f"https://ankle.website/dada/{item['id']}" if item.get("id") else (item.get("url") or "https://ankle.website/dada"),
        ])
    emit({"ok": True, "dada": dada_items},
         table(["ID", "L0 WORLD", "L1 SUBJECT", "AUTHOR", "URL"], rows, [8, 26, 26, 14, None]) if rows else "No DADA objects matched.")
    return EXIT_OK


def _send_terminal_agent_turn(api: Api, message: str) -> str:
    # Prefer local ANKLE.app (:18484) when running so terminal & desktop share session state
    try:
        r = http_request(
            "POST",
            "http://127.0.0.1:18484/local/agent/turn",
            body={"message": message, "build": {"kind": "house", "model": "gemini-4-argon", "provider": "gemini"}},
            timeout=35,
        )
        if r.status == 200 and r.is_json():
            d = r.json()
            reply = (d.get("response") or d.get("reply") or "").strip()
            if reply:
                return reply
    except Exception:
        pass
    # Cloud Paired Agent fallback
    resp = api.authed("POST", "https://aleqth.com/api/paired-agent/chat", body={"message": message, "context": ["surface:ankle-cli"]})
    if resp.status == 200 and resp.is_json():
        d = resp.json()
        reply = (d.get("response") or d.get("reply") or "").strip()
        if "No successful save was recorded in this reply" in reply:
            for rec in (d.get("tool_receipts") or []):
                if rec.get("ok") and rec.get("tool") == "builder_list":
                    pages = (rec.get("result") or {}).get("pages") or []
                    if pages:
                        return "Saved pages:\n" + "\n".join(
                            f"  - {p.get('title', 'Untitled')} (id: {p.get('id')}, world: {p.get('word_community') or '-'})"
                            for p in pages[:25]
                        )
        if reply:
            return reply
    raise http_error(resp)


def cmd_chat(api: Api, args) -> int:
    msg_parts = getattr(args, "message", None) or []
    message = " ".join(msg_parts).strip()
    if api.dry_run:
        api._dry("POST", "https://aleqth.com/api/paired-agent/chat", {"message": message or "hello"})
    if message:
        reply = _send_terminal_agent_turn(api, message)
        if Out.json:
            emit({"ok": True, "model": "gemini-4-argon", "response": reply})
        else:
            print(reply)
        return EXIT_OK
    # Interactive ANKLE OS Terminal Shell (REPL)
    print("ANKLE OS // TERMINAL SHELL (@COMMAND · gemini-4-argon)")
    print("Type a message, or /worlds, /surf <q>, /pages, /ankl, /index, /status, /quit")
    while True:
        try:
            line = input("@COMMAND> ").strip()
        except (EOFError, KeyboardInterrupt):
            print()
            break
        if not line:
            continue
        if line in {"/quit", "/exit", "exit", "quit"}:
            break
        if line == "/help":
            print("Commands: /worlds, /surf <q>, /pages, /build <prompt>, /dada [q], /ankl, /index, /reciprocity, /status, /quit")
            continue
        if line == "/worlds":
            cmd_worlds(api, args)
            continue
        if line == "/pages":
            setattr(args, "limit", 20)
            setattr(args, "after", 0)
            cmd_pages(api, args)
            continue
        if line == "/ankl":
            cmd_ankl(api, args)
            continue
        if line == "/index":
            setattr(args, "limit", 15)
            cmd_index(api, args)
            continue
        if line == "/reciprocity":
            cmd_reciprocity(api, args)
            continue
        if line == "/status":
            cmd_status(api, args)
            continue
        if line.startswith("/surf "):
            setattr(args, "limit", 10)
            cmd_surf(api, args, line[6:].strip())
            continue
        try:
            print(_send_terminal_agent_turn(api, line))
        except CliError as exc:
            note("error: " + exc.message)
    return EXIT_OK


def cmd_act(api: Api, args) -> int:
    emit(api.act(args.action, _read_json_file(args.payload_file)))
    return EXIT_OK


def legacy_world(api: Api, args, rest: list) -> int:
    Out.json = True
    if rest[0] == "list":
        emit(api.act("worlds.list", {}))
    else:
        if len(rest) < 2:
            raise CliError(f"Usage: {PROG} world create <word> --request-id ID", EXIT_USAGE)
        _need(args, "request-id")
        emit(api.act("worlds.found", {"word": rest[1], "idempotency_key": args.request_id}))
    return EXIT_OK


def legacy_page(api: Api, args, rest: list) -> int:
    Out.json = True
    op = rest[0]
    if op == "list":
        emit(api.act("builder.list", {}))
        return EXIT_OK
    if op == "create":
        if len(rest) < 2:
            raise CliError(f"Usage: {PROG} page create <html_file> --world W --title T --request-id ID", EXIT_USAGE)
        _need(args, "world", "title", "request-id")
        html = _read_file_arg("html_file", rest[1])
        emit(api.act("builder.create", {"raw_html": html, "word": args.world, "title": args.title,
                                        "idempotency_key": args.request_id}))
        return EXIT_OK
    if len(rest) < 2:
        raise CliError(f"Usage: {PROG} page {op} <page_id> ...", EXIT_USAGE)
    payload = {"page_id": _page_id(rest[1])}
    if op != "get":
        _need(args, "revision", "request-id")
        payload.update(expected_revision=args.revision, idempotency_key=args.request_id)
        if op == "patch":
            if len(rest) < 3:
                raise CliError(f"Usage: {PROG} page patch <page_id> <patch.json> --revision N --request-id ID", EXIT_USAGE)
            payload["patch_ops"] = _read_json_file(rest[2])
        if op == "attach":
            _need(args, "world")
            payload["word"] = args.world
    emit(api.act("builder." + op, payload))
    return EXIT_OK


def cmd_mcp(api: Api, _args) -> int:
    """Stdio-to-Streamable-HTTP MCP bridge using ~/.config/ankle/credentials.json (with auto-refresh) or ANKLE_AGENT_KEY."""
    version = MCP_PROTOCOL
    url = api.origin + "/api/mcp"
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        req_id = None
        try:
            message = json.loads(line)
            req_id = message.get("id")
            raw = json.dumps(message).encode("utf-8")
            if len(raw) > MAX_REQUEST:
                raise CliError("MCP request exceeds 6 MiB.")
            resp = api.authed("POST", url, body=message, headers={
                "Accept": "application/json, text/event-stream",
                "MCP-Protocol-Version": version,
            })
            if resp.status in (202, 204) or not resp.body:
                continue
            if resp.status != 200:
                raise http_error(resp)
            result = resp.json()
            if message.get("method") == "initialize" and isinstance(result, dict):
                version = (result.get("result") or {}).get("protocolVersion") or version
            print(json.dumps(result, ensure_ascii=False), flush=True)
        except Exception as exc:
            reason = exc.message if isinstance(exc, CliError) else "MCP connection or configuration error."
            if req_id is not None:
                print(json.dumps({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32000, "message": reason}}), flush=True)
            else:
                note(reason)
    return EXIT_OK


def _atomic_write_bytes(path: Path, payload: bytes, *, write_backup: bool = True, existing_bytes: bytes | None = None) -> Path | None:
    """Write payload to path via atomic sibling .tmp + os.replace, writing path.bak first when path exists."""
    path.parent.mkdir(parents=True, exist_ok=True)
    existed = path.is_file()
    mode = 0o600
    if existed:
        try:
            mode = (path.stat().st_mode & 0o777) or 0o600
        except OSError:
            mode = 0o600
        if existing_bytes is None:
            existing_bytes = path.read_bytes()

    bak_path: Path | None = None
    if existed and write_backup and existing_bytes is not None:
        bak_path = path.with_name(path.name + ".bak")
        bak_tmp = path.with_name(f".{bak_path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp")
        bak_fd = os.open(str(bak_tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
        try:
            with os.fdopen(bak_fd, "wb") as bfh:
                bfh.write(existing_bytes)
                bfh.flush()
                os.fsync(bfh.fileno())
            os.chmod(bak_tmp, mode)
            os.replace(bak_tmp, bak_path)
        finally:
            if bak_tmp.exists():
                bak_tmp.unlink()

    tmp = path.with_name(f".{path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp")
    fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
    try:
        with os.fdopen(fd, "wb") as fh:
            fh.write(payload)
            fh.flush()
            os.fsync(fh.fileno())
        os.chmod(tmp, mode)
        os.replace(tmp, path)
    finally:
        if tmp.exists():
            tmp.unlink()
    return bak_path


def _register_json_mcp_server(
    cfg_path: Path,
    bin_path: str,
    skip_if_present: tuple = (),
    *,
    dry_run: bool = False,
) -> bool:
    try:
        raw_bytes: bytes | None = None
        if cfg_path.exists():
            if not cfg_path.is_file():
                note(f"Skipping {cfg_path}: not a regular file; left untouched.")
                return False
            raw_bytes = cfg_path.read_bytes()
            try:
                data = json.loads(raw_bytes.decode("utf-8"))
            except (ValueError, UnicodeDecodeError):
                note(f"Skipping {cfg_path}: failed to parse as JSON (JSONC comments or syntax error); left untouched.")
                return False
        else:
            data = {}
        if not isinstance(data, dict):
            note(f"Skipping {cfg_path}: top-level JSON is not an object; left untouched.")
            return False
        servers = data.setdefault("mcpServers", {})
        if not isinstance(servers, dict):
            note(f"Skipping {cfg_path}: mcpServers is not a JSON object; left untouched.")
            return False
        if any(k in servers for k in skip_if_present):
            return True
        if dry_run:
            return True
        servers["ankle"] = {"command": bin_path, "args": ["mcp"]}
        payload = (json.dumps(data, indent=2) + "\n").encode("utf-8")
        _atomic_write_bytes(cfg_path, payload, write_backup=True, existing_bytes=raw_bytes)
        return True
    except Exception as exc:
        note(f"Skipping {cfg_path}: {exc.__class__.__name__}; left untouched.")
        return False


def _register_claude_code_mcp(mcp_cmd: str = "ankle", *, dry_run: bool = False) -> bool:
    """Register the ANKLE stdio MCP server in Claude Code via `claude mcp add` instead of editing ~/.claude.json."""
    claude_code_cfg = Path.home() / ".claude.json"
    if claude_code_cfg.exists():
        if not claude_code_cfg.is_file():
            note(f"Skipping {claude_code_cfg}: not a regular file; left untouched.")
            return False
        try:
            data = json.loads(claude_code_cfg.read_text(encoding="utf-8"))
        except (ValueError, UnicodeDecodeError):
            note(f"Skipping {claude_code_cfg}: failed to parse as JSON (JSONC comments or syntax error); left untouched.")
            return False
        if not isinstance(data, dict):
            note(f"Skipping {claude_code_cfg}: top-level JSON is not an object; left untouched.")
            return False
        if "mcpServers" in data and not isinstance(data.get("mcpServers"), dict):
            note(f"Skipping {claude_code_cfg}: mcpServers is not a JSON object; left untouched.")
            return False
    if not shutil.which("claude"):
        return False
    if dry_run:
        return True
    try:
        proc = subprocess.run(
            ["claude", "mcp", "add", "--transport", "stdio", "ankle", "--", mcp_cmd, "mcp"],
            capture_output=True,
            text=True,
            timeout=15,
        )
        if proc.returncode == 0:
            return True
        combined = ((proc.stdout or "") + "\n" + (proc.stderr or "")).lower()
        if "already exists" in combined:
            return True
        return False
    except Exception:
        return False


def cmd_setup(api: Api, args) -> int:
    """One-command setup for humans and external agents: sign in (if needed), install skill, and wire MCP."""
    if not api.auth.token and not getattr(args, "no_login", False) and not api.dry_run:
        note("Not signed in yet — starting browser login (click Allow in your browser)...")
        login_args = argparse.Namespace(
            scopes=getattr(args, "scopes", None),
            no_browser=getattr(args, "no_browser", False),
            paste=getattr(args, "paste", False),
            timeout=getattr(args, "timeout", 300),
            reregister=False,
        )
        rc = cmd_login(api, login_args)
        if rc != EXIT_OK:
            return rc
        api = Api(api.origin, dry_run=api.dry_run)

    bin_path = shutil.which("ankle") or str(Path.home() / ".local" / "bin" / "ankle")
    wired = []

    # 1. Install ANKLE skill for Hermes / external agents (~/.hermes/skills/ankle/SKILL.md)
    if not api.dry_run:
        try:
            skill_dir = Path.home() / ".hermes" / "skills" / "ankle"
            resp = http_request("GET", "https://ankle.md/SKILL.md")
            if resp.status == 200 and resp.body:
                _atomic_write_bytes(skill_dir / "SKILL.md", resp.body, write_backup=True)
                wired.append(f"skill -> {skill_dir / 'SKILL.md'}")
        except Exception:
            pass

    # 2. Wire Cursor MCP (~/.cursor/mcp.json) if ~/.cursor exists
    cursor_dir = Path.home() / ".cursor"
    if cursor_dir.is_dir() and _register_json_mcp_server(cursor_dir / "mcp.json", bin_path, dry_run=api.dry_run):
        wired.append(f"cursor mcp -> {cursor_dir / 'mcp.json'}")

    # 3. Wire Claude Desktop MCP (atomic .bak + tmp+rename) & Claude Code MCP (via `claude mcp add`)
    claude_desktop_cfg = Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
    if claude_desktop_cfg.parent.is_dir() and _register_json_mcp_server(
        claude_desktop_cfg, bin_path, ("ankle-os",), dry_run=api.dry_run
    ):
        wired.append(f"claude desktop mcp -> {claude_desktop_cfg}")
    if _register_claude_code_mcp("ankle", dry_run=api.dry_run):
        wired.append("claude code mcp -> claude mcp add --transport stdio ankle -- ankle mcp")

    # 4. Verify live identity & tools if signed in
    user_handle = None
    tool_count = 0
    if api.auth.token and not api.dry_run:
        try:
            me = api.me()
            owner = me.get("owner") or {}
            user_handle = "@" + str(owner.get("username") or me.get("username") or "unknown")
            tool_count = len(api.tools())
        except Exception:
            pass

    summary = {
        "ok": bool(api.auth.token),
        "user": user_handle,
        "tools_ready": tool_count,
        "mcp_stdio_command": f"{bin_path} mcp",
        "mcp_http_url": f"{api.origin}/api/mcp",
        "wired": wired,
    }
    text_lines = [
        f"ANKLE OS setup complete ({user_handle or 'not signed in'} · {tool_count} MCP tools ready)",
        f"  CLI binary:       {bin_path}",
        f"  Stdio MCP server: {bin_path} mcp   (uses ~/.config/ankle/credentials.json automatically)",
        f"  HTTP MCP server:  {api.origin}/api/mcp",
    ]
    for w in wired:
        text_lines.append(f"  Auto-configured:  {w}")
    emit(summary, "\n".join(text_lines))
    return EXIT_OK


# -- desk passthrough (merge with the local terminal launcher) -----------------------------------

def _desk_bin() -> str | None:
    cand = os.environ.get("ANKLE_DESK_BIN") or shutil.which("ankle-desk")
    if cand and os.access(cand, os.X_OK) and os.path.realpath(cand) != os.path.realpath(sys.argv[0] or ""):
        return cand
    return None


# -- argument parsing -------------------------------------------------------------------------

def build_parser() -> argparse.ArgumentParser:
    common = argparse.ArgumentParser(add_help=False)
    common.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help="Machine-readable JSON output.")
    common.add_argument("--origin", default=argparse.SUPPRESS, help="API origin (default https://ankle.studio or $ANKLE_ORIGIN).")
    common.add_argument("--dry-run", action="store_true", default=argparse.SUPPRESS,
                        help="Print the request instead of sending it (never prints credentials).")

    p = argparse.ArgumentParser(prog=PROG, parents=[common], description=__doc__.split("\n\n")[0],
                                formatter_class=argparse.RawDescriptionHelpFormatter, epilog=(
        "commands:\n"
        "  login | logout | whoami         sign in with your browser, sign out, show identity\n"
        "  tools | call <tool> k=v ...     list MCP tools, call any tool (k:=json, k=@file)\n"
        "  worlds | surf <query>           your Worlds, search the SURF archive\n"
        "  pages | page <id> [--html]      list pages, read one\n"
        "  build <prompt> [--save]         generate a page (scope pages.generate)\n"
        "  settings [get | set ...]        read or update your account preferences (opt-in scopes)\n"
        "  credits                         credit balance\n"
        "  world <word> | ask <word> \"q\"   a World's public agent\n\n"
        "exit codes: 0 ok, 1 error, 2 usage, 3 not signed in / key rejected, 4 not found\n"
        "env: ANKLE_AGENT_KEY, ANKLE_ORIGIN, ANKLE_CONFIG_DIR"))
    p.add_argument("--version", action="version", version=f"ankle {VERSION} ({ANKLE_CLI_ID})")
    sub = p.add_subparsers(dest="command", metavar="<command>")
    sub.required = True

    def add(name, help_text, **kw):
        safe_help = help_text.replace("%", "%%") if isinstance(help_text, str) else help_text
        return sub.add_parser(name, parents=[common], help=safe_help, **kw)

    s = add("login", "Sign in: opens your browser, you click Allow.")
    s.add_argument("--scopes", help="Scopes: comma/space list, presets read|draft|build, or +scope to add to the "
                                    "default read set. Default: the server's read-mostly set.")
    s.add_argument("--no-browser", action="store_true", help="Do not open a browser; print the URL only.")
    s.add_argument("--paste", action="store_true", help="Headless/SSH: paste the redirected address back in.")
    s.add_argument("--timeout", type=int, default=300, help="Seconds to wait for the browser (default 300).")
    s.add_argument("--reregister", action="store_true", help="Register a fresh OAuth client.")
    add("logout", "Sign out on this computer and cancel its key.")
    add("whoami", "Show who you are signed in as and what you allowed.")
    add("tools", "List everything your key can do.")
    s = add("call", "Advanced: run any tool by name, e.g. call surf_search query=dragon")
    s.add_argument("tool")
    s.add_argument("pairs", nargs="*", metavar="key=value")
    s.add_argument("--args", help="Base arguments as a JSON object.")
    add("worlds", "List your Worlds.")
    s = add("surf", "Search the SURF archive.")
    s.add_argument("query", nargs="+")
    s.add_argument("--limit", type=int, default=12)
    s = add("pages", "List your pages.")
    s.add_argument("--limit", type=int, default=30)
    s.add_argument("--after", type=int, default=0, help="Paginate after this page id.")
    s = add("page", "Read one page: ankle page <id> [--html | -o FILE].")
    s.add_argument("rest", nargs="+", metavar="id")
    s.add_argument("--html", action="store_true", help="Print only the stored HTML.")
    s.add_argument("-o", "--output", help="Write the stored HTML to FILE.")
    for flag in ("--world", "--title", "--request-id"):
        s.add_argument(flag, help=argparse.SUPPRESS)
    s.add_argument("--revision", type=int, help=argparse.SUPPRESS)
    s = add("build", "Make a page from a sentence.")
    s.add_argument("prompt", nargs="+")
    s.add_argument("--page", type=int, help="Apply the prompt to an existing page you own (saves to it).")
    s.add_argument("-o", "--output", help="Write the generated preview HTML to FILE.")
    s.add_argument("--save", action="store_true", help="Save the preview as a new private draft (scope builder.create).")
    s.add_argument("--title", help="Title for --save (default: the prompt).")
    s.add_argument("--world", help="World word for --save.")
    add("credits", "Show your credit balance.")
    s = add("settings", "Read or update your account settings (opt-in scopes settings.get / settings.update).")
    s.add_argument("rest", nargs="*", metavar="get|set [key=value ...]")
    s.add_argument("--theme", help="Set account theme slug (e.g. ankle-2029, discmaster, ankle-classic, dark-studio, bauhaus).")
    s.add_argument("--locale", help="Set account locale (e.g. en-US, es-ES, fr-FR, de-DE, ja-JP, ko-KR, zh-CN).")
    s.add_argument("--color-mode", dest="color_mode", help="Set color mode (system, light, dark).")
    s.add_argument("--site-theme-takeover", dest="site_theme_takeover", help="Enable/disable external site skin takeover (true/false).")
    s.add_argument("--display-name", dest="display_name", help="Set profile display name (max 80 chars).")
    s.add_argument("--bio", help="Set profile bio (max 500 chars).")
    s.add_argument("--avatar-url", dest="avatar_url", help="Set profile avatar URL.")
    s.add_argument("--telegram-notifications", dest="telegram_notifications", help="Enable/disable Telegram notifications (true/false).")
    s.add_argument("--sms-notifications", dest="sms_notifications", help="Enable/disable SMS notifications (true/false).")
    s.add_argument("--in-app-notifications", dest="in_app_notifications", help="Enable/disable in-app notifications (true/false).")
    s.add_argument("--email-notifications", dest="email_notifications", help="Enable/disable email notifications (true/false).")
    s.add_argument("--args", help="Settings update payload as a JSON object.")
    s = add("world", "Show a World's public agent: ankle world <word>.")
    s.add_argument("rest", nargs="+", metavar="word")
    s.add_argument("--auth", action="store_true", help="Send your key to the World host.")
    s.add_argument("--request-id", help=argparse.SUPPRESS)
    s = add("ask", "Ask a World's agent: ankle ask <word> \"question\".")
    s.add_argument("word")
    s.add_argument("question", nargs="+")
    s.add_argument("--auth", action="store_true", help="Send your key to the World host.")
    s = add("talk", "Talk to an agent you own: ankle talk <agent> \"message\".")
    s.add_argument("agent")
    s.add_argument("message", nargs="+")
    s = add("brief", "Get an agent's grounded brief: ankle brief <agent>.")
    s.add_argument("agent")
    add("discover", "Advanced: print what ANKLE offers agents (no sign-in needed).")
    s = add("act", "Advanced: run one agent action from a JSON file.")
    s.add_argument("action")
    s.add_argument("payload_file")
    add("status", "Show ANKLE OS cloud, account, $ANKL index, and local node status.")
    s = add("chat", "Talk with @COMMAND (gemini-4-argon) in your terminal, or omit message for interactive shell.")
    s.add_argument("message", nargs="*")
    s = add("shell", "Launch interactive ANKLE OS terminal shell (@COMMAND REPL).")
    s.add_argument("message", nargs="*")
    s = add("dada", "Search or browse /dada L0-L3 semantic objects.")
    s.add_argument("query", nargs="*")
    s.add_argument("--limit", type=int, default=12)
    add("ankl", "Show live $ANKL Reserve Oracle, Streamflow lock, and burn ledger.")
    s = add("index", "Show the live $ANKL S&P 500 Cultural Reserve Index constituents.")
    s.add_argument("--limit", type=int, default=15)
    add("reciprocity", "Show the live Reciprocity Settlement Rail protocol summary.")
    s = add("setup", "One-command agent setup: sign in, install skill, and wire MCP for local agents.")
    s.add_argument("--scopes", help="Optional scopes for login if not signed in yet.")
    s.add_argument("--no-browser", action="store_true", help="Do not open a browser; print the login URL.")
    s.add_argument("--paste", action="store_true", help="Headless/SSH login paste mode.")
    s.add_argument("--no-login", action="store_true", help="Configure local agent files without triggering browser login.")
    add("mcp", "Run stdio MCP server using your signed-in ~/.config/ankle/credentials.json or ANKLE_AGENT_KEY.")
    return p


def welcome() -> str:
    """What a person sees when they type just `ankle`: plain words, three first steps."""
    signed_in = bool(os.environ.get("ANKLE_AGENT_KEY")) or creds_path().exists()
    status = "You're signed in." if signed_in else "You're not signed in yet."
    first = (f"  {PROG} worlds              see your worlds\n"
             f"  {PROG} surf dragon         search the archive for anything\n"
             f"  {PROG} pages               list the pages you've made\n") if signed_in else (
             f"  1. {PROG} login            opens your browser; click Allow\n"
             f"  2. {PROG} worlds           see your worlds\n"
             f"  3. {PROG} surf dragon      search the archive for anything\n")
    return ("ANKLE OS\n"
            f"{status}\n\n"
            "Start here\n" + first + "\n"
            "More things you can do\n"
            f"  {PROG} page 42             read one of your pages\n"
            f"  {PROG} build \"a page about tomatoes\"   make a page from a sentence\n"
            f"  {PROG} world tomato        see a world's agent\n"
            f"  {PROG} ask tomato \"what's new?\"        ask that world's agent\n"
            f"  {PROG} credits             your credit balance\n"
            f"  {PROG} help                every command\n\n"
            "Guide with pictures: https://ankle.studio/cli")


def main(argv=None) -> int:
    argv = list(sys.argv[1:] if argv is None else argv)
    desk = _desk_bin()
    if desk and (not argv or argv[0] in DESK_COMMANDS):
        os.execv(desk, [desk] + argv)
    parser = build_parser()
    if not argv:
        print(welcome())
        return EXIT_OK
    if argv[0] in {"help", "--help-all"}:
        parser.print_help()
        return EXIT_OK
    args = parser.parse_args(argv)
    Out.json = bool(getattr(args, "json", False))
    try:
        api = Api(resolve_origin(getattr(args, "origin", None)), dry_run=bool(getattr(args, "dry_run", False)))
        cmd = args.command
        if cmd == "login":
            return cmd_login(api, args)
        if cmd == "logout":
            return cmd_logout(api, args)
        if cmd == "whoami":
            return cmd_whoami(api, args)
        if cmd == "tools":
            return cmd_tools(api, args)
        if cmd == "call":
            return cmd_call(api, args)
        if cmd == "worlds":
            return cmd_worlds(api, args)
        if cmd == "surf":
            q = args.query
            if q[0] == "search" and len(q) > 1:  # v0: ankle surf search <query>
                Out.json = True
                return cmd_surf(api, args, " ".join(q[1:]), legacy=True)
            return cmd_surf(api, args, " ".join(q))
        if cmd == "pages":
            return cmd_pages(api, args)
        if cmd == "page":
            if args.rest[0] in {"list", "get", "create", "patch", "publish", "clear", "attach"}:
                return legacy_page(api, args, args.rest)
            if len(args.rest) != 1:
                raise CliError(f"Usage: {PROG} page <id> [--html | -o FILE]", EXIT_USAGE)
            return cmd_page(api, args, _page_id(args.rest[0]))
        if cmd == "build":
            return cmd_build(api, args)
        if cmd == "credits":
            return cmd_credits(api, args)
        if cmd == "settings":
            return cmd_settings(api, args)
        if cmd == "world":
            if args.rest[0] in {"list", "create"}:  # v0: ankle world list | world create <word>
                return legacy_world(api, args, args.rest)
            if len(args.rest) != 1:
                raise CliError(f"Usage: {PROG} world <word>", EXIT_USAGE)
            return cmd_world(api, args, args.rest[0])
        if cmd == "ask":
            return cmd_ask(api, args, args.word)
        if cmd == "talk":
            return cmd_talk(api, args, args.agent)
        if cmd == "brief":
            return cmd_brief(api, args, args.agent)
        if cmd == "discover":
            return cmd_discover(api, args)
        if cmd == "act":
            return cmd_act(api, args)
        if cmd == "status":
            return cmd_status(api, args)
        if cmd in ("chat", "shell"):
            return cmd_chat(api, args)
        if cmd == "dada":
            return cmd_dada(api, args)
        if cmd == "ankl":
            return cmd_ankl(api, args)
        if cmd == "index":
            return cmd_index(api, args)
        if cmd == "reciprocity":
            return cmd_reciprocity(api, args)
        if cmd == "setup":
            return cmd_setup(api, args)
        if cmd == "mcp":
            return cmd_mcp(api, args)
        raise CliError(f"Unknown command {cmd}", EXIT_USAGE)
    except DryRun:
        return EXIT_OK
    except CliError as exc:
        if Out.json:
            print(json.dumps({"error": exc.message, "status": exc.status, "hint": exc.hint}), file=sys.stderr)
        else:
            note("error: " + exc.message)
            if exc.hint:
                note("hint: " + exc.hint)
        return exc.code
    except KeyboardInterrupt:
        note("Interrupted.")
        return 130


if __name__ == "__main__":
    sys.exit(main())
