"""Pull attendance from the Kingdom Metrics public API.

Usage:
    export KM_API_KEY="km_pub_..."
    python python.py 2026-04-01 2026-04-30

Get a key at:
    https://app.kingdommetrics.com/dashboard/settings?section=integrations
"""

from __future__ import annotations

import os
import sys
from datetime import date, timedelta

import requests

BASE = "https://api.kingdommetrics.com/public/v1"


def fetch_attendance(start: str, end: str) -> list[dict]:
    key = os.environ.get("KM_API_KEY")
    if not key:
        raise SystemExit("error: set KM_API_KEY before running")

    rows: list[dict] = []
    cursor: str | None = None
    while True:
        params = {"start_date": start, "end_date": end}
        if cursor:
            params["cursor"] = cursor
        resp = requests.get(
            f"{BASE}/attendance",
            headers={"Authorization": f"Bearer {key}"},
            params=params,
            timeout=30,
        )
        resp.raise_for_status()
        body = resp.json()
        rows.extend(body["data"])
        cursor = body.get("next_cursor")
        if not cursor:
            break
    return rows


def main() -> None:
    today = date.today()
    start = sys.argv[1] if len(sys.argv) > 1 else (today - timedelta(days=30)).isoformat()
    end = sys.argv[2] if len(sys.argv) > 2 else today.isoformat()

    rows = fetch_attendance(start, end)
    for row in rows:
        count = row["count"] if row["count"] is not None else "—"
        print(f"{row['date']}  {row['event']:25s}  {count!s:>4}  ({row['status']})")


if __name__ == "__main__":
    main()
