#!/usr/bin/env python3
"""
Check Tommy's daily API spend via Anthropic usage API.
Alerts Tony if daily spend exceeds threshold.
"""
import sys, os, json, urllib.request
from datetime import datetime, date, timedelta
from pathlib import Path

THRESHOLD_DAILY = 3.00   # Alert if daily cost exceeds $3
THRESHOLD_MONTHLY = 35.00  # Alert if projected monthly exceeds $35

def load_env():
    env = {}
    for line in (Path.home() / ".openclaw/workspace/.env").read_text().splitlines():
        if "=" in line and not line.startswith("#"):
            k, v = line.split("=", 1)
            env[k.strip()] = v.strip()
    return env

def check_costs():
    env = load_env()
    api_key = env.get("ANTHROPIC_TOMMY_API_KEY") or env.get("TOMMY_API_KEY")

    if not api_key:
        print("No Tommy API key found — skipping cost check")
        return

    today = date.today()
    yesterday = today - timedelta(days=1)

    headers = {
        "x-api-key": api_key,
        "anthropic-version": "2023-06-01",
        "Content-Type": "application/json"
    }

    # Try Anthropic usage API
    try:
        url = f"https://api.anthropic.com/v1/usage?start_date={yesterday}&end_date={today}"
        req = urllib.request.Request(url, headers=headers)
        with urllib.request.urlopen(req, timeout=10) as r:
            data = json.loads(r.read())
            yesterday_cost = sum(item.get("cost_usd", 0) for item in data.get("data", [])
                               if item.get("date") == str(yesterday))

            print(f"Yesterday ({yesterday}): ${yesterday_cost:.2f}")

            alerts = []
            if yesterday_cost > THRESHOLD_DAILY:
                alerts.append(f"⚠️ Tommy API cost spike: ${yesterday_cost:.2f} yesterday (threshold: ${THRESHOLD_DAILY:.2f}/day)")

            projected_monthly = yesterday_cost * 30
            if projected_monthly > THRESHOLD_MONTHLY:
                alerts.append(f"⚠️ Tommy projected monthly: ${projected_monthly:.2f} (threshold: ${THRESHOLD_MONTHLY:.2f}/mo)")

            if alerts:
                return "\n".join(alerts)
            return None

    except Exception as e:
        # API might not support usage endpoint — log and skip
        log = Path.home() / ".openclaw/workspace/memory/tommy-cost-check.log"
        log.parent.mkdir(exist_ok=True)
        with open(log, "a") as f:
            f.write(f"[{datetime.now()}] Cost check failed: {e}\n")
        return None

if __name__ == "__main__":
    alert = check_costs()
    if alert:
        print(f"ALERT: {alert}")
        sys.exit(2)  # Non-zero exit = alert triggered
    else:
        print("OK — within limits")
        sys.exit(0)

# TONY-APPROVED: 2026-03-01 | sha:6b68cbed
