import abc
from typing import Any, Literal

from pydantic import Field

from bayesline.api._src._utils import docstrings_from_sync
from bayesline.api._src.equity.portfolioreport import (
    AsyncReportAccessorApi,
    ReportAccessorApi,
)
from bayesline.api._src.equity.report.accessor import (
    AsyncTypedReportAccessorApi,
    TypedReportAccessorApi,
)
from bayesline.api._src.equity.report.api import AsyncReportApi, ReportApi
from bayesline.api._src.equity.report.settings import IdioVolSettings, ReportSettings
from bayesline.api._src.equity.riskmodels_settings import FactorRiskModelSettings
from bayesline.api._src.tasks import AsyncTask, Task
from bayesline.api._src.types import DateLike


class IdioReportSettings(ReportSettings):
    """Settings for an idiosyncratic return and volatility report."""

    report_type: Literal["idio"] = Field(
        default="idio", description="Report type discriminator"
    )
    factor_model_settings: FactorRiskModelSettings = Field()
    idio_vol_settings: IdioVolSettings = Field(
        default_factory=IdioVolSettings,
        description="Settings for the idiosyncratic volatility matrix forecasts.",
    )
    annualize: bool = Field(
        default=True,
        description="Whether to annualize the idio vol (multiply variance by 252)",
    )


class IdioReportAccessor(TypedReportAccessorApi):
    """Accessor for an idiosyncratic return and volatility report."""

    pass


@docstrings_from_sync
class AsyncIdioReportAccessor(AsyncTypedReportAccessorApi):
    pass


class IdioReportApi(
    ReportApi[[DateLike, DateLike], IdioReportAccessor, IdioReportSettings]
):
    """API for an idiosyncratic return and volatility report."""

    @abc.abstractmethod
    def get_maybe_cached(
        self,
        start_date: DateLike | None,
        end_date: DateLike | None,
        **kwargs: Any,
    ) -> IdioReportAccessor | None:
        """
        Get the cached idio report accessor API if it is available.

        Parameters
        ----------
        start_date: DateLike | None
            The start date of the report.
        end_date: DateLike | None
            The end date of the report.
        **kwargs: Any
            Additional keyword arguments.

        Returns
        -------
        IdioReportAccessor | None
            The cached idio report accessor API, or None if not cached.
        """

    @abc.abstractmethod
    def calculate(
        self,
        start_date: DateLike | None,
        end_date: DateLike | None,
        **kwargs: Any,
    ) -> IdioReportAccessor:
        """
        Calculate the idio report.

        Parameters
        ----------
        start_date: DateLike | None
            The start date of the report.
        end_date: DateLike | None
            The end date of the report.
        **kwargs: Any
            Additional keyword arguments.

        Returns
        -------
        IdioReportAccessor
            The idio report accessor.
        """

    @abc.abstractmethod
    def calculate_as_task(
        self,
        start_date: DateLike | None,
        end_date: DateLike | None,
        **kwargs: Any,
    ) -> Task[IdioReportAccessor]:
        """
        Calculate the idio report as a task.

        Parameters
        ----------
        start_date: DateLike | None
            The start date of the report.
        end_date: DateLike | None
            The end date of the report.
        **kwargs: Any
            Additional keyword arguments.

        Returns
        -------
        Task[IdioReportAccessor]
            The task for the idio report accessor.
        """


@docstrings_from_sync
class AsyncIdioReportApi(
    AsyncReportApi[
        [DateLike | None, DateLike | None],
        AsyncIdioReportAccessor,
        IdioReportSettings,
    ]
):

    @abc.abstractmethod
    async def get_maybe_cached(  # noqa: D102
        self,
        start_date: DateLike | None,
        end_date: DateLike | None,
        **kwargs: Any,
    ) -> AsyncIdioReportAccessor | None: ...

    @abc.abstractmethod
    async def calculate(  # noqa: D102
        self,
        start_date: DateLike | None,
        end_date: DateLike | None,
        **kwargs: Any,
    ) -> AsyncIdioReportAccessor: ...

    @abc.abstractmethod
    async def calculate_as_task(  # noqa: D102
        self,
        start_date: DateLike | None,
        end_date: DateLike | None,
        **kwargs: Any,
    ) -> AsyncTask[AsyncIdioReportAccessor]: ...


class IdioReportAccessorImpl(IdioReportAccessor):  # noqa: D101

    def __init__(self, accessor: ReportAccessorApi):
        self._accessor = accessor

    @property
    def accessor(self) -> ReportAccessorApi:  # noqa: D102
        return self._accessor


class AsyncIdioReportAccessorImpl(AsyncIdioReportAccessor):  # noqa: D101

    def __init__(self, accessor: AsyncReportAccessorApi):
        self._accessor = accessor

    @property
    def accessor(self) -> AsyncReportAccessorApi:  # noqa: D102
        return self._accessor
