import datetime
import logging

from bs4 import BeautifulSoup

from gallery.sketch.schedule.api import ScheduleApi
from gallery.sketch.schedule.model import Channel, ChannelId, Schedule, ScheduleValue
from gallery.sketch.source import ApiSource

logger = logging.getLogger("matchtv")


class MatchTvApi(ScheduleApi):
    PROVIDER = "matchtv"
    SOURCE = ApiSource("https://matchtv.ru")

    async def get_channels(self) -> list[ChannelId]:
        return [
            ChannelId.MATCH_TV,
            ChannelId.MATCH_IGRA,
            ChannelId.MATCH_ARENA,
            ChannelId.MATCH_FUTBOL_1,
            ChannelId.MATCH_FUTBOL_2,
            ChannelId.MATCH_FUTBOL_3,
            ChannelId.MATCH_STRANA,
        ]

    async def get_channel_schedule(self, channel_id: ChannelId, date: datetime.date) -> Schedule:
        endpoint = f"tvguide/{channel_id}?date={date:%Y%m%d}"
        data = await self.SOURCE.request(endpoint)
        soup = BeautifulSoup(data, features="html.parser")
        values = []
        channel_name = soup.select_one(".p-tv-guide-header__title").text.replace("Телепрограмма ", "").strip()
        current_day = datetime.datetime.combine(date.today(), datetime.datetime.min.time())
        end = current_day + datetime.timedelta(days=1, hours=6)
        prev_value: ScheduleValue | None = None
        for item in soup.select(
            ".p-tv-guide-schedule-channel-carcass__transmissions .p-tv-guide-schedule-channel-transmission"
        ):
            title = item.select_one(".p-tv-guide-schedule-channel-transmission__title").text.strip()
            time_str = item.select_one(".p-tv-guide-schedule-channel-transmission__time-block").text.strip()
            hours, minutes = map(int, time_str.split(":"))
            item_date = current_day.replace(hour=hours, minute=minutes)
            if prev_value is not None and item_date.hour < prev_value.start.hour:
                current_day += datetime.timedelta(days=1)
                item_date += datetime.timedelta(days=1)
            live = "Прямая трансляция" in title
            value = ScheduleValue(start=item_date, end=end, label=title, live=live)
            values.append(value)
            if prev_value is not None:
                prev_value.end = item_date
            prev_value = value
        return Schedule(channel=Channel(id=channel_id, name=channel_name), date=date, values=values)
