#!/usr/bin/env python3
"""Löscht Chat-Log Einträge älter als 7 Tage aus Supabase."""

import os
import json
from datetime import datetime, timezone, timedelta
from urllib.request import Request, urlopen

SUPABASE_URL = os.environ.get("ARIA_SUPABASE_URL", "https://rdwtyjtotiryfvfzyafq.supabase.co")
SUPABASE_KEY = os.environ.get("ARIA_SUPABASE_SERVICE_KEY", "")
TABLE = "aria_chat_log"
RETENTION_DAYS = 7


def cleanup():
    if not SUPABASE_KEY:
        print("FEHLER: ARIA_SUPABASE_SERVICE_KEY nicht gesetzt")
        return

    cutoff = (datetime.now(timezone.utc) - timedelta(days=RETENTION_DAYS)).strftime("%Y-%m-%dT%H:%M:%S")
    url = f"{SUPABASE_URL}/rest/v1/{TABLE}?created_at=lt.{cutoff}"
    headers = {
        "apikey": SUPABASE_KEY,
        "Authorization": f"Bearer {SUPABASE_KEY}",
        "Prefer": "return=representation",
    }

    req = Request(url, headers=headers, method="DELETE")
    try:
        resp = urlopen(req, timeout=15)
        deleted = json.loads(resp.read())
        print(f"[CLEANUP] {len(deleted)} Einträge älter als {RETENTION_DAYS} Tage gelöscht")
    except Exception as e:
        print(f"[ERROR] Cleanup fehlgeschlagen: {e}")


if __name__ == "__main__":
    cleanup()
