import datetime
from pathlib import Path

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

from gallery.easel.core import AppRequest
from gallery.easel.depends.api import api_resolver
from gallery.easel.depends.schedule import ScheduleApiDepends
from gallery.sketch.schedule.api import ScheduleApi

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


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


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

router = APIRouter(prefix="/schedule")


@router.get("/", response_class=HTMLResponse)
async def get_schedule_index(request: AppRequest, provider: str | None = None, query: str | None = None):
    if query and provider:
        schedule_api = api_resolver(ScheduleApi)(request, provider)
        channels = await schedule_api.find_channels(query)
    else:
        channels = []
    return templates.TemplateResponse(
        request=request,
        name="index.html",
        context={
            "channels": channels,
        },
    )


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


@router.get("/{provider}/{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_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,
        },
    )
