#!/usr/bin/env python3
"""Keeps a Legato page of this month's Anthropic API spend against a budget.
Python 3.9 or later, standard library only. Run it every hour from launchd or cron, on the
Mac that runs Legato:

    python3 -I api-spend.py --budget 500

It reads ANTHROPIC_ADMIN_KEY (an Admin API key, sk-ant-admin01-..., from an organization's
Claude Console), sums this calendar month's cost from the Admin API's cost report, and writes
the page "ai-spend" with `legato set`: a pacing bar against the budget, a sparkline of daily
spend, and a note when spend runs ahead of pace. Once spend reaches the budget, the page also
asks for one macOS notification that month. Months and days are UTC, like the cost report's
buckets. --dry-run prints the page instead.

`legato` is the tool inside Legato.app. The script runs
/Applications/Legato.app/Contents/Helpers/legato unless LEGATO_CLI names another path.
"""
import argparse
import calendar
import json
import os
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
from decimal import ROUND_HALF_UP, Decimal

ANTHROPIC = os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com").rstrip("/")
LEGATO_CLI = os.environ.get("LEGATO_CLI") or "/Applications/Legato.app/Contents/Helpers/legato"
USER_AGENT = "legato-api-spend/1.0 (https://legatobar.com/docs/scripts)"


def fail(message):
    print(f"api-spend: {message}", file=sys.stderr)
    sys.exit(1)


def get(url, headers):
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, **headers})
    try:
        with urllib.request.urlopen(req, timeout=30) as res:
            return json.load(res)
    except urllib.error.HTTPError as e:
        fail(f"GET {url.split('?')[0]} answered HTTP {e.code}: {e.read().decode(errors='replace')[:2000]}")
    except urllib.error.URLError as e:
        fail(f"GET {url.split('?')[0]} failed: {e.reason}")


def daily_cost(admin_key, month_start, now):
    """{date: cents} for each day of the month so far, from GET /v1/organizations/cost_report.

    Each bucket is one UTC day, and its results' amounts are decimal strings in cents ("123.45"
    is $1.23). There's no ending_at, so the report runs up to today; limit=31 fits a month on one
    page, but the loop follows next_page all the same.
    """
    days, page = {}, None
    while True:
        query = {"starting_at": month_start.strftime("%Y-%m-%dT%H:%M:%SZ"), "bucket_width": "1d", "limit": "31"}
        if page:
            query["page"] = page
        report = get(f"{ANTHROPIC}/v1/organizations/cost_report?{urllib.parse.urlencode(query)}",
                      {"x-api-key": admin_key, "anthropic-version": "2023-06-01"})
        for bucket in report.get("data", []):
            start = datetime.fromisoformat(bucket["starting_at"].replace("Z", "+00:00"))
            if month_start <= start <= now:
                cents = sum((Decimal(r["amount"]) for r in bucket.get("results", [])), Decimal(0))
                days[start.date()] = days.get(start.date(), Decimal(0)) + cents
        page = report.get("next_page")
        if not report.get("has_more") or not page:
            return days


def cents(dollars):
    """To the cent, halves up, as a JSON number."""
    return float(dollars.quantize(Decimal("0.01"), ROUND_HALF_UP))


def money(dollars):
    return f"${dollars:,.2f}"


def build_page(days, budget, now):
    month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    month_days = calendar.monthrange(now.year, now.month)[1]
    elapsed = min(max((now - month_start) / timedelta(days=month_days), 0.0), 1.0)
    # Every day so far, oldest first, with $0 for a day the report left out.
    points = [days.get((month_start + timedelta(days=i)).date(), Decimal(0)) / 100 for i in range(now.day)]
    spent = sum(points, Decimal(0))
    value = cents(spent)

    cards = [{"id": "month", "type": "pacing", "label": now.strftime("%B"),
                "value": value, "target": budget, "elapsed": round(elapsed, 4), "unit": "USD"}]
    if len(points) >= 2:  # a sparkline takes 2 to 60 points, so it starts on the 2nd
        cards.append({"id": "daily", "type": "sparkline", "label": "Daily spend",
                        "points": [cents(p) for p in points], "unit": "USD"})

    page = {"title": "API spend", "icon": "sparkles", "cards": cards}
    if value >= budget:
        cards.append({"id": "note", "type": "text", "tone": "critical",
                        "body": f"Over the {money(budget)} budget by {money(value - budget)}, with {round((1 - elapsed) * 100)}% of the month to go."})
        # Shown once per id, so once a month however often the job runs.
        page["notify"] = {"id": f"over-budget-{now:%Y-%m}", "title": "Over budget",
                          "body": f"{money(value)} of the {money(budget)} budget spent this month."}
    elif elapsed > 0 and value / budget > elapsed:
        projected = value / elapsed
        cards.append({"id": "note", "type": "text", "tone": "warning",
                        "body": f"Ahead of pace: at this rate the month ends near {money(projected)}, {money(projected - budget)} over budget."})
    return page


def write_page(page_id, page):
    """`legato set <page_id>` with the page on stdin: its JSON answer, or fail with its error."""
    try:
        done = subprocess.run([LEGATO_CLI, "set", page_id], input=json.dumps(page), capture_output=True, text=True, timeout=60)
    except FileNotFoundError:
        fail(f"{LEGATO_CLI} isn't there; install Legato in /Applications, or set LEGATO_CLI to its legato tool")
    except subprocess.TimeoutExpired:
        fail("legato set took more than a minute")
    try:
        answer = json.loads(done.stdout)
    except ValueError:
        answer = {}
    if done.returncode != 0 or "error" in answer:
        error = answer.get("error") or {"message": (done.stderr or done.stdout).strip()}
        details = f" {json.dumps(error['details'])}" if error.get("details") else ""
        fail(f"legato set {page_id} refused it: {error.get('code', 'failed')}: {error.get('message')}{details}")
    return answer


def main():
    parser = argparse.ArgumentParser(description="Write this month's Anthropic API spend to a Legato page.")
    parser.add_argument("--budget", type=float, required=True, help="the month's budget in USD, for example 500")
    parser.add_argument("--page", default="ai-spend", help="the page id to write (default: ai-spend)")
    parser.add_argument("--dry-run", action="store_true", help="print the page instead of writing it")
    parser.add_argument("--now", help=argparse.SUPPRESS)  # an RFC 3339 time, for tests
    args = parser.parse_args()
    if args.budget <= 0:
        parser.error("--budget must be above 0")

    admin_key = os.environ.get("ANTHROPIC_ADMIN_KEY") or fail("set ANTHROPIC_ADMIN_KEY to an Admin API key (sk-ant-admin01-...)")

    now = datetime.fromisoformat(args.now.replace("Z", "+00:00")) if args.now else datetime.now(timezone.utc)
    month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    page = build_page(daily_cost(admin_key, month_start, now), args.budget, now)

    if args.dry_run:
        print(json.dumps(page, indent=2))
        return
    result = write_page(args.page, page)
    print(f"{args.page}: version {result.get('version')}, {'changed' if result.get('changed') else 'unchanged'}, "
          f"{page['cards'][0]['value']:.2f} of {args.budget:.2f} USD")
    if result.get("note"):  # saved, but not shown yet: Legato isn't running, or has no trial or license
        print(f"{args.page}: {result['note']}", file=sys.stderr)


if __name__ == "__main__":
    main()
