"""FRED data Oracle service methods."""

from __future__ import annotations

from libs.oracle_client.client import OracleClient
from libs.oracle_client.models import FredObservation, FredProxyResponse, FredSeriesInfo


class FredService:
    def __init__(self, client: OracleClient) -> None:
        self._client = client

    async def get_observations(
        self,
        series_id: str,
        start: str | None = None,
        end: str | None = None,
    ) -> FredProxyResponse:
        params: dict[str, str] = {"series_id": series_id}
        if start:
            params["observation_start"] = start
        if end:
            params["observation_end"] = end
        data = await self._client.get("/api/v1/fred/proxy/series/observations", params=params)
        # Real Oracle: {"success": true, "data": {"realtime_start": ..., "observations": [{"date": ..., "value": "4.06"}]}}
        inner = data.get("data", {})
        obs_raw = inner.get("observations", [])
        observations = [
            FredObservation(
                date=o["date"],
                value=float(o["value"]) if o.get("value") not in (None, ".", "") else None,
            )
            for o in obs_raw
        ]
        return FredProxyResponse(
            series_id=series_id,
            observations=observations,
            realtime_start=inner.get("realtime_start"),
            realtime_end=inner.get("realtime_end"),
        )

    async def get_series_info(self, series_id: str) -> FredSeriesInfo:
        params = {"series_id": series_id}
        data = await self._client.get("/api/v1/fred/proxy/series", params=params)
        # Real Oracle: {"success": true, "data": {"seriess": [{id, title, frequency, ...}]}}
        inner = data.get("data", {})
        seriess = inner.get("seriess", [])
        if seriess:
            info = seriess[0]
            return FredSeriesInfo.model_validate({**info, "id": info.get("id", series_id)})
        return FredSeriesInfo(id=series_id)
