from datetime import datetime
from pathlib import Path
from pprint import pprint

from dotenv import load_dotenv
from pydantic import TypeAdapter

from tariff_fetch.arcadia.api import ArcadiaSignalAPI
from tariff_fetch.arcadia.schema.lookup import Lookup
from tariff_fetch.arcadia.schema.tariff import TariffExtended
from tariff_fetch.urdb.arcadia import (
    Scenario,
    average_aligned_bands,
    build_urdb,
    get_rate_bands_at_datetime,
    get_tariff_bands_at_datetime,
    lookup_variable_rate,
)

load_dotenv()


def main():
    tariff_list_adapter = TypeAdapter(list[TariffExtended])
    tariffs = tariff_list_adapter.validate_json(Path("./outputs/arcadia.json").read_bytes(), by_name=True)
    tariff = tariffs[0]
    api = ArcadiaSignalAPI()
    scenario = Scenario(
        3633,
        2026,
        {},
    )
    result = get_tariff_bands_at_datetime(api, tariff, scenario, datetime(2026, 6, 1, 0, 30))
    # result = build_urdb(api, tariff, scenario)
    # assert "rates" in tariff
    # rate_id = 17275990
    # rate = next(rate for rate in tariff["rates"] if rate["tariff_rate_id"] == rate_id)
    # sampled_dts = list(iter_sampled_datetimes(2025, 1, 0, is_weekday))
    # band_sets = [get_rate_bands_at_datetime(api, rate, scenario, [], dt) for dt in sampled_dts]
    # bands = average_aligned_bands([_ for _ in band_sets if _ is not None])
    # result = get_rate_bands_at_datetime(api, rate, scenario, [], datetime(2025, 1, 1, 0, 30))

    pprint(result, indent=2)

    # lookups_adapter = TypeAdapter(dict[str, list[Lookup]])
    # api = ArcadiaSignalAPI()
    # result = fetch_tariff_property_lookups(api, tariff, 2025)
    # Path("./outputs/lookups.json").write_bytes(lookups_adapter.dump_json(result, indent=2, by_alias=True))
    # lookups = lookups_adapter.validate_json(Path("./outputs/lookups.json").read_bytes())
    # print(lookups)
    # build_urdb(tariff, lookups, 3633)


if __name__ == "__main__":
    main()
