"""Run the first SEC Event Intelligence API call through RapidAPI.

Set RAPIDAPI_KEY before running:

    export RAPIDAPI_KEY="your-rapidapi-key"
    python3 sec_event_intelligence_first_call.py

Optional environment variables:

    TICKERS="AAPL,MSFT,NVDA"
    SINCE="2026-07-01"
    LIMIT="10"
"""

from __future__ import annotations

import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request


RAPIDAPI_HOST = "sec-event-intelligence.p.rapidapi.com"


def main() -> int:
    api_key = os.environ.get("RAPIDAPI_KEY")
    if not api_key:
        print("Set RAPIDAPI_KEY to the key generated by RapidAPI.", file=sys.stderr)
        return 2

    params = urllib.parse.urlencode(
        {
            "tickers": os.environ.get("TICKERS", "AAPL,MSFT,NVDA"),
            "since": os.environ.get("SINCE", "2026-07-01"),
            "limit": os.environ.get("LIMIT", "10"),
        }
    )
    url = f"https://{RAPIDAPI_HOST}/v1/sec/watchlist/changes?{params}"
    request = urllib.request.Request(
        url,
        headers={
            "x-rapidapi-host": RAPIDAPI_HOST,
            "x-rapidapi-key": api_key,
            "accept": "application/json",
        },
    )

    try:
        with urllib.request.urlopen(request, timeout=20) as response:
            payload = json.loads(response.read().decode("utf-8"))
            print("HTTP 200 /v1/sec/watchlist/changes")
            print(json.dumps(payload.get("meta", {}), indent=2, sort_keys=True))
            for bucket in payload.get("data", []):
                print(f"{bucket.get('ticker')}: {bucket.get('count', 0)} filings")
            return 0
    except urllib.error.HTTPError as exc:
        print(f"HTTP {exc.code} from RapidAPI", file=sys.stderr)
        print(exc.read().decode("utf-8", errors="replace"), file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
