from __future__ import annotations

import json
import os
import urllib.parse
import urllib.request
from datetime import date

from prefect import flow, get_run_logger, task
from prefect.blocks.system import Secret

RAPIDAPI_HOST = "sec-event-intelligence.p.rapidapi.com"
API_BASE_URL = f"https://{RAPIDAPI_HOST}"


def load_rapidapi_key() -> str:
    env_value = os.environ.get("RAPIDAPI_KEY")
    if env_value:
        return env_value
    return Secret.load("sec-event-intelligence-rapidapi-key").get()


@task(retries=2, retry_delay_seconds=30)
def fetch_sec_watchlist(tickers: str, since: str, limit: int = 25) -> list[dict]:
    rapidapi_key = load_rapidapi_key()
    query = urllib.parse.urlencode({
        "tickers": tickers,
        "since": since,
        "limit": str(limit),
    })
    request = urllib.request.Request(
        f"{API_BASE_URL}/v1/sec/watchlist/changes?{query}",
        headers={
            "x-rapidapi-host": RAPIDAPI_HOST,
            "x-rapidapi-key": rapidapi_key,
            "accept": "application/json",
        },
    )

    with urllib.request.urlopen(request, timeout=30) as response:
        payload = json.loads(response.read().decode("utf-8"))

    rows = []
    for group in payload.get("data", []):
        for change in group.get("changes", []):
            filing = change.get("filing", {})
            rows.append({
                "ticker": group.get("ticker"),
                "form": filing.get("form", ""),
                "company_name": filing.get("companyName", ""),
                "filed_at": filing.get("filedAt", ""),
                "accession_no": filing.get("accessionNo", ""),
                "filing_url": filing.get("filingUrl", ""),
            })
    return rows


@flow(name="sec-event-intelligence-watchlist", retries=1, retry_delay_seconds=60)
def sec_event_intelligence_watchlist(
    tickers: str = "AAPL,MSFT,NVDA",
    since: str | None = None,
    limit: int = 25,
) -> list[dict]:
    logger = get_run_logger()
    effective_since = since or date.today().isoformat()
    rows = fetch_sec_watchlist(tickers=tickers, since=effective_since, limit=limit)
    logger.info("Fetched %s SEC filing rows for %s", len(rows), tickers)
    return rows


if __name__ == "__main__":
    sec_event_intelligence_watchlist()
