"""Financial data Oracle service methods."""

from __future__ import annotations

from libs.oracle_client.client import OracleClient
from libs.oracle_client.models import CompanyInfo, FinancialDataResponse, FinancialPeriod


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

    async def get_financial_data(self, ticker: str, quarters: int = 8) -> FinancialDataResponse:
        # Oracle accepts period param (e.g. "2y"), convert quarters to approximate years
        years = max(1, (quarters + 3) // 4)
        data = await self._client.get(
            f"/api/v1/financial/data/{ticker}", params={"period": f"{years}y"}
        )
        # Real Oracle: {"company": {...}, "financial_data": [{period_date, ...}]}
        periods = []
        for p in data.get("financial_data", []):
            period_date = p.get("period_date", "")
            period_end = period_date[:10] if period_date else ""
            periods.append(
                FinancialPeriod(
                    period=period_end,
                    period_end=period_end,
                    revenue=p.get("revenue"),
                    net_income=p.get("net_income"),
                    eps=p.get("eps"),
                    gross_margin=p.get("gross_margin"),
                    operating_margin=p.get("operating_margin"),
                )
            )
        return FinancialDataResponse(ticker=ticker, periods=periods)

    async def get_company_info(self, ticker: str) -> CompanyInfo:
        data = await self._client.get(f"/api/v1/financial/data/{ticker}", params={"period": "1y"})
        company = data.get("company", {})
        return CompanyInfo(
            ticker=company.get("ticker", ticker),
            name=company.get("name"),
            cik=company.get("cik"),
            exchange=company.get("exchange"),
            sector=company.get("sector"),
            industry=company.get("industry"),
            country=company.get("country"),
            market_cap=company.get("market_cap"),
        )
