from __future__ import annotations

from datetime import datetime, timezone

import polars as pl

from uforia.config import AppConfig, get_config
from uforia.ingest.deribit.client import DeribitPublicClient


def fetch_funding_rate(
    *,
    start: datetime,
    end: datetime,
    underlying: str = "BTC",
    venue: str = "deribit",
    client: DeribitPublicClient | None = None,
    config: AppConfig | None = None,
) -> pl.DataFrame:
    cfg = config or get_config()
    deribit = client or DeribitPublicClient(cfg)
    instrument_name = f"{underlying}-PERPETUAL"
    history = deribit.get_funding_rate_history(
        instrument_name=instrument_name,
        start=start.astimezone(timezone.utc),
        end=end.astimezone(timezone.utc),
    )
    rows: list[dict[str, object]] = []
    for row in history:
        ts = datetime.fromtimestamp(int(row["timestamp"]) / 1000, tz=timezone.utc)
        rows.append(
            {
                "ts": ts,
                "date": ts.date(),
                "venue": venue,
                "underlying": underlying,
                "source": "deribit_perpetual",
                "interest_1h": float(row.get("interest_1h", 0.0)),
                "interest_8h": float(row.get("interest_8h", 0.0)),
                "quality_flag": "ok",
            }
        )
    return pl.DataFrame(rows)
