import datetime
from pathlib import Path
from typing import Annotated

from fastapi import APIRouter, Depends
from fastapi.responses import HTMLResponse, RedirectResponse

from gallery.easel.core import AppRequest
from gallery.sketch.schedule.api import ScheduleApi
from gallery.sketch.schedule.catalog import BUNDLE

from ..common.utils.tag import TagType, TagUtil
from ..common.utils.template import build_templates
from .filters import timedelta_format


async def get_schedule_api(request: AppRequest, provider: str | None = None) -> ScheduleApi:
    return request.app.state.api.get_schedule(provider)


ScheduleApiDepends = Annotated[ScheduleApi, Depends(get_schedule_api)]


def context_procesor(request: AppRequest) -> dict:
    return {
        "providers": request.app.state.api.get_api_providers(ScheduleApi.TYPE),
    }


templates = build_templates(
    Path(__file__).parent / "templates",
    {
        "timedelta_format": timedelta_format,
    },
)

router = APIRouter(prefix="/schedule")


@router.get("/", response_class=HTMLResponse)
async def get_schedule_list(request: AppRequest, schedule_api: ScheduleApiDepends):
    channels = await schedule_api.get_channels()
    channels_data = BUNDLE.select_items(channels)
    return templates.TemplateResponse(
        request=request,
        name="index.html",
        context={
            "channels": channels_data,
        },
    )


@router.get("/tag/{tag}", response_class=HTMLResponse)
async def get_schedule_tag(request: AppRequest, schedule_api: ScheduleApiDepends, tag: str, live: bool = False):
    tag_value = TagUtil.parse_tag(tag)
    results = await schedule_api.get_all_schedules(tag_value.date)
    return templates.TemplateResponse(
        request=request,
        name="schedule.html",
        context={
            "tag_util": TagUtil,
            "datetime": datetime,
            "response": results[0],
            "responses": results,
            "live": live,
        },
    )


@router.get("/{channel}", response_class=RedirectResponse)
async def get_channel_default(channel: str):
    return RedirectResponse(f"{channel}/tag/today")


@router.get("/{channel}/tag/{tag}", response_class=HTMLResponse)
async def get_channel_tag(request: AppRequest, schedule_api: ScheduleApiDepends, channel: str, tag: str):
    tag_value = TagUtil.parse_tag(tag)
    if tag_value.type == TagType.DAY:
        response = await schedule_api.get_channel_schedule(channel, tag_value.date)
    else:
        raise ValueError(tag)
    return templates.TemplateResponse(
        request=request,
        name="channel.html",
        context={
            "tag_util": TagUtil,
            "datetime": datetime,
            "response": response,
        },
    )
