#!/usr/bin/env python3
"""
Chairman AI agent — conversational + autonomous execution.

Modes:
  python3 agent.py --chat "message"          one-shot conversational reply
  python3 agent.py --chat-stdin              read message from stdin
  python3 agent.py --heartbeat               run one autonomous heartbeat cycle

Uses Claude with server-side tool use (bash, text_editor, web_search).
Loops until the model stops calling tools.
"""
import argparse
import json
import os
import subprocess
import sys
import time
import urllib.parse
import urllib.request
import urllib.error
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent
REPO = ROOT.parent
MEMORY_FILE = REPO / "sovereign-wiki" / "memory" / "CHAIRMAN-MEMORY.md"
INBOX = ROOT / "inbox"
DONE = ROOT / "done"
LOG_DIR = ROOT / "logs"
HEARTBEAT_LOG = LOG_DIR / "heartbeat.log"
CHAT_LOG = LOG_DIR / "chat.log"

sys.path.insert(0, str(ROOT))
from prompt import SYSTEM_PROMPT  # noqa

ENV_FILE = REPO / "content-os" / "config" / ".env"


def load_env():
    if not ENV_FILE.exists():
        return
    for line in ENV_FILE.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        v = v.strip().strip('"').strip("'")
        if not os.environ.get(k.strip()):
            os.environ[k.strip()] = v


load_env()
API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
if not API_KEY:
    print("ERROR: ANTHROPIC_API_KEY not set", file=sys.stderr)
    sys.exit(1)

MODEL = os.environ.get("CHAIRMAN_MODEL", "claude-sonnet-5")
# Opt-in usage emission: when CHAIRMAN_EMIT_USAGE=1, agent_loop prints one
# machine-readable usage line to stdout after the final text. Without the env
# var, behavior is byte-identical (heartbeat, CLI, subagent.py unaffected).
EMIT_USAGE = os.environ.get("CHAIRMAN_EMIT_USAGE") == "1"
API_URL = "https://api.anthropic.com/v1/messages"
MAX_ITERATIONS = 12
MAX_TOKENS = 8192


# ------------------------------------------------------------ live grounding
CRM_SNAPSHOT = LOG_DIR / ".crm_snapshot.json"
CRM_SNAPSHOT_TTL = 600      # serve cached block without refetching (seconds)
CRM_SNAPSHOT_MAX_AGE = 86400  # never serve a snapshot older than a day


def live_crm_context(timeout=10):
    """Fetch real empire numbers from the Sovereign CRM and return a system
    prompt block. Uses the anon-whitelisted read RPCs (lockdown-safe, no
    service key needed). The dashboard stats RPC aggregates 175K+ rows and is
    intermittently slow, so the block is cached to disk: fresh cache is served
    without a fetch, and a failed fetch falls back to the last snapshot (its
    embedded timestamp shows the age). Fails silent — an unreachable CRM must
    never block the Chairman."""
    now = time.time()
    cached = None
    try:
        c = json.loads(CRM_SNAPSHOT.read_text())
        if now - c["ts"] <= CRM_SNAPSHOT_MAX_AGE:
            cached = c
        if cached and now - c["ts"] <= CRM_SNAPSHOT_TTL:
            return cached["block"]
    except Exception:
        pass

    base = os.environ.get("SUPABASE_URL", "").split("/rest/")[0]
    key = os.environ.get("SUPABASE_ANON_KEY", "")
    if not base or not key:
        return cached["block"] if cached else ""

    def rpc(name):
        req = urllib.request.Request(
            f"{base}/rest/v1/rpc/{name}",
            data=b"{}",
            headers={"apikey": key, "Authorization": f"Bearer {key}",
                     "Content-Type": "application/json"},
            method="POST",
        )
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read().decode())

    try:
        s = rpc("crm_dashboard_stats")
        tiers = s.get("tiers", {})
        plats = sorted((s.get("platforms") or {}).items(),
                       key=lambda kv: -kv[1])[:6]
        block = (
            "\n\nLIVE EMPIRE DATA (Sovereign CRM, fetched "
            f"{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')} — "
            "TRUST THESE NUMBERS over any figure quoted elsewhere in this "
            "prompt; historical anchors below are for trajectory only):\n"
            f"- Contacts: {s.get('total_contacts'):,} · paying {s.get('paying_contacts'):,}"
            f" · multi-platform {s.get('multi_platform_count'):,}\n"
            f"- Revenue: net ${s.get('total_revenue'):,.0f} · gross ${s.get('gross_revenue'):,.0f}"
            f" · avg LTV ${s.get('avg_ltv'):,.0f}\n"
            f"- Tiers: sovereign {tiers.get('sovereign'):,} · hot {tiers.get('hot'):,}"
            f" · warm {tiers.get('warm'):,} · cold {tiers.get('cold'):,}\n"
            f"- Hot 1000: {s.get('hot_1000_count'):,} · Super 10K: {s.get('super_10000_count'):,}\n"
            f"- Top platforms: " + ", ".join(f"{k} {v:,}" for k, v in plats) + "\n"
            "- CAVEAT: purchase-level rows frozen since 2026-04-15 (sync cron "
            "was never installed); platform LTV totals are trustworthy, "
            "recent per-sale detail is not — flag this when reasoning about "
            "current-month revenue."
        )
        try:
            CRM_SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
            CRM_SNAPSHOT.write_text(json.dumps({"ts": now, "block": block}))
        except Exception:
            pass
        return block
    except Exception:
        if os.environ.get("CHAIRMAN_DEBUG") == "1":
            import traceback
            traceback.print_exc()
        if cached:
            return cached["block"]
        return (
            "\n\nLIVE EMPIRE DATA: unavailable this session (CRM fetch "
            "failed). Do not quote contact/revenue figures as current — "
            "label any number you use as historical."
        )

# ---------------------------------------------------------------- providers
# Non-Anthropic models run through OpenAI-compatible chat completions
# with a full function-calling tool loop (same local execute_tool hands
# as the Claude path: bash, files, web_search, text_19keys).
# Model ids verified live against each provider's /models on 2026-07-02.
OPENAI_COMPAT = {
    # dashboard model id -> (env key name, endpoint, remote model id)
    "openrouter/openai/gpt-5.5": (
        "OPENROUTER_API_KEY",
        "https://openrouter.ai/api/v1/chat/completions",
        "openai/gpt-5.5",
    ),
    "openrouter/z-ai/glm-5.2": (
        "OPENROUTER_API_KEY",
        "https://openrouter.ai/api/v1/chat/completions",
        "z-ai/glm-5.2",
    ),
    "deepseek-v4-flash": (
        "DEEPSEEK_API",
        "https://api.deepseek.com/chat/completions",
        "deepseek-v4-flash",
    ),
    "deepseek-v4-pro": (
        "DEEPSEEK_API",
        "https://api.deepseek.com/chat/completions",
        "deepseek-v4-pro",
    ),
}


def _openai_tools():
    """TOOLS (Anthropic name/description/input_schema) in OpenAI format."""
    return [
        {
            "type": "function",
            "function": {
                "name": t["name"],
                "description": t.get("description", ""),
                "parameters": t.get(
                    "input_schema", {"type": "object", "properties": {}}
                ),
            },
        }
        for t in TOOLS
    ]


def _openai_post(url, key, payload):
    """POST one chat completions request; returns parsed JSON or raises."""
    req = urllib.request.Request(
        url,
        data=json.dumps(payload).encode(),
        headers={
            "Authorization": f"Bearer {key}",
            "content-type": "application/json",
        },
    )
    with urllib.request.urlopen(req, timeout=180) as r:
        return json.loads(r.read())


def openai_compat_call(model_id, system, user_msg):
    """Tool-loop chat against an OpenAI-compatible provider.

    Runs up to MAX_ITERATIONS rounds of OpenAI function calling; each
    tool_call is executed locally through execute_tool, so non-Claude
    models keep the same hands as the Claude path. Returns (text, usage)
    with usage keys matching the Anthropic names so the dashboard ledger
    stays uniform. Cache fields are always 0 here. If the provider
    rejects function calling on the first request, degrades to plain
    chat once and flags that in the reply.
    """
    env_key, url, remote_id = OPENAI_COMPAT[model_id]
    key = os.environ.get(env_key, "")
    if not key:
        return f"(error: {env_key} not set; cannot reach {remote_id})", None
    openai_tools = _openai_tools()
    messages = [
        {"role": "system", "content": system},
        {"role": "user", "content": user_msg},
    ]
    usage_totals = {
        "input_tokens": 0,
        "output_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation_input_tokens": 0,
    }
    text_parts = []
    tools_enabled = True
    degraded = False
    first_call = True
    for _ in range(MAX_ITERATIONS):
        payload = {
            "model": remote_id,
            "max_tokens": MAX_TOKENS,
            "messages": messages,
        }
        if tools_enabled:
            payload["tools"] = openai_tools
            payload["tool_choice"] = "auto"
        try:
            resp = _openai_post(url, key, payload)
        except urllib.error.HTTPError as e:
            body = e.read().decode("utf-8", "replace")
            low = body.lower()
            if (
                first_call
                and tools_enabled
                and 400 <= e.code < 500
                and ("tool" in low or "function" in low)
            ):
                # Provider likely rejects function calling; retry the
                # whole conversation once as plain chat.
                tools_enabled = False
                degraded = True
                retry_payload = {
                    "model": remote_id,
                    "max_tokens": MAX_TOKENS,
                    "messages": messages,
                }
                try:
                    resp = _openai_post(url, key, retry_payload)
                except urllib.error.HTTPError as e2:
                    body2 = e2.read().decode("utf-8", "replace")
                    return f"(provider error {e2.code}: {body2[:300]})", None
                except Exception as e2:  # noqa: BLE001
                    return (
                        f"(provider error: {type(e2).__name__}: {e2})",
                        None,
                    )
            else:
                return f"(provider error {e.code}: {body[:300]})", None
        except Exception as e:  # noqa: BLE001
            return f"(provider error: {type(e).__name__}: {e})", None
        first_call = False
        u = resp.get("usage") or {}
        try:
            usage_totals["input_tokens"] += int(u.get("prompt_tokens") or 0)
            usage_totals["output_tokens"] += int(u.get("completion_tokens") or 0)
        except (TypeError, ValueError):
            pass
        choices = resp.get("choices") or []
        msg = (choices[0].get("message") or {}) if choices else {}
        content = msg.get("content")
        if isinstance(content, str) and content.strip():
            text_parts.append(content.strip())
        tool_calls = msg.get("tool_calls") or []
        if tools_enabled and tool_calls:
            # Append the assistant message exactly as returned, then one
            # role:tool result per call, then loop for the next round.
            messages.append(msg)
            for tc in tool_calls:
                fn = tc.get("function") or {}
                name = fn.get("name", "")
                raw_args = fn.get("arguments") or "{}"
                try:
                    args = json.loads(raw_args)
                except (json.JSONDecodeError, TypeError, ValueError):
                    args = None
                if isinstance(args, dict):
                    result = execute_tool(name, args)
                else:
                    result = (
                        "(error: tool arguments were not a valid JSON "
                        f"object: {str(raw_args)[:200]})"
                    )
                messages.append(
                    {
                        "role": "tool",
                        "tool_call_id": tc.get("id", ""),
                        "content": str(result)[:40000],
                    }
                )
            continue
        break
    if not text_parts and tools_enabled:
        # Loop exhausted while the model was still tool-calling: force one
        # final text-only round so the user never sees an empty reply.
        messages.append(
            {
                "role": "user",
                "content": (
                    "Tool budget exhausted. Answer now in plain text using "
                    "only the data already gathered above."
                ),
            }
        )
        try:
            resp = _openai_post(
                url,
                key,
                {
                    "model": remote_id,
                    "max_tokens": MAX_TOKENS,
                    "messages": messages,
                },
            )
            u = resp.get("usage") or {}
            usage_totals["input_tokens"] += int(u.get("prompt_tokens") or 0)
            usage_totals["output_tokens"] += int(
                u.get("completion_tokens") or 0
            )
            choices = resp.get("choices") or []
            msg = (choices[0].get("message") or {}) if choices else {}
            content = msg.get("content")
            if isinstance(content, str) and content.strip():
                text_parts.append(content.strip())
        except Exception:  # noqa: BLE001  fall through to the empty marker
            pass
    text = "\n".join(text_parts).strip()
    if degraded:
        note = "(note: this model ran without tools this turn)"
        text = f"{text}\n{note}" if text else note
    return text or "(empty reply from provider)", usage_totals

TOOLS = [
    {
        "name": "bash",
        "description": "Run a shell command on the Mac. Use for data pulls, git, python scripts, file ops, curl, any shell action. Cwd is the repo root.",
        "input_schema": {
            "type": "object",
            "properties": {"command": {"type": "string"}},
            "required": ["command"],
        },
    },
    {
        "name": "read_file",
        "description": "Read a file. Optional view_range = [start, end] (1-indexed, inclusive). Returns up to 40KB.",
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "view_range": {"type": "array", "items": {"type": "integer"}},
            },
            "required": ["path"],
        },
    },
    {
        "name": "write_file",
        "description": "Create or overwrite a file with the given content. Creates parent dirs as needed.",
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "content": {"type": "string"},
            },
            "required": ["path", "content"],
        },
    },
    {
        "name": "str_replace",
        "description": "Replace one unique occurrence of old_str with new_str in the file at path. Errors if old_str is not unique or not found.",
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "old_str": {"type": "string"},
                "new_str": {"type": "string"},
            },
            "required": ["path", "old_str", "new_str"],
        },
    },
    {
        "name": "web_search",
        "description": "Search the web. Use for any claim about dates, stats, people, or companies before asserting it.",
        "input_schema": {
            "type": "object",
            "properties": {"query": {"type": "string"}},
            "required": ["query"],
        },
    },
    {
        "name": "text_19keys",
        "description": "Send an iMessage to 19Keys via SendBlue. Use during heartbeat only when an alert is breached, a milestone is hit, or a user-requested task finished. Keep content under 500 chars. Do not spam; at most one text per heartbeat cycle.",
        "input_schema": {
            "type": "object",
            "properties": {"content": {"type": "string"}},
            "required": ["content"],
        },
    },
]


def api_call(messages, system):
    payload = {
        "model": MODEL,
        "max_tokens": MAX_TOKENS,
        "system": [
            {"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}
        ],
        "messages": messages,
        "tools": TOOLS,
    }
    data = json.dumps(payload).encode()
    req = urllib.request.Request(
        API_URL,
        data=data,
        headers={
            "x-api-key": API_KEY,
            "anthropic-version": "2023-06-01",
            "content-type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=180) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", "replace")
        raise RuntimeError(f"API {e.code}: {body[:500]}")


def run_bash(cmd, timeout=120):
    try:
        p = subprocess.run(
            ["/bin/bash", "-lc", cmd],
            capture_output=True,
            text=True,
            timeout=timeout,
            cwd=str(REPO),
        )
        out = p.stdout + (("\n[stderr]\n" + p.stderr) if p.stderr else "")
        return out[:40000] or "(no output)"
    except subprocess.TimeoutExpired:
        return f"(timeout after {timeout}s)"
    except Exception as e:
        return f"(error: {e})"


def run_read_file(tool_input):
    try:
        p = Path(tool_input["path"])
        if p.is_dir():
            return "\n".join(sorted(str(x.relative_to(p)) for x in p.iterdir()))[:40000]
        text = p.read_text()
        vr = tool_input.get("view_range")
        if vr and len(vr) == 2:
            text = "\n".join(text.splitlines()[vr[0] - 1 : vr[1]])
        return text[:40000]
    except Exception as e:
        return f"(read error: {e})"


def run_write_file(tool_input):
    try:
        p = Path(tool_input["path"])
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(tool_input["content"])
        return f"wrote {p} ({len(tool_input['content'])} bytes)"
    except Exception as e:
        return f"(write error: {e})"


def run_str_replace(tool_input):
    try:
        p = Path(tool_input["path"])
        text = p.read_text()
        old = tool_input["old_str"]
        new = tool_input["new_str"]
        if old not in text:
            return f"ERROR: old_str not found in {p}"
        if text.count(old) > 1:
            return "ERROR: old_str not unique; add more context"
        p.write_text(text.replace(old, new, 1))
        return f"edited {p}"
    except Exception as e:
        return f"(edit error: {e})"


def run_web_search(query):
    try:
        req = urllib.request.Request(
            f"https://duckduckgo.com/html/?q={urllib.parse.quote(query)}",
            headers={"User-Agent": "Mozilla/5.0"},
        )
        with urllib.request.urlopen(req, timeout=15) as r:
            html = r.read().decode("utf-8", "replace")
        import re

        hits = re.findall(
            r'<a[^>]+class="result__a"[^>]+href="([^"]+)"[^>]*>(.*?)</a>.*?<a[^>]+class="result__snippet"[^>]*>(.*?)</a>',
            html,
            flags=re.S,
        )
        lines = []
        for url, title, snip in hits[:5]:
            t = re.sub(r"<[^>]+>", "", title).strip()
            s = re.sub(r"<[^>]+>", "", snip).strip()
            lines.append(f"- {t}\n  {url}\n  {s}")
        return "\n".join(lines) or "(no results)"
    except Exception as e:
        return f"(search error: {e})"


def run_text_19keys(tool_input):
    number = os.environ.get("KEYS_IMESSAGE_NUMBER", "")
    if not number:
        return "(skip: KEYS_IMESSAGE_NUMBER not set — text not sent)"
    try:
        from sendblue import send as sb_send

        result = sb_send(number, tool_input.get("content", "")[:1500])
        return json.dumps(result)[:800]
    except Exception as e:
        return f"(sendblue error: {e})"


def execute_tool(name, tool_input):
    if name == "bash":
        return run_bash(tool_input.get("command", ""))
    if name == "read_file":
        return run_read_file(tool_input)
    if name == "write_file":
        return run_write_file(tool_input)
    if name == "str_replace":
        return run_str_replace(tool_input)
    if name == "web_search":
        return run_web_search(tool_input.get("query", ""))
    if name == "text_19keys":
        return run_text_19keys(tool_input)
    return f"(unknown tool: {name})"


def agent_loop(user_msg, system=SYSTEM_PROMPT, log_path=None):
    # Ground every session in live CRM numbers (fetched once per invocation,
    # provider-agnostic — Claude and OpenAI-compat paths both get it).
    system = system + live_crm_context()
    # Non-Anthropic models: full tool loop over OpenAI function calling.
    # Same logging and usage emission contract as the Claude path.
    if MODEL in OPENAI_COMPAT:
        out, usage = openai_compat_call(MODEL, system, user_msg)
        if log_path:
            log_path.parent.mkdir(parents=True, exist_ok=True)
            with log_path.open("a") as f:
                f.write(
                    f"\n===== {datetime.now(timezone.utc).isoformat()} =====\n"
                    f"MODEL: {MODEL}\nINPUT: {user_msg[:500]}\nOUTPUT: {out}\n"
                )
        if EMIT_USAGE and usage is not None:
            print(
                "__CHAIRMAN_USAGE__ " + json.dumps(dict(usage, model=MODEL)),
                flush=True,
            )
        return out

    messages = [{"role": "user", "content": user_msg}]
    final_text_parts = []
    usage_totals = {
        "input_tokens": 0,
        "output_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation_input_tokens": 0,
    }
    for i in range(MAX_ITERATIONS):
        resp = api_call(messages, system)
        if EMIT_USAGE:
            u = resp.get("usage") or {}
            for k in usage_totals:
                try:
                    usage_totals[k] += int(u.get(k) or 0)
                except (TypeError, ValueError):
                    pass
        content = resp.get("content", [])
        stop = resp.get("stop_reason")
        messages.append({"role": "assistant", "content": content})
        if stop == "tool_use":
            tool_results = []
            for block in content:
                if block.get("type") == "tool_use":
                    result = execute_tool(block["name"], block.get("input", {}))
                    tool_results.append(
                        {
                            "type": "tool_result",
                            "tool_use_id": block["id"],
                            "content": result,
                        }
                    )
                elif block.get("type") == "text" and block.get("text"):
                    final_text_parts.append(block["text"])
            messages.append({"role": "user", "content": tool_results})
            continue
        for block in content:
            if block.get("type") == "text":
                final_text_parts.append(block.get("text", ""))
        break
    out = "\n".join(p for p in final_text_parts if p).strip()
    if log_path:
        log_path.parent.mkdir(parents=True, exist_ok=True)
        with log_path.open("a") as f:
            f.write(
                f"\n===== {datetime.now(timezone.utc).isoformat()} =====\n"
                f"INPUT: {user_msg[:500]}\nOUTPUT: {out}\n"
            )
    if EMIT_USAGE:
        print(
            "__CHAIRMAN_USAGE__ " + json.dumps(dict(usage_totals, model=MODEL)),
            flush=True,
        )
    return out


def heartbeat():
    LOG_DIR.mkdir(parents=True, exist_ok=True)
    INBOX.mkdir(parents=True, exist_ok=True)
    DONE.mkdir(parents=True, exist_ok=True)
    ts = datetime.now(timezone.utc).isoformat()

    tasks = sorted(INBOX.glob("*.md"))
    task_summary = "\n".join(f"- {p.name}" for p in tasks) or "(inbox empty)"

    directive = f"""Heartbeat cycle at {ts}.

Your autonomous checklist this cycle:

1. Read your memory: /Users/19keys/sovereign-empire-sweep/sovereign-wiki/memory/CHAIRMAN-MEMORY.md
2. Check the active monitoring signals. If any threshold is breached, flag it.
3. Scan the inbox for queued tasks:
{task_summary}
4. For each task file in the inbox, read it, act on it, write a short outcome to the same file (append "## OUTCOME" section), then move it to /Users/19keys/sovereign-empire-sweep/chairman-agent/done/ via bash mv.
5. If the inbox is empty, pick ONE item from the Decisions Log in memory that is still "Pending" and do one small thing to move it forward (write a draft, pull data, send a nudge).
6. Update CHAIRMAN-MEMORY.md with anything learned this cycle.

End with a one-paragraph heartbeat summary. No preamble.
"""
    try:
        out = agent_loop(directive, log_path=HEARTBEAT_LOG)
    except (RuntimeError, urllib.error.URLError, OSError) as exc:
        # Two owner-side conditions must never crash-loop launchd:
        # network down (laptop offline/DNS flake) and API credits exhausted.
        import credit_guard
        if isinstance(exc, (urllib.error.URLError, OSError)) and not (
            isinstance(exc, RuntimeError)
        ):
            with HEARTBEAT_LOG.open("a") as f:
                f.write(f"\n----- HEARTBEAT {ts} SKIPPED — network unreachable: {exc} -----\n")
            print(f"heartbeat skipped: network unreachable ({exc})")
            return
        import cost_guard
        if isinstance(exc, cost_guard.CutoffError):
            # 80%-of-$50 monthly cap tripped (same threshold as musa/telegram).
            credit_guard.record_skip("heartbeat")
            with HEARTBEAT_LOG.open("a") as f:
                f.write(f"\n----- HEARTBEAT {ts} SKIPPED — budget cutoff active -----\n")
            if credit_guard.should_notify("heartbeat"):
                try:
                    sys.path.insert(0, "/Users/19keys/sovereign-empire-sweep/loops/lib")
                    import alert
                    alert.send("heartbeat", "Chairman heartbeat skipped — monthly "
                               "Anthropic budget cutoff active (80% of $50 cap). "
                               "/unlock via telegram to resume, or wait for next month.")
                    credit_guard.mark_notified("heartbeat")
                except Exception:
                    pass
            print("heartbeat skipped: budget cutoff active (clean exit)")
            return
        if not credit_guard.is_credit_error(exc):
            raise
        credit_guard.record_skip("heartbeat")
        with HEARTBEAT_LOG.open("a") as f:
            f.write(f"\n----- HEARTBEAT {ts} SKIPPED — API credits exhausted -----\n")
        if credit_guard.should_notify("heartbeat"):
            try:
                sys.path.insert(0, "/Users/19keys/sovereign-empire-sweep/loops/lib")
                import alert
                alert.send("heartbeat", "Chairman heartbeat skipped — API credits "
                           "exhausted (owner action: add credits at console.anthropic.com). "
                           "Resumes automatically once credits exist.")
                credit_guard.mark_notified("heartbeat")
            except Exception:
                pass
        print("heartbeat skipped: API credits exhausted (clean exit)")
        return
    with HEARTBEAT_LOG.open("a") as f:
        f.write(f"\n----- HEARTBEAT {ts} -----\n{out}\n")
    print(out)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--chat", help="one-shot message")
    ap.add_argument("--chat-stdin", action="store_true", help="read message from stdin")
    ap.add_argument("--heartbeat", action="store_true", help="run autonomous cycle")
    args = ap.parse_args()

    if args.heartbeat:
        heartbeat()
        return
    msg = args.chat or (sys.stdin.read().strip() if args.chat_stdin else "")
    if not msg:
        ap.error("provide --chat, --chat-stdin, or --heartbeat")
    print(agent_loop(msg, log_path=CHAT_LOG))


if __name__ == "__main__":
    # Meter this process's own api_call the same way telegram_bridge.py meters
    # it for the chat/musa entry points (2026-07-12): the heartbeat LaunchAgent
    # runs `python3 agent.py --heartbeat` as a standalone process that never
    # imports telegram_bridge, so it previously had no proactive budget cap —
    # only the reactive credit_guard skip-on-zero-balance. Scoped to __main__
    # only: when telegram_bridge imports this module, ITS wrapper is the one
    # active, so this can never double-count a call.
    import cost_guard
    _unmetered_api_call = api_call

    def _metered_api_call(messages, system):
        if cost_guard.is_cutoff_active():
            raise cost_guard.CutoffError("budget cutoff active — /unlock to resume")
        resp = _unmetered_api_call(messages, system)
        try:
            u = resp.get("usage") or {}
            cost_guard.log_api_call(
                "anthropic", MODEL,
                int(u.get("input_tokens") or 0), int(u.get("output_tokens") or 0),
            )
        except Exception:
            pass
        return resp

    api_call = _metered_api_call
    main()
