from collections.abc import Collection
from typing import cast
from tariff_fetch.rateacuity.schema import Consumption, Tariff
from tariff_fetch.urdb.schema import EnergyTier, MonthSchedule, URDBRate


def build_urdb(tariff: Tariff):
    result = {}
    schedules = next()
    return build_energyschedule(tariff)


def build_energyschedule(tariff: Tariff) -> URDBRate:
    rates = cast(
        list[Consumption],
        next(
            values
            for section in tariff["sections"]
            for table in section["tables"]
            if "consumption" in (values := table["values"])[0]
        ),
    )
    monthly_rates = [get_monthly_rate(rates, month) for month in range(1, 13)]
    monthly_rates_structure = list(set(monthly_rates))
    monthly_rates_indices = [monthly_rates_structure.index(mr) for mr in monthly_rates]
    weekday_schedule = tuple(tuple([index] * 24) for index in monthly_rates_indices)
    energy_rate_structure: list[list[EnergyTier]] = [[{"rate": r}] for r in monthly_rates_structure]
    return {
        "energyratestructure": energy_rate_structure,
        "energyweekdayschedule": weekday_schedule,  # pyright: ignore[reportReturnType]
        "energyweekendschdule": weekday_schedule,
    }


def get_monthly_rate(rates: Collection[Consumption], month: int) -> float:
    return sum(
        rate["rate"]
        for rate in rates
        if (season := get_rate_applicable_month_range(rate))
        if season[0] <= month <= season[1]
    )


def get_rate_applicable_month_range(rate: Consumption) -> tuple[int, int]:
    season_start = 1
    season_end = 12
    if rate["season_start"] is not None:
        if not rate["season_start"].day == 1:
            raise RuntimeError("Start day of season is expected to be 1")
        season_start = rate["season_start"].month
    if rate["season_end"] is not None:
        season_end = rate["season_end"].month
    return season_start, season_end
