#!/usr/bin/env python3
"""EcoCoder Reviewer Kit (single-file, zero-dependency Python 3 stdlib CLI).

Supports:
  1. `ecocoder login` / `ecocoder check` — credential setup & $25 budget check
  2. `ecocoder claude [args...]` — Anthropic Router Shim (isolated from daily `claude`, with workspace sync)
  3. `ecocoder pi [args...]` / `ecocoder setup-pi` — `pi-coding-agent` runner & config helper
  4. `ecocoder delegate "<prompt>"` / `ecocoder install-subagent` — bounded workflow subagent delegation
  5. `ecocoder stats` — actual measured GPU/Facility Wh vs 3T Frontier (MoE & Dense) and Claude Opus/Sonnet/Haiku
"""
from __future__ import annotations

import argparse
import fnmatch
import getpass
import hashlib
import http.client
import http.server
import json
import os
import shutil
import socketserver
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
from typing import Any

DEFAULT_GATEWAY_URL = os.environ.get("ECOCODER_GATEWAY_URL", "https://api.leanlm.ai")
DEFAULT_MODEL = "nw:ecocoder-3tier"
CONFIG_DIR = Path(os.environ.get("ECOCODER_CONFIG_DIR", str(Path.home() / ".ecocoder")))
KEY_FILE = CONFIG_DIR / "key"
GATEWAY_FILE = CONFIG_DIR / "gateway_url"

ALLOWED_SOURCE_EXTS = frozenset(
    {".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".java", ".go", ".rs", ".json", ".toml", ".yaml", ".yml"}
)
IGNORED_DIRS = frozenset(
    {".git", ".venv", "venv", "node_modules", "__pycache__", ".metrics", "target", "dist", "build", ".ecocoder", ".claude"}
)
SECRET_FILENAME_PATTERNS = (
    ".env",
    ".env.*",
    "*.pem",
    "*.key",
    "*.p12",
    "*.pfx",
    "*.keystore",
    "id_rsa*",
    "id_ed25519*",
    "*secret*",
    "*credential*",
    "service-account*.json",
    "service_account*.json",
    ".npmrc",
    ".pypirc",
    ".netrc",
    "auth.json",
    "token.json",
)
MAX_SINGLE_FILE_BYTES = 1024 * 1024
MAX_WORKSPACE_SYNC_BYTES = 15 * 1024 * 1024


def is_secret_path(rel_posix: str) -> bool:
    """Return True if a relative path matches any credential/secret filename pattern."""
    parts = [p.lower() for p in rel_posix.split("/") if p]
    if not parts:
        return True
    name = parts[-1]
    if any(seg in (".aws", ".ssh", ".gnupg", ".ecocoder") for seg in parts[:-1]):
        return True
    return any(fnmatch.fnmatch(name, pat) for pat in SECRET_FILENAME_PATTERNS)


def _save_private_text(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}_", suffix=".tmp", dir=str(path.parent))
    try:
        os.chmod(tmp_name, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as fh:
            fh.write(content.strip() + "\n")
        os.replace(tmp_name, path)
    except Exception:
        if os.path.exists(tmp_name):
            os.unlink(tmp_name)
        raise


def resolve_gateway_url(explicit: str = "") -> str:
    if explicit.strip():
        return explicit.strip().rstrip("/")
    env_gw = (os.environ.get("ECOCODER_GATEWAY_URL") or "").strip()
    if env_gw:
        return env_gw.rstrip("/")
    if GATEWAY_FILE.is_file():
        saved = GATEWAY_FILE.read_text(encoding="utf-8").strip()
        if saved:
            return saved.rstrip("/")
    return DEFAULT_GATEWAY_URL.rstrip("/")


def resolve_api_key(key_path: Path | None = None) -> tuple[str, str]:
    resolved_path = key_path or KEY_FILE
    env_key = (os.environ.get("ECOCODER_API_KEY") or "").strip()
    if env_key:
        return env_key, "env:ECOCODER_API_KEY"
    if resolved_path.is_file():
        saved = resolved_path.read_text(encoding="utf-8").strip()
        if saved:
            return saved, str(resolved_path)
    raise RuntimeError(
        "No EcoCoder API key configured. Run `ecocoder login --key <eco_live_...>` "
        "or export ECOCODER_API_KEY."
    )


def _api_get_json(gateway_url: str, token: str, path: str, query: dict[str, Any] | None = None) -> dict[str, Any]:
    url = f"{gateway_url.rstrip('/')}{path}"
    if query:
        clean_q = {k: str(v) for k, v in query.items() if v is not None and str(v) != ""}
        if clean_q:
            url = f"{url}?{urllib.parse.urlencode(clean_q)}"
    req = urllib.request.Request(
        url,
        headers={
            "Authorization": f"Bearer {token}",
            "Accept": "application/json",
            "User-Agent": "ecocoder-cli/1.0",
        },
        method="GET",
    )
    with urllib.request.urlopen(req, timeout=15) as resp:
        return json.loads(resp.read().decode("utf-8"))


def _list_candidate_relpaths(repo_dir: Path) -> list[Path]:
    try:
        proc = subprocess.run(
            ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
            cwd=str(repo_dir),
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            timeout=5,
            check=False,
        )
        if proc.returncode == 0 and proc.stdout:
            rels: list[Path] = []
            for raw in proc.stdout.split(b"\0"):
                if not raw:
                    continue
                rels.append(Path(raw.decode("utf-8", errors="surrogateescape")))
            return sorted(rels)
    except (OSError, subprocess.SubprocessError):
        pass

    out: list[Path] = []
    for path in sorted(repo_dir.rglob("*")):
        if path.is_symlink() or not path.is_file():
            continue
        rel = path.relative_to(repo_dir)
        if any(part in IGNORED_DIRS for part in rel.parts):
            continue
        out.append(rel)
    return out


class WorkspaceSyncCache:
    """Stat-indexed workspace collector that skips secrets and fails closed over 15 MiB."""

    def __init__(self, repo_dir: Path, max_total_bytes: int = MAX_WORKSPACE_SYNC_BYTES) -> None:
        self.repo_dir = repo_dir.resolve()
        self.max_total_bytes = max_total_bytes
        self._stat_cache: dict[str, tuple[int, int, str]] = {}
        self.last_files: dict[str, str] = {}

    def scan(self) -> dict[str, str]:
        files: dict[str, str] = {}
        next_cache: dict[str, tuple[int, int, str]] = {}
        total_bytes = 0

        for rel in _list_candidate_relpaths(self.repo_dir):
            if any(part in IGNORED_DIRS for part in rel.parts):
                continue
            rel_posix = rel.as_posix()
            if Path(rel_posix).suffix.lower() not in ALLOWED_SOURCE_EXTS:
                continue
            if is_secret_path(rel_posix):
                continue
            full = self.repo_dir / rel
            if full.is_symlink() or not full.is_file():
                continue
            try:
                resolved = full.resolve()
                if not resolved.is_relative_to(self.repo_dir):
                    continue
                st = full.stat()
            except OSError:
                continue
            if st.st_size > MAX_SINGLE_FILE_BYTES:
                continue

            cached = self._stat_cache.get(rel_posix)
            if cached is not None and cached[0] == st.st_mtime_ns and cached[1] == st.st_size:
                text = cached[2]
                b_len = st.st_size
            else:
                try:
                    raw_bytes = full.read_bytes()
                    if b"\x00" in raw_bytes:
                        continue
                    text = raw_bytes.decode("utf-8")
                    b_len = len(raw_bytes)
                except (UnicodeDecodeError, OSError):
                    continue

            if total_bytes + b_len > self.max_total_bytes:
                raise RuntimeError(
                    f"Workspace source exceeds {self.max_total_bytes // (1024 * 1024)} MiB sync budget "
                    f"at {rel_posix}. Run from a narrower --workspace-dir or pass --no-sync."
                )
            files[rel_posix] = text
            next_cache[rel_posix] = (st.st_mtime_ns, st.st_size, text)
            total_bytes += b_len

        self._stat_cache = next_cache
        return files

    def build_initial_payload(self) -> tuple[dict[str, Any], int, int]:
        cur = self.scan()
        self.last_files = cur
        total_bytes = sum(len(v.encode("utf-8")) for v in cur.values())
        return {"files": cur, "replace": True}, len(cur), total_bytes

    def build_delta_payload(self) -> dict[str, Any] | None:
        cur = self.scan()
        changed = {k: v for k, v in cur.items() if self.last_files.get(k) != v}
        deleted = [k for k in self.last_files if k not in cur]
        self.last_files = cur
        if not changed and not deleted:
            return None
        return {"mode": "delta", "files": changed, "deleted": deleted}


def _post_sync(gateway_url: str, token: str, workspace_id: str, payload: dict[str, Any]) -> dict[str, Any]:
    raw = json.dumps(payload).encode("utf-8")
    last_exc: Exception | None = None
    for attempt in range(3):
        req = urllib.request.Request(
            f"{gateway_url.rstrip('/')}/v1/workspaces/{workspace_id}/sync",
            data=raw,
            headers={
                "Authorization": f"Bearer {token}",
                "Content-Type": "application/json",
                "Accept": "application/json",
                "User-Agent": "ecocoder-cli/1.0",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(req, timeout=60) as resp:
                return json.loads(resp.read().decode("utf-8"))
        except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, OSError) as exc:
            last_exc = exc
            if isinstance(exc, urllib.error.HTTPError) and exc.code < 500:
                raise
            time.sleep(1.5 * (attempt + 1))
    assert last_exc is not None
    raise last_exc


class _ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True


def start_local_shim_proxy(
    *,
    gateway_url: str,
    api_key: str,
    workspace_dir: Path | None,
    run_id: str,
    max_run_usd: float | None = None,
    quiet: bool = False,
) -> tuple[_ThreadedHTTPServer, int, str]:
    """Start localhost HTTP proxy injecting auth, run_id, and delta workspace syncs."""
    parsed = urllib.parse.urlparse(gateway_url)
    up_host = parsed.hostname or "api.leanlm.ai"
    up_port = parsed.port or (443 if parsed.scheme == "https" else 80)
    use_https = parsed.scheme == "https"
    ssl_ctx = ssl.create_default_context() if use_https else None

    ws_cache: WorkspaceSyncCache | None = None
    ws_id = ""
    sync_lock = threading.Lock()
    if workspace_dir is not None and workspace_dir.is_dir():
        resolved_ws = workspace_dir.resolve()
        ws_hash = hashlib.sha256(str(resolved_ws).encode("utf-8")).hexdigest()[:16]
        slug = "".join(c if c.isalnum() or c in "-_" else "-" for c in resolved_ws.name).strip("-")[:24] or "repo"
        ws_id = f"ws-{slug}-{ws_hash}"
        ws_cache = WorkspaceSyncCache(resolved_ws)
        init_payload, n_files, n_bytes = ws_cache.build_initial_payload()
        if n_files > 0:
            if not quiet:
                sys.stderr.write(
                    f"[ecocoder] Syncing {n_files} source files ({n_bytes / 1024.0:.1f} KiB) -> {ws_id}...\n"
                )
            _post_sync(gateway_url, api_key, ws_id, init_payload)

    session_id = f"sess-{run_id}"

    class _Handler(http.server.BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"

        def log_message(self, format: str, *args: Any) -> None:  # noqa: A002
            return

        def _send_json_err(self, code: int, err_type: str, msg: str) -> None:
            raw = json.dumps({"type": "error", "error": {"type": err_type, "message": msg}}).encode("utf-8")
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(raw)))
            self.send_header("Connection", "close")
            self.end_headers()
            self.wfile.write(raw)
            self.close_connection = True

        def _proxy(self) -> None:
            cl = int(self.headers.get("Content-Length") or 0)
            body = self.rfile.read(cl) if cl > 0 else (b"" if self.command in ("POST", "PUT", "PATCH") else None)

            if self.command == "POST" and ws_cache is not None and ws_id and not self.path.startswith("/v1/workspaces/"):
                with sync_lock:
                    try:
                        delta = ws_cache.build_delta_payload()
                        if delta is not None:
                            _post_sync(gateway_url, api_key, ws_id, delta)
                    except Exception as exc:
                        self._send_json_err(503, "workspace_sync_error", f"Workspace delta sync failed: {exc}")
                        return

            fwd: dict[str, str] = {}
            for k, v in self.headers.items():
                lk = k.lower()
                if lk in ("host", "authorization", "x-api-key", "content-length", "connection", "transfer-encoding"):
                    continue
                if lk.startswith("x-cg-"):
                    continue
                if lk == "user-agent" and v.strip().lower().startswith("python-urllib"):
                    continue
                fwd[k] = v
            if "user-agent" not in {k.lower() for k in fwd}:
                fwd["User-Agent"] = "ecocoder-cli/1.0"
            fwd["Host"] = up_host
            fwd["Authorization"] = f"Bearer {api_key}"
            fwd["x-leanlm-run-id"] = run_id
            if "x-session-id" not in {k.lower() for k in fwd}:
                fwd["x-session-id"] = session_id
            if ws_id:
                fwd["x-workspace-id"] = ws_id
            if max_run_usd is not None and max_run_usd > 0:
                fwd["x-leanlm-max-run-usd"] = f"{max_run_usd:.4f}"
            if body is not None:
                fwd["Content-Length"] = str(len(body))

            conn: http.client.HTTPConnection
            if use_https:
                conn = http.client.HTTPSConnection(up_host, up_port, timeout=600, context=ssl_ctx)
            else:
                conn = http.client.HTTPConnection(up_host, up_port, timeout=600)
            try:
                conn.request(self.command, self.path, body=body, headers=fwd)
                up_resp = conn.getresponse()
                self.send_response(up_resp.status)
                is_sse = False
                has_len = False
                for hk, hv in up_resp.getheaders():
                    lhk = hk.lower()
                    if lhk in ("transfer-encoding", "connection", "keep-alive"):
                        continue
                    if lhk == "content-type" and "text/event-stream" in hv.lower():
                        is_sse = True
                    if lhk == "content-length":
                        has_len = True
                    self.send_header(hk, hv)
                if is_sse or not has_len:
                    self.send_header("Connection", "close")
                    self.end_headers()
                    while True:
                        chunk = up_resp.read(4096)
                        if not chunk:
                            break
                        self.wfile.write(chunk)
                        self.wfile.flush()
                    self.close_connection = True
                else:
                    resp_bytes = up_resp.read()
                    self.send_header("Connection", "close")
                    self.end_headers()
                    if resp_bytes:
                        self.wfile.write(resp_bytes)
                        self.wfile.flush()
                    self.close_connection = True
            except (BrokenPipeError, ConnectionResetError):
                self.close_connection = True
            except Exception as exc:
                self._send_json_err(502, "bad_gateway", f"Upstream gateway connection error: {exc}")
            finally:
                conn.close()

        do_GET = _proxy
        do_POST = _proxy
        do_PUT = _proxy
        do_DELETE = _proxy

    srv = _ThreadedHTTPServer(("127.0.0.1", 0), _Handler)
    port = int(srv.server_address[1])
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    return srv, port, ws_id


def _parse_kv_overrides(items: list[str] | None) -> dict[str, str]:
    out: dict[str, str] = {}
    for raw in items or []:
        if "=" not in raw:
            raise ValueError(f"Expected KEY=VALUE in --set, got {raw!r}")
        k, v = raw.split("=", 1)
        out[k.strip()] = v.strip()
    return out


def format_energy_report(data: dict[str, Any], *, show_methodology: bool = False) -> str:
    lines: list[str] = []
    budget = data.get("budget") or {}
    actual = data.get("actual") or {}
    cov = data.get("coverage") or {}
    assump = data.get("assumptions") or {}

    lines.append("=== EcoCoder Budget & Measured Energy ===")
    if budget:
        lines.append(
            f"Budget      : ${float(budget.get('spent_usd') or 0):.4f} spent / "
            f"${float(budget.get('granted_usd') or 0):.2f} limit "
            f"(${float(budget.get('available_usd') or 0):.4f} available)"
        )
    turns = int(actual.get("turns") or 0)
    unc_in = int(actual.get("uncached_input_tokens") or 0)
    cac_in = int(actual.get("cached_input_tokens") or 0)
    out_tok = int(actual.get("output_tokens") or 0)
    gpu_wh = float(actual.get("gpu_wh") or 0.0)
    fac_wh = float(actual.get("facility_wh") or 0.0)
    gpu_j = float(actual.get("gpu_joules") or 0.0)
    pue = float(assump.get("pue") or 1.2)
    lines.append(
        f"Workload    : {turns} settled turns | {unc_in:,} uncached in | {cac_in:,} cached in | {out_tok:,} output tokens"
    )
    lines.append(
        f"EcoCoder    : {gpu_wh:.4f} Wh NeuralWatt metered ({gpu_j:,.1f} J, {int(cov.get('metered_turns') or 0)}/{turns} turns) "
        f"| {fac_wh:.4f} Wh w/ PUE={pue:.2f}"
    )

    by_model = data.get("by_model") or []
    if by_model:
        parts = [
            f"{m.get('model')}: {int(m.get('turns') or 0)}t / {float(m.get('energyJoules') or 0) / 3600.0:.4f} Wh"
            for m in by_model
        ]
        lines.append(f"Tier Split  : {' | '.join(parts)}")

    lines.append("")
    lines.append("=== Counterfactual Frontier Energy Comparison (Same Tokens & Turn KV-Cache Traffic) ===")
    hdr = (
        f"{'MODEL':<32} {'ACTIVE / TOTAL':<16} "
        f"{'METHOD A: GPU Wh (opt / cen / con)':<36} {'METHOD B: EcoLogits Wh':<23} {'VS ECOCODER'}"
    )
    lines.append(hdr)
    lines.append("-" * len(hdr))
    for cf in data.get("counterfactuals") or []:
        ma = cf.get("method_a_token_physics") or {}
        mb = cf.get("method_b_ecologits") or {}
        act_r = cf.get("active_params_b_range") or [0, 0, 0]
        tot_c = float(cf.get("total_params_b_central") or 0)
        act_str = f"{act_r[1]:g}B / {tot_c:g}B"
        ma_opt_wh = float(ma.get("gpu_joules_optimistic") or 0) / 3600.0
        ma_cen_wh = float(ma.get("gpu_joules_central") or 0) / 3600.0
        ma_con_wh = float(ma.get("gpu_joules_conservative") or 0) / 3600.0
        ma_col = f"{ma_opt_wh:.3f} / {ma_cen_wh:.3f} / {ma_con_wh:.3f} Wh"
        mb_wh = float(mb.get("facility_wh_central") or 0)
        mb_flag = "*" if mb.get("extrapolated_beyond_fit") else ""
        mb_col = f"{mb_wh:.3f} Wh ({int(mb.get('gpu_count_central') or 1)} GPU){mb_flag}"
        mult = cf.get("vs_ecocoder_multiple")
        pct = cf.get("vs_ecocoder_energy_saved_pct")
        vs_col = f"{mult}x ({pct:+.1f}% saved)" if mult is not None and pct is not None else "n/a (0 J baseline)"
        lines.append(f"{str(cf.get('label')):<32} {act_str:<16} {ma_col:<36} {mb_col:<23} {vs_col}")

    lines.append(
        "* Note: Method A models uncached prefill + cached KV load + active decode + exact turn KV-bandwidth "
        "(s_kappa = s^(2/3)). Method B is published EcoLogits 0.11.x (output-only; * = extrapolated >16 GPUs at fixed batch=64)."
    )

    if show_methodology:
        lines.append("")
        lines.append("=== Open Calibration Questions for Energy-Tracker Reviewers ===")
        for q in data.get("methodology_questions") or []:
            lines.append(f"  {q}")
        lines.append("")
        lines.append(
            "Tip: Re-run with custom priors, e.g. "
            "`ecocoder stats --set pue=1.12 --set frontier_active_b=250 --set quant_bits=8`"
        )
    return "\n".join(lines)


def _print_run_receipt_stderr(gateway_url: str, api_key: str, run_id: str) -> None:
    try:
        time.sleep(0.35)
        summary = _api_get_json(gateway_url, api_key, "/v1/energy/summary", {"run_id": run_id})
        act = summary.get("actual") or {}
        turns = int(act.get("turns") or 0)
        if turns <= 0:
            return
        bud = summary.get("budget") or {}
        cfs = {c.get("model_id"): c for c in (summary.get("counterfactuals") or [])}
        m3t = (cfs.get("frontier-3t-moe") or {}).get("vs_ecocoder_multiple")
        mopus = (cfs.get("claude-opus-5-5") or {}).get("vs_ecocoder_multiple")
        gpu_wh = float(act.get("gpu_wh") or 0.0)
        avail = float(bud.get("available_usd") or 0.0)
        spent = float(bud.get("spent_usd") or 0.0)
        cmp_parts = []
        if m3t:
            cmp_parts.append(f"{m3t}x less energy than 3T-MoE")
        if mopus:
            cmp_parts.append(f"{mopus}x less than Opus 5.5")
        cmp_str = f" ({', '.join(cmp_parts)})" if cmp_parts else ""
        sys.stderr.write(
            f"\n[ecocoder] Run {run_id}: {turns} turns | {gpu_wh:.4f} Wh NeuralWatt metered{cmp_str} "
            f"| Account spent: ${spent:.4f} (${avail:.2f} remaining)\n"
        )
    except Exception:
        return


def cmd_login(args: argparse.Namespace) -> int:
    gw = resolve_gateway_url(args.gateway_url)
    raw_key = (args.key or os.environ.get("ECOCODER_API_KEY") or "").strip()
    if not raw_key:
        raw_key = getpass.getpass("Paste your EcoCoder API key (eco_live_...): ").strip()
    if not raw_key:
        print("Error: API key cannot be empty.", file=sys.stderr)
        return 1
    who = _api_get_json(gw, raw_key, "/v1/whoami")
    status = _api_get_json(gw, raw_key, "/v1/billing/status")
    _save_private_text(KEY_FILE, raw_key)
    _save_private_text(GATEWAY_FILE, gw)
    avail = float(status.get("availableMicros") or 0) / 1_000_000.0
    granted = float(status.get("totalGrantedMicros") or 0) / 1_000_000.0
    print(f"Saved key to {KEY_FILE} (0600).")
    print(
        f"Authenticated: tenant={who.get('tenant')} principal={who.get('principal')} "
        f"| Available budget: ${avail:.2f} / ${granted:.2f}"
    )
    return 0


def cmd_check(args: argparse.Namespace) -> int:
    gw = resolve_gateway_url(args.gateway_url)
    key, src = resolve_api_key()
    who = _api_get_json(gw, key, "/v1/whoami")
    status = _api_get_json(gw, key, "/v1/billing/status")
    if args.json:
        print(json.dumps({"whoami": who, "billing": status, "key_source": src}, indent=2))
        return 0
    avail = float(status.get("availableMicros") or 0) / 1_000_000.0
    spent = float(status.get("totalSettledMicros") or 0) / 1_000_000.0
    granted = float(status.get("totalGrantedMicros") or 0) / 1_000_000.0
    print(
        f"OK ({src}): tenant={who.get('tenant')} principal={who.get('principal')} "
        f"| Budget: ${spent:.4f} spent / ${granted:.2f} limit (${avail:.4f} remaining)"
    )
    return 0


def cmd_stats(args: argparse.Namespace) -> int:
    gw = resolve_gateway_url(args.gateway_url)
    key, _ = resolve_api_key()
    query = _parse_kv_overrides(args.set)
    if args.run_id:
        query["run_id"] = args.run_id
    summary = _api_get_json(gw, key, "/v1/energy/summary", query)
    if args.json:
        print(json.dumps(summary, indent=2))
    else:
        print(format_energy_report(summary, show_methodology=args.methodology))
    return 0


def cmd_claude(args: argparse.Namespace) -> int:
    claude_bin = shutil.which("claude")
    if not claude_bin:
        print("Error: `claude` CLI not found on PATH.", file=sys.stderr)
        return 1
    gw = resolve_gateway_url(args.gateway_url)
    key, _ = resolve_api_key()
    ws_dir = None if args.no_sync else Path(args.workspace_dir or os.getcwd())
    run_id = args.run_id or f"claude-{uuid.uuid4().hex[:10]}"
    srv, port, _ = start_local_shim_proxy(
        gateway_url=gw,
        api_key=key,
        workspace_dir=ws_dir,
        run_id=run_id,
        max_run_usd=args.max_usd,
    )
    try:
        child_env = os.environ.copy()
        child_env.pop("ANTHROPIC_API_KEY", None)
        child_env["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{port}"
        child_env["ANTHROPIC_AUTH_TOKEN"] = "ecocoder-local-proxy"
        extra = list(args.agent_args or [])
        if extra and extra[0] == "--":
            extra = extra[1:]
        cmd = [claude_bin]
        if "--model" not in extra:
            cmd.extend(["--model", DEFAULT_MODEL])
        cmd.extend(extra)
        proc = subprocess.run(cmd, env=child_env, check=False)
        return int(proc.returncode)
    finally:
        srv.shutdown()
        srv.server_close()
        _print_run_receipt_stderr(gw, key, run_id)


def _build_pi_models_dict(base_url: str, api_key: str) -> dict[str, Any]:
    return {
        "providers": {
            "ecocoder": {
                "baseUrl": base_url,
                "api": "openai-completions",
                "apiKey": api_key,
                "authHeader": True,
                "models": [
                    {"id": "nw:ecocoder-3tier"},
                    {"id": "nw:ecocoder-flint"},
                ],
            }
        }
    }


def cmd_setup_pi(args: argparse.Namespace) -> int:
    gw = resolve_gateway_url(args.gateway_url)
    key, _ = resolve_api_key()
    cfg = _build_pi_models_dict(f"{gw}/v1", key)
    target = Path.home() / ".pi" / "agent" / "models.json"
    if not args.write:
        print(f"# Preview for {target} (pass --write to merge into ~/.pi/agent/models.json):")
        print(json.dumps(cfg, indent=2))
        return 0
    target.parent.mkdir(parents=True, exist_ok=True)
    merged: dict[str, Any] = {"providers": {}}
    if target.is_file():
        try:
            existing = json.loads(target.read_text(encoding="utf-8"))
            if isinstance(existing, dict):
                merged.update(existing)
                if not isinstance(merged.get("providers"), dict):
                    merged["providers"] = {}
        except Exception:
            pass
    merged["providers"]["ecocoder"] = cfg["providers"]["ecocoder"]
    _save_private_text(target, json.dumps(merged, indent=2))
    print(f"Configured provider `ecocoder` in {target} (0600). Run: pi --provider ecocoder --model {DEFAULT_MODEL}")
    return 0


def cmd_pi(args: argparse.Namespace) -> int:
    pi_bin = shutil.which("pi")
    if not pi_bin:
        print("Error: `pi` (`pi-coding-agent`) not found on PATH. Use `ecocoder setup-pi` or install pi.", file=sys.stderr)
        return 1
    gw = resolve_gateway_url(args.gateway_url)
    key, _ = resolve_api_key()
    ws_dir = None if args.no_sync else Path(args.workspace_dir or os.getcwd())
    run_id = args.run_id or f"pi-{uuid.uuid4().hex[:10]}"
    srv, port, _ = start_local_shim_proxy(
        gateway_url=gw,
        api_key=key,
        workspace_dir=ws_dir,
        run_id=run_id,
        max_run_usd=args.max_usd,
    )
    pi_tmp_dir = Path(tempfile.mkdtemp(prefix="ecocoder_pi_"))
    try:
        os.chmod(pi_tmp_dir, 0o700)
        user_pi_dir = Path(os.environ.get("PI_CODING_AGENT_DIR") or (Path.home() / ".pi" / "agent"))
        for fname in ("settings.json", "auth.json"):
            src_f = user_pi_dir / fname
            if src_f.is_file():
                shutil.copy2(src_f, pi_tmp_dir / fname)
        models_cfg = _build_pi_models_dict(f"http://127.0.0.1:{port}/v1", "ecocoder-local-proxy")
        if (user_pi_dir / "models.json").is_file():
            try:
                orig_m = json.loads((user_pi_dir / "models.json").read_text(encoding="utf-8"))
                if isinstance(orig_m, dict) and isinstance(orig_m.get("providers"), dict):
                    orig_m["providers"]["ecocoder"] = models_cfg["providers"]["ecocoder"]
                    models_cfg = orig_m
            except Exception:
                pass
        (pi_tmp_dir / "models.json").write_text(json.dumps(models_cfg, indent=2), encoding="utf-8")

        child_env = os.environ.copy()
        child_env["PI_CODING_AGENT_DIR"] = str(pi_tmp_dir)
        extra = list(args.agent_args or [])
        if extra and extra[0] == "--":
            extra = extra[1:]
        cmd = [pi_bin]
        if "--provider" not in extra:
            cmd.extend(["--provider", "ecocoder"])
        if "--model" not in extra:
            cmd.extend(["--model", DEFAULT_MODEL])
        cmd.extend(extra)
        proc = subprocess.run(cmd, env=child_env, check=False)
        return int(proc.returncode)
    finally:
        srv.shutdown()
        srv.server_close()
        shutil.rmtree(pi_tmp_dir, ignore_errors=True)
        _print_run_receipt_stderr(gw, key, run_id)


def cmd_delegate(args: argparse.Namespace) -> int:
    gw = resolve_gateway_url(args.gateway_url)
    key, _ = resolve_api_key()
    ws_dir = None if args.no_sync else Path(args.workspace_dir or os.getcwd())
    run_id = args.run_id or f"del-{uuid.uuid4().hex[:10]}"

    runner = args.runner
    if runner == "auto":
        if shutil.which("claude"):
            runner = "claude"
        elif shutil.which("pi"):
            runner = "pi"
        else:
            runner = "http"

    srv, port, _ = start_local_shim_proxy(
        gateway_url=gw,
        api_key=key,
        workspace_dir=ws_dir,
        run_id=run_id,
        max_run_usd=args.max_usd,
        quiet=args.json,
    )
    output_text = ""
    exit_code = 0
    try:
        if runner == "claude":
            claude_bin = shutil.which("claude")
            if not claude_bin:
                raise RuntimeError("`claude` CLI not found on PATH")
            child_env = os.environ.copy()
            child_env.pop("ANTHROPIC_API_KEY", None)
            child_env["ANTHROPIC_BASE_URL"] = f"http://127.0.0.1:{port}"
            child_env["ANTHROPIC_AUTH_TOKEN"] = "ecocoder-local-proxy"
            proc = subprocess.run(
                [claude_bin, "--model", DEFAULT_MODEL, "-p", args.prompt],
                env=child_env,
                capture_output=args.json,
                text=True,
                check=False,
            )
            exit_code = int(proc.returncode)
            output_text = (proc.stdout or "").strip() if args.json else ""
        elif runner == "pi":
            pi_bin = shutil.which("pi")
            if not pi_bin:
                raise RuntimeError("`pi` CLI not found on PATH")
            pi_tmp = Path(tempfile.mkdtemp(prefix="ecocoder_pi_del_"))
            try:
                (pi_tmp / "models.json").write_text(
                    json.dumps(_build_pi_models_dict(f"http://127.0.0.1:{port}/v1", "ecocoder-local-proxy")),
                    encoding="utf-8",
                )
                child_env = os.environ.copy()
                child_env["PI_CODING_AGENT_DIR"] = str(pi_tmp)
                proc = subprocess.run(
                    [pi_bin, "--provider", "ecocoder", "--model", DEFAULT_MODEL, "-p", args.prompt],
                    env=child_env,
                    capture_output=args.json,
                    text=True,
                    check=False,
                )
                exit_code = int(proc.returncode)
                output_text = (proc.stdout or "").strip() if args.json else ""
            finally:
                shutil.rmtree(pi_tmp, ignore_errors=True)
        else:
            body = json.dumps(
                {"model": DEFAULT_MODEL, "messages": [{"role": "user", "content": args.prompt}]}
            ).encode("utf-8")
            req = urllib.request.Request(
                f"http://127.0.0.1:{port}/v1/chat/completions",
                data=body,
                headers={"Content-Type": "application/json"},
                method="POST",
            )
            with urllib.request.urlopen(req, timeout=300) as resp:
                parsed = json.loads(resp.read().decode("utf-8"))
            output_text = str((((parsed.get("choices") or [{}])[0]).get("message") or {}).get("content") or "")
            if not args.json:
                print(output_text)
    finally:
        srv.shutdown()
        srv.server_close()

    if args.json:
        time.sleep(0.35)
        energy = _api_get_json(gw, key, "/v1/energy/summary", {"run_id": run_id})
        print(json.dumps({"run_id": run_id, "exit_code": exit_code, "output": output_text, "energy": energy}, indent=2))
    else:
        _print_run_receipt_stderr(gw, key, run_id)
    return exit_code


def cmd_install_subagent(args: argparse.Namespace) -> int:
    script_abs = Path(__file__).resolve()
    base_dir = (Path.home() / ".claude" / "agents") if args.global_agent else (Path.cwd() / ".claude" / "agents")
    base_dir.mkdir(parents=True, exist_ok=True)
    agent_file = base_dir / "ecocoder.md"
    md = f"""---
name: ecocoder
description: Delegate bounded implementation, bug-fix, or test-writing tasks to EcoCoder (3-tier CodeGraph Slicer + Governor on NeuralWatt with live GPU energy & $25 cap tracking).
tools: Bash, Read, Grep, Glob
omitClaudeMd: true
---

You are a lightweight delegation bridge to **EcoCoder**.
Execute the delegated coding task in the current repository by running:

```bash
python3 "{script_abs}" delegate "<concise actionable task brief with file paths and acceptance test command>" --max-usd {args.max_usd:.2f}
```

After it finishes, inspect `git status` / `git diff`, run the requested verification command if needed, and report back:
1. Files changed and verification result
2. The `[ecocoder] Run ...` energy (Wh) and spend receipt printed at completion.
"""
    agent_file.write_text(md, encoding="utf-8")
    print(f"Installed Claude Code subagent -> {agent_file}")
    print("\nYou can also call EcoCoder directly as a delegated agent from Python / OpenAI SDK workflows:")
    print(
        f'  subprocess.run(["python3", "{script_abs}", "delegate", "Implement feature X", "--max-usd", "{args.max_usd:.2f}", "--json"])'
    )
    return 0


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description="EcoCoder Reviewer CLI: Router Shim, Pi, Delegation & Frontier Energy Comparator")
    p.add_argument("--gateway-url", default="", help=f"Gateway base URL (default: {DEFAULT_GATEWAY_URL})")
    sub = p.add_subparsers(dest="command", required=True)

    sp_login = sub.add_parser("login", help="Save reviewer API key (~/.ecocoder/key, 0600) and verify budget")
    sp_login.add_argument("--key", default="", help="EcoCoder API key (eco_live_...)")
    sp_login.set_defaults(func=cmd_login)

    sp_chk = sub.add_parser("check", help="Verify API key and remaining $25.00 credit balance")
    sp_chk.add_argument("--json", action="store_true")
    sp_chk.set_defaults(func=cmd_check)

    sp_stats = sub.add_parser(
        "stats",
        help="Compare measured GPU/Facility Wh against 3T Frontier (MoE & Dense) and Claude Opus/Sonnet/Haiku",
    )
    sp_stats.add_argument("--run-id", default="", help="Filter to a single run_id")
    sp_stats.add_argument(
        "--set",
        action="append",
        default=[],
        metavar="KEY=VAL",
        help="Override physics assumptions (pue, frontier_total_b, frontier_active_b, quant_bits, batch_size, kappa_exp)",
    )
    sp_stats.add_argument("--methodology", action="store_true", help="Print equations and reviewer calibration questions")
    sp_stats.add_argument("--json", action="store_true")
    sp_stats.set_defaults(func=cmd_stats)

    sp_cl = sub.add_parser("claude", help="Launch Claude Code routed through EcoCoder (leaves daily `claude` untouched)")
    sp_cl.add_argument("--workspace-dir", default="", help="Workspace directory to sync (default: cwd)")
    sp_cl.add_argument("--no-sync", action="store_true", help="Disable workspace source sync")
    sp_cl.add_argument("--max-usd", type=float, default=None, help="Optional per-session spend cap in USD")
    sp_cl.add_argument("--run-id", default="")
    sp_cl.add_argument("agent_args", nargs=argparse.REMAINDER, help="Arguments passed through to `claude`")
    sp_cl.set_defaults(func=cmd_claude)

    sp_pi = sub.add_parser("pi", help="Launch `pi` (`pi-coding-agent`) routed through EcoCoder with workspace sync")
    sp_pi.add_argument("--workspace-dir", default="", help="Workspace directory to sync (default: cwd)")
    sp_pi.add_argument("--no-sync", action="store_true", help="Disable workspace source sync")
    sp_pi.add_argument("--max-usd", type=float, default=None, help="Optional per-session spend cap in USD")
    sp_pi.add_argument("--run-id", default="")
    sp_pi.add_argument("agent_args", nargs=argparse.REMAINDER, help="Arguments passed through to `pi`")
    sp_pi.set_defaults(func=cmd_pi)

    sp_spi = sub.add_parser("setup-pi", help="Preview or merge EcoCoder provider into ~/.pi/agent/models.json")
    sp_spi.add_argument("--write", action="store_true", help="Merge into ~/.pi/agent/models.json (mode 0600)")
    sp_spi.set_defaults(func=cmd_setup_pi)

    sp_del = sub.add_parser("delegate", help="Run a one-shot bounded coding task as a delegated subagent")
    sp_del.add_argument("prompt", help="Actionable coding task prompt")
    sp_del.add_argument("--runner", choices=("auto", "claude", "pi", "http"), default="auto")
    sp_del.add_argument("--max-usd", type=float, default=1.50, help="Hard per-delegation USD cap (default: 1.50)")
    sp_del.add_argument("--workspace-dir", default="")
    sp_del.add_argument("--no-sync", action="store_true")
    sp_del.add_argument("--run-id", default="")
    sp_del.add_argument("--json", action="store_true", help="Emit structured JSON with output + energy summary")
    sp_del.set_defaults(func=cmd_delegate)

    sp_sub = sub.add_parser("install-subagent", help="Install `.claude/agents/ecocoder.md` for workflow delegation")
    sp_sub.add_argument("--global", dest="global_agent", action="store_true", help="Install in ~/.claude/agents/")
    sp_sub.add_argument("--max-usd", type=float, default=1.50, help="Default per-task cap in subagent prompt")
    sp_sub.set_defaults(func=cmd_install_subagent)

    return p


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        return int(args.func(args))
    except urllib.error.HTTPError as exc:
        raw = exc.read().decode("utf-8", errors="replace")
        msg = raw
        try:
            msg = str((json.loads(raw).get("error") or {}).get("message") or raw)
        except Exception:
            pass
        print(f"[ecocoder] HTTP {exc.code}: {msg}", file=sys.stderr)
        return 1
    except Exception as exc:
        print(f"[ecocoder] error: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
