import json
import base64
import os
import requests
from datetime import datetime, timezone


def budget_alert(event, context):
    """Triggered by a Pub/Sub budget alert. Disables demo if threshold exceeded."""
    data = base64.b64decode(event['data']).decode('utf-8')
    alert = json.loads(data)

    # Only act on threshold exceeded alerts (not forecasts)
    cost_amount = alert.get('costAmount', 0)
    budget_amount = alert.get('budgetAmount', 1)
    threshold = cost_amount / budget_amount if budget_amount else 0

    if threshold < 0.9:
        print(f"Threshold {threshold:.1%} below 90%, no action")
        return

    supabase_url = os.environ['SUPABASE_URL']
    service_key  = os.environ['SUPABASE_SERVICE_KEY']

    resp = requests.patch(
        f"{supabase_url}/rest/v1/demo_config?key=eq.demo_enabled",
        headers={
            'Authorization': f'Bearer {service_key}',
            'apikey': service_key,
            'Content-Type': 'application/json',
            'Prefer': 'return=minimal',
        },
        json={'value': 'false', 'updated_at': datetime.now(timezone.utc).isoformat()}
    )
    print(f"Demo disabled — budget at {threshold:.1%}. Supabase: {resp.status_code}")
