"""Starter client for SEC Event Intelligence through RapidAPI.

Set RAPIDAPI_KEY before running:

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

from __future__ import annotations

import json
import os
import urllib.parse
import urllib.request
from typing import Any


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


class SecEventIntelligenceClient:
    def __init__(
        self,
        api_key: str | None = None,
        *,
        host: str = f"https://{RAPIDAPI_HOST}",
        timeout: int = 20,
    ) -> None:
        self.api_key = api_key or os.environ["RAPIDAPI_KEY"]
        self.host = host.rstrip("/")
        self.timeout = timeout

    def _get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
        query = urllib.parse.urlencode(
            {key: value for key, value in (params or {}).items() if value is not None}
        )
        url = f"{self.host}{path}"
        if query:
            url = f"{url}?{query}"
        request = urllib.request.Request(
            url,
            headers={
                "x-rapidapi-host": RAPIDAPI_HOST,
                "x-rapidapi-key": self.api_key,
                "accept": "application/json",
            },
        )
        with urllib.request.urlopen(request, timeout=self.timeout) as response:
            return json.loads(response.read().decode("utf-8"))

    def changes(
        self,
        *,
        since: str,
        ticker: str | None = None,
        form: str | None = None,
        event_type: str | None = None,
        limit: int = 25,
    ) -> dict[str, Any]:
        return self._get(
            "/v1/sec/changes",
            {
                "since": since,
                "ticker": ticker,
                "form": form,
                "eventType": event_type,
                "limit": limit,
            },
        )

    def watchlist_changes(
        self,
        *,
        tickers: str,
        since: str,
        form: str | None = None,
        event_type: str | None = None,
        limit: int = 25,
    ) -> dict[str, Any]:
        return self._get(
            "/v1/sec/watchlist/changes",
            {
                "tickers": tickers,
                "since": since,
                "form": form,
                "eventType": event_type,
                "limit": limit,
            },
        )

    def search_companies(self, query: str, *, limit: int = 10) -> dict[str, Any]:
        return self._get("/v1/sec/companies/search", {"q": query, "limit": limit})

    def company_profile(self, ticker: str) -> dict[str, Any]:
        return self._get(f"/v1/sec/company/{urllib.parse.quote(ticker)}/profile")


if __name__ == "__main__":
    client = SecEventIntelligenceClient()
    payload = client.changes(since="2026-07-01", form="8-K", limit=5)
    for item in payload.get("data", []):
        filing = item.get("filing", {})
        print(filing.get("ticker"), filing.get("form"), filing.get("filedAt"))
