#!/usr/bin/env python3
"""
a2ac.py — A2AC Local .cube Indexer, Token Benchmark & MCP Stdio Server
Zero external dependencies (Python 3.9+ stdlib; uses tiktoken if installed).

Usage:
  python a2ac.py index [repo_path]
  python a2ac.py bench [repo_path] [--steps 15]
  python a2ac.py mcp [repo_path]
  python a2ac.py setup [--client claude|cursor|vscode] [--write]
"""

from __future__ import annotations

import argparse
import ast
import hashlib
import json
import os
import re
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

VERSION = "1.0.0"
PROTOCOL_VERSION = "2024-11-05"

IGNORE_DIRS = {
    ".git", ".hg", ".svn", ".a2ac", ".venv", "venv", "env", "__pycache__",
    "node_modules", "dist", "build", "target", ".next", ".nuxt", ".cache",
    "coverage", ".pytest_cache", ".mypy_cache", "vendor", ".idea", ".vscode",
}

CODE_EXTS = {
    ".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
    ".go", ".rs", ".java", ".kt", ".cs", ".rb", ".php", ".c", ".cpp", ".h",
}

DOC_EXTS = {".md", ".json", ".yaml", ".yml", ".toml", ".sql"}

PRICE_PER_1M_INPUT = {
    "claude-sonnet": 3.00,
    "claude-opus": 15.00,
    "gpt-4o": 2.50,
}

try:
    import tiktoken  # type: ignore
    _ENC = tiktoken.get_encoding("cl100k_base")

    def count_tokens(text: str) -> int:
        return len(_ENC.encode(text)) if text else 0

    TOKENIZER_NAME = "tiktoken:cl100k_base"
except Exception:
    def count_tokens(text: str) -> int:
        if not text:
            return 0
        # Calibrated code-BPE heuristic (~3.55 chars/token for source code)
        return max(1, (len(text) + 3) // 4 + text.count("\n") // 8)

    TOKENIZER_NAME = "a2ac-bpe-calibrated"


def sha256_hex(data: str) -> str:
    return hashlib.sha256(data.encode("utf-8", errors="replace")).hexdigest()


def iter_repo_files(repo: Path, include_docs: bool = False) -> List[Path]:
    allowed = CODE_EXTS | (DOC_EXTS if include_docs else set())
    results: List[Path] = []
    for root, dirs, files in os.walk(repo):
        dirs[:] = sorted(d for d in dirs if d not in IGNORE_DIRS and not d.startswith("."))
        for fname in sorted(files):
            if fname in {"a2ac.py", "a2ac_token_benchmark.py"}:
                continue
            p = Path(root) / fname
            if p.suffix.lower() in allowed:
                try:
                    if p.stat().st_size <= 512_000:
                        results.append(p)
                except OSError:
                    continue
    return results


def extract_python_symbols(text: str) -> List[Dict[str, Any]]:
    symbols: List[Dict[str, Any]] = []
    try:
        tree = ast.parse(text)
    except SyntaxError:
        return extract_regex_symbols(text, ".py")

    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
            kind = "class" if isinstance(node, ast.ClassDef) else "function"
            start = getattr(node, "lineno", 1)
            end = getattr(node, "end_lineno", start) or start
            sig = ""
            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                args = [a.arg for a in node.args.args]
                sig = f"({', '.join(args[:6])}{', ...' if len(args) > 6 else ''})"
            doc = ast.get_docstring(node) or ""
            first_doc = doc.strip().splitlines()[0][:100] if doc.strip() else ""
            symbols.append({
                "name": node.name,
                "kind": kind,
                "start_line": start,
                "end_line": end,
                "signature": sig,
                "summary": first_doc,
            })
    symbols.sort(key=lambda s: (s["start_line"], s["name"]))
    return symbols


REGEX_PATTERNS = [
    ("class", re.compile(r"^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|trait|type)\s+([A-Za-z_][A-Za-z0-9_]*)")),
    ("function", re.compile(r"^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|def|fn|func|sub)\s+([A-Za-z_][A-Za-z0-9_]*)")),
    ("function", re.compile(r"^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_][A-Za-z0-9_]*)\s*=>")),
    ("route", re.compile(r"^\s*(?:app|router)\.(?:get|post|put|patch|delete|use|all)\(\s*['\"`]([^'\"`]+)['\"`]")),
    ("export", re.compile(r"^\s*(?:module\.)?exports\.([A-Za-z_][A-Za-z0-9_]*)\s*=")),
    ("config", re.compile(r"^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?:new\s+[A-Za-z_]|express\(|create|define)")),
    ("method", re.compile(r"^\s*(?:public|private|protected|static|async|\s)*([A-Za-z_][A-Za-z0-9_]*)\s*\([^;{}]*\)\s*\{")),
]


def extract_regex_symbols(text: str, ext: str) -> List[Dict[str, Any]]:
    lines = text.splitlines()
    symbols: List[Dict[str, Any]] = []
    seen = set()
    for idx, line in enumerate(lines, start=1):
        for kind, pat in REGEX_PATTERNS:
            m = pat.match(line)
            if m:
                name = m.group(1)
                if name in {"if", "for", "while", "switch", "catch", "return"}:
                    continue
                key = (idx, name)
                if key in seen:
                    continue
                seen.add(key)
                symbols.append({
                    "name": name,
                    "kind": kind,
                    "start_line": idx,
                    "end_line": min(len(lines), idx + 25),
                    "signature": "",
                    "summary": line.strip()[:90],
                })
                break
    # Refine end_line using next symbol start
    for i in range(len(symbols) - 1):
        next_start = symbols[i + 1]["start_line"]
        if next_start > symbols[i]["start_line"]:
            symbols[i]["end_line"] = min(symbols[i]["end_line"], next_start - 1)
    return symbols


def build_cube_for_file(repo: Path, file_path: Path) -> Dict[str, Any]:
    rel = file_path.relative_to(repo).as_posix()
    text = file_path.read_text(encoding="utf-8", errors="replace")
    lines = text.splitlines()
    ext = file_path.suffix.lower()
    symbols = extract_python_symbols(text) if ext == ".py" else extract_regex_symbols(text, ext)
    raw_tokens = count_tokens(text)
    cube = {
        "schema": "a2ac-cube-v1",
        "file": rel,
        "ext": ext,
        "bytes": len(text.encode("utf-8", errors="replace")),
        "lines": len(lines),
        "raw_tokens": raw_tokens,
        "sha256": sha256_hex(text)[:16],
        "symbols": symbols,
    }
    cube["cube_tokens"] = count_tokens(json.dumps({
        "file": rel,
        "lines": len(lines),
        "symbols": [
            {"n": s["name"], "k": s["kind"], "l": f"{s['start_line']}-{s['end_line']}"}
            for s in symbols[:40]
        ],
    }, separators=(",", ":")))
    return cube


def index_repo(repo: Path, write_sidecars: bool = True) -> Dict[str, Any]:
    t0 = time.perf_counter()
    files = iter_repo_files(repo, include_docs=False)
    cubes: List[Dict[str, Any]] = []
    cubes_dir = repo / ".a2ac" / "cubes"
    if write_sidecars:
        cubes_dir.mkdir(parents=True, exist_ok=True)

    total_raw = 0
    total_cube = 0
    total_symbols = 0

    for fp in files:
        c = build_cube_for_file(repo, fp)
        cubes.append(c)
        total_raw += c["raw_tokens"]
        total_cube += c["cube_tokens"]
        total_symbols += len(c["symbols"])
        if write_sidecars:
            out_path = cubes_dir / (c["file"].replace("/", "__") + ".cube")
            out_path.write_text(json.dumps(c, indent=2), encoding="utf-8")

    elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 1)
    manifest = {
        "schema": "a2ac-manifest-v1",
        "version": VERSION,
        "tokenizer": TOKENIZER_NAME,
        "repo": str(repo.resolve()),
        "files_indexed": len(cubes),
        "symbols_indexed": total_symbols,
        "total_raw_tokens": total_raw,
        "total_cube_tokens": total_cube,
        "index_reduction_pct": round((1.0 - (total_cube / total_raw)) * 100.0, 2) if total_raw else 0.0,
        "elapsed_ms": elapsed_ms,
        "files": [
            {
                "file": c["file"],
                "lines": c["lines"],
                "raw_tokens": c["raw_tokens"],
                "cube_tokens": c["cube_tokens"],
                "symbols": len(c["symbols"]),
                "sha256": c["sha256"],
            }
            for c in cubes
        ],
    }
    if write_sidecars:
        (repo / ".a2ac" / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    return {"manifest": manifest, "cubes": cubes}


def run_benchmark(repo: Path, steps: int = 15) -> Dict[str, Any]:
    indexed = index_repo(repo, write_sidecars=True)
    cubes = indexed["cubes"]
    manifest = indexed["manifest"]
    if not cubes:
        return {"error": f"No supported source files found in {repo}"}

    # Select top representative code files (most symbols / meaty size)
    ranked = sorted(cubes, key=lambda c: (len(c["symbols"]), c["raw_tokens"]), reverse=True)
    targets = ranked[: min(4, len(ranked))]

    # Track A: Standard multi-turn AI loop (accumulating full-file context across steps)
    raw_turn_tokens = 0
    raw_context_acc = 0
    for s in range(1, steps + 1):
        target = targets[(s - 1) % len(targets)]
        # A standard coding loop re-sends accumulated files + new file read + ~450 prompt/tool tokens
        raw_context_acc = min(sum(t["raw_tokens"] for t in targets), raw_context_acc + target["raw_tokens"])
        raw_turn_tokens += raw_context_acc + 450

    # Track B: A2AC MCP loop (reads compact .cube symbol map + exact function slice per step)
    a2ac_turn_tokens = 0
    manifest_map_tokens = min(900, max(120, len(targets) * 65))
    for s in range(1, steps + 1):
        target = targets[(s - 1) % len(targets)]
        fp = repo / target["file"]
        text_lines = fp.read_text(encoding="utf-8", errors="replace").splitlines()
        if target["symbols"]:
            sym = target["symbols"][(s - 1) % len(target["symbols"])]
            slice_lines = text_lines[max(0, sym["start_line"] - 1) : min(len(text_lines), sym["end_line"])]
            slice_text = "\n".join(slice_lines[:80])
        else:
            slice_text = "\n".join(text_lines[:45])
        slice_tokens = count_tokens(slice_text)
        a2ac_turn_tokens += (manifest_map_tokens if s == 1 else 95) + slice_tokens + 110

    avoided = max(0, raw_turn_tokens - a2ac_turn_tokens)
    reduction_pct = round((avoided / raw_turn_tokens) * 100.0, 2) if raw_turn_tokens else 0.0
    mult = round(raw_turn_tokens / max(1, a2ac_turn_tokens), 1)

    costs = {}
    for model, price in PRICE_PER_1M_INPUT.items():
        r_usd = round((raw_turn_tokens / 1_000_000.0) * price, 4)
        a_usd = round((a2ac_turn_tokens / 1_000_000.0) * price, 4)
        costs[model] = {
            "raw_usd": r_usd,
            "a2ac_usd": a_usd,
            "saved_usd": round(max(0.0, r_usd - a_usd), 4),
            "monthly_saved_100_tasks_usd": round(max(0.0, r_usd - a_usd) * 100.0, 2),
        }

    report = {
        "schema": "a2ac-bench-receipt-v1",
        "repo": str(repo.resolve()),
        "tokenizer": TOKENIZER_NAME,
        "files_indexed": manifest["files_indexed"],
        "symbols_indexed": manifest["symbols_indexed"],
        "steps": steps,
        "target_files": [t["file"] for t in targets],
        "raw_tokens": raw_turn_tokens,
        "a2ac_tokens": a2ac_turn_tokens,
        "tokens_avoided": avoided,
        "reduction_pct": reduction_pct,
        "efficiency_multiplier": mult,
        "costs": costs,
        "local_api_cost_usd": 0.0,
    }
    report["receipt_sha256"] = sha256_hex(json.dumps(report, sort_keys=True))[:24]
    out_file = repo / ".a2ac" / "bench_receipt.json"
    out_file.parent.mkdir(parents=True, exist_ok=True)
    out_file.write_text(json.dumps(report, indent=2), encoding="utf-8")
    return report


class A2ACMcpServer:
    def __init__(self, repo: Path):
        self.repo = repo.resolve()
        self.session_raw_tokens = 0
        self.session_a2ac_tokens = 0
        self.calls = 0
        self._cache: Optional[Dict[str, Any]] = None

    def _ensure_index(self) -> Dict[str, Any]:
        if self._cache is None:
            self._cache = index_repo(self.repo, write_sidecars=True)
        return self._cache

    def _cube_map(self) -> Dict[str, Dict[str, Any]]:
        data = self._ensure_index()
        return {c["file"]: c for c in data["cubes"]}

    def tools(self) -> List[Dict[str, Any]]:
        return [
            {
                "name": "a2ac_index_workspace",
                "description": "Index or refresh local .cube AST/symbol sidecars for the repository at $0 cloud cost.",
                "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
            },
            {
                "name": "a2ac_list_files",
                "description": "List indexed repository files with line counts, symbol counts, and raw token sizes.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "prefix": {"type": "string", "description": "Optional path prefix filter"},
                        "limit": {"type": "integer", "description": "Max files to return (default 80)"},
                    },
                },
            },
            {
                "name": "a2ac_get_symbols",
                "description": "Get compact symbol map (functions, classes, methods, line ranges) for a file without reading the whole file.",
                "inputSchema": {
                    "type": "object",
                    "properties": {"file": {"type": "string", "description": "Relative file path"}},
                    "required": ["file"],
                },
            },
            {
                "name": "a2ac_read_slice",
                "description": "Read only the exact line range or named symbol from a file instead of loading the entire file.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "file": {"type": "string", "description": "Relative file path"},
                        "symbol": {"type": "string", "description": "Optional symbol name from a2ac_get_symbols"},
                        "start_line": {"type": "integer", "description": "1-indexed start line"},
                        "end_line": {"type": "integer", "description": "1-indexed end line"},
                    },
                    "required": ["file"],
                },
            },
            {
                "name": "a2ac_search_symbols",
                "description": "Search indexed symbols across the entire repo and return exact file + line ranges.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "query": {"type": "string", "description": "Substring or regex to match symbol names"},
                        "limit": {"type": "integer", "description": "Max matches (default 25)"},
                    },
                    "required": ["query"],
                },
            },
            {
                "name": "a2ac_savings_receipt",
                "description": "Return cumulative tokens saved in this MCP session and SHA-256 receipt.",
                "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
            },
        ]

    def call_tool(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]:
        self.calls += 1
        if name == "a2ac_index_workspace":
            self._cache = index_repo(self.repo, write_sidecars=True)
            m = self._cache["manifest"]
            return {"ok": True, "files_indexed": m["files_indexed"], "symbols_indexed": m["symbols_indexed"], "index_reduction_pct": m["index_reduction_pct"], "elapsed_ms": m["elapsed_ms"]}

        if name == "a2ac_list_files":
            prefix = (args.get("prefix") or "").strip()
            limit = int(args.get("limit") or 80)
            m = self._ensure_index()["manifest"]
            files = [f for f in m["files"] if not prefix or f["file"].startswith(prefix)][:limit]
            out = {"files_total": m["files_indexed"], "returned": len(files), "files": files}
            self.session_a2ac_tokens += count_tokens(json.dumps(out))
            return out

        if name == "a2ac_get_symbols":
            rel = str(args.get("file") or "").lstrip("./")
            cmap = self._cube_map()
            cube = cmap.get(rel)
            if not cube:
                return {"error": f"File not indexed: {rel}"}
            out = {
                "file": cube["file"],
                "lines": cube["lines"],
                "raw_tokens": cube["raw_tokens"],
                "symbols": cube["symbols"],
            }
            self.session_raw_tokens += cube["raw_tokens"]
            self.session_a2ac_tokens += count_tokens(json.dumps(out))
            return out

        if name == "a2ac_read_slice":
            rel = str(args.get("file") or "").lstrip("./")
            target = (self.repo / rel).resolve()
            if not str(target).startswith(str(self.repo)) or not target.is_file():
                return {"error": f"File not found inside workspace: {rel}"}
            text = target.read_text(encoding="utf-8", errors="replace")
            lines = text.splitlines()
            raw_tok = count_tokens(text)

            start = args.get("start_line")
            end = args.get("end_line")
            sym_name = args.get("symbol")
            if sym_name and (start is None or end is None):
                cube = self._cube_map().get(rel)
                if cube:
                    for s in cube["symbols"]:
                        if s["name"] == sym_name:
                            start = s["start_line"]
                            end = s["end_line"]
                            break
            s_idx = max(1, int(start or 1))
            e_idx = min(len(lines), int(end or min(len(lines), s_idx + 79)))
            snippet = "\n".join(f"{i}: {lines[i - 1]}" for i in range(s_idx, e_idx + 1))
            slice_tok = count_tokens(snippet)
            self.session_raw_tokens += raw_tok
            self.session_a2ac_tokens += slice_tok
            return {
                "file": rel,
                "start_line": s_idx,
                "end_line": e_idx,
                "slice_tokens": slice_tok,
                "full_file_tokens": raw_tok,
                "tokens_saved": max(0, raw_tok - slice_tok),
                "content": snippet,
            }

        if name == "a2ac_search_symbols":
            q = str(args.get("query") or "").lower()
            limit = int(args.get("limit") or 25)
            matches: List[Dict[str, Any]] = []
            for cube in self._ensure_index()["cubes"]:
                for s in cube["symbols"]:
                    if q in s["name"].lower() or q in s.get("summary", "").lower():
                        matches.append({
                            "file": cube["file"],
                            "symbol": s["name"],
                            "kind": s["kind"],
                            "start_line": s["start_line"],
                            "end_line": s["end_line"],
                        })
                        if len(matches) >= limit:
                            break
                if len(matches) >= limit:
                    break
            out = {"query": q, "count": len(matches), "matches": matches}
            self.session_a2ac_tokens += count_tokens(json.dumps(out))
            return out

        if name == "a2ac_savings_receipt":
            avoided = max(0, self.session_raw_tokens - self.session_a2ac_tokens)
            payload = {
                "calls": self.calls,
                "raw_equivalent_tokens": self.session_raw_tokens,
                "a2ac_slice_tokens": self.session_a2ac_tokens,
                "tokens_avoided": avoided,
                "reduction_pct": round((avoided / self.session_raw_tokens) * 100.0, 2) if self.session_raw_tokens else 0.0,
            }
            payload["receipt_sha256"] = sha256_hex(json.dumps(payload, sort_keys=True))[:24]
            return payload

        return {"error": f"Unknown tool: {name}"}

    def serve(self) -> None:
        for raw_line in sys.stdin:
            line = raw_line.strip()
            if not line:
                continue
            try:
                req = json.loads(line)
            except json.JSONDecodeError:
                continue
            req_id = req.get("id")
            method = req.get("method", "")
            params = req.get("params") or {}
            if req_id is None:
                continue

            if method == "initialize":
                resp = {
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {
                        "protocolVersion": PROTOCOL_VERSION,
                        "serverInfo": {"name": "a2ac-local-mcp", "version": VERSION},
                        "capabilities": {"tools": {"listChanged": False}},
                    },
                }
            elif method == "tools/list":
                resp = {"jsonrpc": "2.0", "id": req_id, "result": {"tools": self.tools()}}
            elif method == "tools/call":
                tname = params.get("name", "")
                targs = params.get("arguments") or {}
                result = self.call_tool(tname, targs)
                resp = {
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]},
                }
            else:
                resp = {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}

            sys.stdout.write(json.dumps(resp) + "\n")
            sys.stdout.flush()


def print_bench(r: Dict[str, Any]) -> None:
    if "error" in r:
        print(f"Error: {r['error']}")
        sys.exit(1)
    print("")
    print("======================================================================")
    print(f" A2AC Local Token Benchmark ({r['tokenizer']})")
    print("======================================================================")
    print(f" Repo           : {r['repo']}")
    print(f" Indexed        : {r['files_indexed']} files | {r['symbols_indexed']} symbols ($0.00 local)")
    print(f" Target Files   : {', '.join(r['target_files'])}")
    print(f" Simulated Loop : {r['steps']} coding steps")
    print("----------------------------------------------------------------------")
    print(f" Standard Cloud AI (full files) : {r['raw_tokens']:>10,} tokens")
    print(f" A2AC .cube + Targeted Slices   : {r['a2ac_tokens']:>10,} tokens")
    print(f" Cloud Tokens Saved             : {r['tokens_avoided']:>10,} tokens ({r['reduction_pct']}% / {r['efficiency_multiplier']}x)")
    print("----------------------------------------------------------------------")
    for model, c in r["costs"].items():
        print(f" {model:<14} | ${c['raw_usd']:<7.4f} -> ${c['a2ac_usd']:<7.4f} per task | Saves ${c['monthly_saved_100_tasks_usd']:>6.2f}/mo @ 100 tasks")
    print("----------------------------------------------------------------------")
    print(f" Receipt SHA-256: {r['receipt_sha256']} -> .a2ac/bench_receipt.json")
    print(" Next Step      : Connect MCP to Claude Code / Cursor / VS Code:")
    print("                  python3 a2ac.py setup --client claude --write")
    print("======================================================================")
    print("")


def cmd_setup(repo: Path, client: str, write: bool) -> None:
    script_path = str(Path(__file__).resolve())
    py_exe = sys.executable or "python3"
    entry = {
        "command": py_exe,
        "args": [script_path, "mcp", str(repo.resolve())],
    }
    if client == "vscode":
        payload = {"servers": {"a2ac-local": entry}}
        target = repo / ".vscode" / "mcp.json"
    elif client == "cursor":
        payload = {"mcpServers": {"a2ac-local": entry}}
        target = repo / ".cursor" / "mcp.json"
    else:
        payload = {"mcpServers": {"a2ac-local": entry}}
        target = repo / ".mcp.json"

    if write:
        target.parent.mkdir(parents=True, exist_ok=True)
        existing: Dict[str, Any] = {}
        if target.exists():
            try:
                existing = json.loads(target.read_text(encoding="utf-8"))
            except Exception:
                existing = {}
        key = "servers" if client == "vscode" else "mcpServers"
        existing.setdefault(key, {})
        existing[key]["a2ac-local"] = entry
        target.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
        print(f"Wrote A2AC MCP config -> {target}")
    else:
        print(f"# Add to {target}:")
        print(json.dumps(payload, indent=2))


def main() -> None:
    parser = argparse.ArgumentParser(prog="a2ac.py", description="A2AC Local .cube Indexer, Benchmark & MCP Server")
    sub = parser.add_subparsers(dest="cmd", required=True)

    p_idx = sub.add_parser("index", help="Build local .cube AST/symbol sidecars")
    p_idx.add_argument("path", nargs="?", default=".", help="Repository path")

    p_bench = sub.add_parser("bench", help="Benchmark token savings on your own repository")
    p_bench.add_argument("path", nargs="?", default=".", help="Repository path")
    p_bench.add_argument("--steps", type=int, default=15, help="Simulated multi-turn coding steps")

    p_mcp = sub.add_parser("mcp", help="Run stdio MCP server for Claude Code, Cursor, VS Code")
    p_mcp.add_argument("path", nargs="?", default=".", help="Repository path")

    p_setup = sub.add_parser("setup", help="Generate or write MCP config for your editor")
    p_setup.add_argument("path", nargs="?", default=".", help="Repository path")
    p_setup.add_argument("--client", choices=["claude", "cursor", "vscode"], default="claude")
    p_setup.add_argument("--write", action="store_true", help="Write config file into the repository")

    args = parser.parse_args()
    repo = Path(args.path).resolve()

    if args.cmd == "index":
        res = index_repo(repo, write_sidecars=True)
        m = res["manifest"]
        print(f"Indexed {m['files_indexed']} files, {m['symbols_indexed']} symbols in {m['elapsed_ms']} ms -> .a2ac/manifest.json")
        print(f"Raw tokens: {m['total_raw_tokens']:,} -> Cube map tokens: {m['total_cube_tokens']:,} ({m['index_reduction_pct']}% smaller)")
    elif args.cmd == "bench":
        print_bench(run_benchmark(repo, steps=max(3, min(100, args.steps))))
    elif args.cmd == "mcp":
        A2ACMcpServer(repo).serve()
    elif args.cmd == "setup":
        cmd_setup(repo, args.client, args.write)


if __name__ == "__main__":
    main()
