#!/usr/bin/env python3
"""Token observability script — reports per-turn token usage.
Run: hermes cron create --script token-usage-report.py --schedule "0 9 * * 1"
Or use inline: python3 ~/.hermes/scripts/token-usage-report.py
"""

import sqlite3, os, sys
from datetime import datetime, timedelta

db = os.path.expanduser("~/.hermes/state.db")

try:
    conn = sqlite3.connect(db)
    cursor = conn.cursor()

    # Overall stats
    cursor.execute("""
        SELECT 
            COUNT(*) as sessions,
            SUM(input_tokens) as input,
            SUM(output_tokens) as output,
            SUM(cache_read_tokens) as cache_read,
            SUM(estimated_cost_usd) as cost
        FROM sessions
    """)
    total = cursor.fetchone()

    # Last 24h stats
    yesterday = datetime.now() - timedelta(hours=24)
    cursor.execute("""
        SELECT 
            COUNT(*) as sessions,
            SUM(input_tokens) as input,
            SUM(output_tokens) as output,
            SUM(cache_read_tokens) as cache_read,
            SUM(estimated_cost_usd) as cost
        FROM sessions WHERE started_at > ?
    """, (yesterday.timestamp(),))
    recent = cursor.fetchone()

    # Top models by input tokens
    cursor.execute("""
        SELECT model, SUM(input_tokens) as total_in, SUM(output_tokens) as total_out, COUNT(*) as count
        FROM sessions GROUP BY model ORDER BY total_in DESC LIMIT 5
    """)
    top_models = cursor.fetchall()

    conn.close()

    print("📊 Token Usage Report")
    print(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print()
    print("All Time:")
    print(f"  Sessions:          {total[0]}")
    print(f"  Input tokens:      {total[1]:>12,}" if total[1] else "  Input tokens:      0")
    print(f"  Output tokens:     {total[2]:>12,}" if total[2] else "  Output tokens:     0")
    print(f"  Cache reads:       {total[3]:>12,}" if total[3] else "  Cache reads:       0")
    print(f"  Est. cost:         ${total[4]:>8.4f}" if total[4] else "  Est. cost:         $0.0000")
    print()
    print("Last 24 Hours:")
    print(f"  Sessions:          {recent[0]}")
    print(f"  Input tokens:      {recent[1]:>12,}" if recent[1] else "  Input tokens:      0")
    print(f"  Output tokens:     {recent[2]:>12,}" if recent[2] else "  Output tokens:     0")
    print(f"  Cache reads:       {recent[3]:>12,}" if recent[3] else "  Cache reads:       0")
    print(f"  Est. cost:         ${recent[4]:>8.4f}" if recent[4] else "  Est. cost:         $0.0000")
    print()
    if top_models:
        print("Top Models by Token Usage:")
        for m in top_models:
            print(f"  {m[0]:30s} in={m[1]:>10,} out={m[2]:>10,} sessions={m[3]}")

except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)
