#!/usr/bin/env python3
"""Aria Cost-Report — $-Kosten-Aufschluesselung via ccusage (npx, zero-install).

Ergaenzt aria-usage.py (nur Tokens) um $-Aequivalent + Modell-Breakdown.
WICHTIG: Die $-Werte sind API-Aequivalent. Aria laeuft auf Anthropic Max-Plan
(Flatrate) — Kais zahlt diese Betraege NICHT real. Der Wert zeigt (a) wie viel
die Nutzung "wert" ist und (b) ob wir ans Plan-Limit/Fair-Use stossen.

Aufruf:
  python3 aria-cost.py            # 7-Tage + Monat, Text
  python3 aria-cost.py --days 14  # andere Fensterbreite
  python3 aria-cost.py --telegram # MarkdownV2-Block fuer Telegram-Report
"""
import argparse
import json
import subprocess
import sys
from datetime import date


def run_ccusage():
    try:
        out = subprocess.run(
            ["npx", "-y", "ccusage@latest", "daily", "--json"],
            capture_output=True, text=True, timeout=120,
        )
    except Exception as e:
        print(f"ccusage-Aufruf fehlgeschlagen: {e}", file=sys.stderr)
        sys.exit(1)
    if out.returncode != 0:
        print(f"ccusage exit {out.returncode}: {out.stderr[:300]}", file=sys.stderr)
        sys.exit(1)
    # ccusage prints a leading blank/log line sometimes; find the JSON body
    text = out.stdout.strip()
    start = text.find("{")
    if start > 0:
        text = text[start:]
    return json.loads(text)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--days", type=int, default=7)
    ap.add_argument("--telegram", action="store_true")
    args = ap.parse_args()

    data = run_ccusage()
    daily = data.get("daily", [])
    totals = data.get("totals", {})

    window = daily[-args.days:] if args.days else daily
    win_cost = sum(d.get("totalCost", 0) for d in window)
    win_tok = sum(d.get("totalTokens", 0) for d in window)

    this_month = date.today().strftime("%Y-%m")
    month_days = [d for d in daily if str(d.get("period", "")).startswith(this_month)]
    month_cost = sum(d.get("totalCost", 0) for d in month_days)
    month_tok = sum(d.get("totalTokens", 0) for d in month_days)

    def fmt_tok(n):
        if n >= 1e9:
            return f"{n/1e9:.2f}B"
        if n >= 1e6:
            return f"{n/1e6:.1f}M"
        if n >= 1e3:
            return f"{n/1e3:.0f}k"
        return str(n)

    if args.telegram:
        esc = lambda s: str(s).replace(".", "\\.").replace("-", "\\-").replace("(", "\\(").replace(")", "\\)").replace("!", "\\!")
        lines = ["*Aria Cost\\-Report* \\(API\\-Aequivalent, Max\\-Plan \\= real $0\\)", ""]
        lines.append(f"*Letzte {args.days} Tage:* `${win_cost:,.0f}` \\({esc(fmt_tok(win_tok))} tok\\)")
        lines.append(f"*Monat {esc(this_month)}:* `${month_cost:,.0f}`")
        lines.append("")
        lines.append("*Top Tage:*")
        for d in sorted(window, key=lambda x: x.get("totalCost", 0), reverse=True)[:3]:
            lines.append(f"• {esc(d.get('period'))}: `${d.get('totalCost',0):,.0f}`")
        print("\n".join(lines))
    else:
        print("=== Aria Cost-Report (ccusage) ===")
        print("HINWEIS: $-Werte sind API-Aequivalent. Max-Plan = Flatrate, real $0.\n")
        print(f"Letzte {args.days} Tage: ${win_cost:,.2f}  ({fmt_tok(win_tok)} tokens)")
        print(f"Monat {this_month}:    ${month_cost:,.2f}  ({fmt_tok(month_tok)} tokens)")
        print(f"All-Time:          ${totals.get('totalCost',0):,.2f}  ({fmt_tok(totals.get('totalTokens',0))} tokens)\n")
        print("Letzte Tage:")
        for d in window:
            models = ",".join(m.replace("claude-", "") for m in d.get("modelsUsed", []))
            print(f"  {d.get('period')}: ${d.get('totalCost',0):>8,.2f}  {fmt_tok(d.get('totalTokens',0)):>7}  [{models}]")


if __name__ == "__main__":
    main()
