"""Retrieves and processes electricity price forecast data from Akkudoktor.

This module provides classes and mappings to manage electricity price data obtained from the
Akkudoktor API, including support for various electricity price attributes such as temperature,
humidity, cloud cover, and solar irradiance. The data is mapped to the `ElecPriceDataRecord`
format, enabling consistent access to forecasted and historical electricity price attributes.
"""

from typing import Any, List, Optional, Union

import pandas as pd
import requests
from loguru import logger
from pydantic import ValidationError

from akkudoktoreos.config.configabc import SettingsBaseModel
from akkudoktoreos.core.cache import cache_in_file
from akkudoktoreos.core.pydantic import PydanticBaseModel
from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider
from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration


class ElecPriceAkkudoktorCommonSettings(SettingsBaseModel):
    """Common configuration settings for Akkodoktor electricity pricing."""


class AkkudoktorElecPriceMeta(PydanticBaseModel):
    start_timestamp: str
    end_timestamp: str
    start: str
    end: str


class AkkudoktorElecPriceValue(PydanticBaseModel):
    start_timestamp: int
    end_timestamp: int
    start: str
    end: str
    marketprice: float
    unit: str
    marketpriceEurocentPerKWh: float


class AkkudoktorElecPrice(PydanticBaseModel):
    meta: AkkudoktorElecPriceMeta
    values: List[AkkudoktorElecPriceValue]


class ElecPriceAkkudoktor(ElecPriceProvider):
    """Fetch and process electricity price forecast data from Akkudoktor.

    ElecPriceAkkudoktor is a singleton-based class that retrieves electricity price forecast data
    from the Akkudoktor API and maps it to `ElecPriceDataRecord` fields, applying
    any necessary scaling or unit corrections. It manages the forecast over a range
    of hours into the future and retains historical data.

    Attributes:
        hours (int, optional): Number of hours in the future for the forecast.
        historic_hours (int, optional): Number of past hours for retaining data.
        start_datetime (datetime, optional): Start datetime for forecasts, defaults to the current datetime.
        end_datetime (datetime, computed): The forecast's end datetime, computed based on `start_datetime` and `hours`.
        keep_datetime (datetime, computed): The datetime to retain historical data, computed from `start_datetime` and `historic_hours`.

    Methods:
        provider_id(): Returns a unique identifier for the provider.
        _request_forecast(): Fetches the forecast from the Akkudoktor API.
        _update_data(): Processes and updates forecast data from Akkudoktor in ElecPriceDataRecord format.
    """

    highest_orig_datetime: Optional[DateTime] = None

    @classmethod
    def provider_id(cls) -> str:
        """Return the unique identifier for the Akkudoktor provider."""
        return "ElecPriceAkkudoktor"

    @classmethod
    def _validate_data(cls, json_str: Union[bytes, Any]) -> AkkudoktorElecPrice:
        """Validate Akkudoktor Electricity Price forecast data."""
        try:
            akkudoktor_data = AkkudoktorElecPrice.model_validate_json(json_str)
        except ValidationError as e:
            error_msg = ""
            for error in e.errors():
                field = " -> ".join(str(x) for x in error["loc"])
                message = error["msg"]
                error_type = error["type"]
                error_msg += f"Field: {field}\nError: {message}\nType: {error_type}\n"
            logger.error(f"Akkudoktor schema change: {error_msg}")
            raise ValueError(error_msg)
        return akkudoktor_data

    @cache_in_file(with_ttl="1 hour")
    def _request_forecast(self) -> AkkudoktorElecPrice:
        """Fetch electricity price forecast data from Akkudoktor API.

        This method sends a request to Akkudoktor's API to retrieve forecast data for a specified
        date range. The response data is parsed and returned as JSON for further processing.

        Returns:
            dict: The parsed JSON response from Akkudoktor API containing forecast data.

        Raises:
            ValueError: If the API response does not include expected `electricity price` data.

        Todo:
            - add the file cache again.
        """
        source = "https://api.akkudoktor.net"
        if not self.ems_start_datetime:
            raise ValueError(f"Start DateTime not set: {self.ems_start_datetime}")
        # Try to take data from 5 weeks back for prediction
        date = to_datetime(self.ems_start_datetime - to_duration("35 days"), as_string="YYYY-MM-DD")
        last_date = to_datetime(self.end_datetime, as_string="YYYY-MM-DD")
        url = f"{source}/prices?start={date}&end={last_date}&tz={self.config.general.timezone}"
        response = requests.get(url, timeout=10)
        logger.debug(f"Response from {url}: {response}")
        response.raise_for_status()  # Raise an error for bad responses
        akkudoktor_data = self._validate_data(response.content)
        # We are working on fresh data (no cache), report update time
        self.update_datetime = to_datetime(in_timezone=self.config.general.timezone)
        return akkudoktor_data

    async def _update_data(self, force_update: Optional[bool] = False) -> None:
        """Update forecast data in the ElecPriceDataRecord format.

        Retrieves data from Akkudoktor, maps each Akkudoktor field to the corresponding
        `ElecPriceDataRecord` and applies any necessary scaling.

        The final mapped and processed data is inserted into the sequence as `ElecPriceDataRecord`.
        """
        # Get Akkudoktor electricity price data
        if not self.ems_start_datetime:
            raise ValueError(f"Start DateTime not set: {self.ems_start_datetime}")

        akkudoktor_data = self._request_forecast(force_update=force_update)  # type: ignore

        # Assumption that all lists are the same length and are ordered chronologically
        # in ascending order and have the same timestamps.

        highest_orig_datetime = None  # newest datetime from the api after that we want to update.
        prices_wh = pd.Series(dtype=float)  # Initialize an empty series

        for value in akkudoktor_data.values:
            orig_datetime = to_datetime(value.start, in_timezone=self.config.general.timezone)
            if highest_orig_datetime is None or orig_datetime > highest_orig_datetime:
                highest_orig_datetime = orig_datetime

            price_wh = value.marketpriceEurocentPerKWh / (100 * 1000)

            # Collect all values into the Pandas Series
            prices_wh.at[orig_datetime] = price_wh

        if not highest_orig_datetime:  # mypy fix
            error_msg = f"Highest original datetime not available: {highest_orig_datetime}"
            logger.error(error_msg)
            raise ValueError(error_msg)
        self.highest_orig_datetime = highest_orig_datetime

        # Every cycle fetches fresh data (no skip-fetch branch here, unlike
        # ElecPriceEnergyCharts), so the gross-series recompute always needs to
        # cover at least the freshly fetched range, in addition to the
        # forward-looking window from ems_start_datetime.
        gross_start_datetime = (
            min(self.ems_start_datetime, prices_wh.index.min())
            if not prices_wh.empty
            else self.ems_start_datetime
        )

        # Always raw here - fees are applied once, later, over the complete
        # raw+predicted series in _store_gross_series().
        await self.key_from_series("elecprice_marketprice_raw_wh", prices_wh)

        # Raw history only, so ETS/median always trains on the true
        # wholesale-price signal, never on fee-inclusive values.
        history = await self.key_to_array(
            key="elecprice_marketprice_raw_wh",
            end_datetime=highest_orig_datetime,
            fill_method="linear",
        )

        # Some of our data is already in the future, so we need to predict less.
        # If we got less data we increase the prediction hours
        needed_hours = int(
            self.config.prediction.hours
            - ((highest_orig_datetime - self.ems_start_datetime).total_seconds() // 3600)
        )

        if needed_hours <= 0:
            # This might keep data longer than
            # self.ems_start_datetime + self.config.prediction.hours in the records
            logger.warning(
                f"No prediction needed. needed_hours={needed_hours}, "
                f"hours={self.config.prediction.hours}, "
                f"highest_orig_datetime {highest_orig_datetime}, "
                f"start_datetime {self.ems_start_datetime}"
            )
            # Fee schedule may have changed since the last run even without new
            # market data; recompute gross only for the window that was
            # actually touched (or is still forward-looking) this cycle.
            await self._store_gross_series(
                start_datetime=gross_start_datetime,
                end_datetime=self.highest_orig_datetime + to_duration("1 second"),
            )
            return

        prediction = self._predict(history, needed_hours)

        # write predictions into the records, update if exist.
        prediction_series = pd.Series(
            data=prediction,
            index=[
                highest_orig_datetime + to_duration(f"{i + 1} hours")
                for i in range(len(prediction))
            ],
        )
        await self.key_from_series("elecprice_marketprice_raw_wh", prediction_series)

        # Bounded to [gross_start_datetime, end of the freshly predicted tail) -
        # covers exactly what was fetched and/or predicted this cycle, not the
        # entire (potentially multi-year) retained history.
        await self._store_gross_series(
            start_datetime=gross_start_datetime,
            end_datetime=prediction_series.index.max() + to_duration("1 second"),
        )
