"""Calendar download for an invitation (task 2.9, FR-1.8)."""

from fastapi import APIRouter, Depends, HTTPException, Response, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.config import get_settings
from app.db import get_session
from app.models import Event, Invitation
from app.services.calendar import build_ics

router = APIRouter(tags=["calendar"])


@router.get("/ics/{token}")
async def download_ics(
    token: str,
    session: AsyncSession = Depends(get_session),
) -> Response:
    invitation = await session.scalar(
        select(Invitation)
        .where(Invitation.token == token)
        .options(selectinload(Invitation.event).selectinload(Event.wedding))
    )
    if invitation is None or not invitation.event.is_published:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invitation not found")

    event = invitation.event
    wedding = event.wedding
    couple = f"{wedding.bride_name} & {wedding.groom_name}"
    settings = get_settings()
    host = settings.app_base_url.removeprefix("https://").removeprefix("http://")

    body = build_ics(
        uid=f"{invitation.id}@{host}",
        summary=f"{event.title_en} — {couple}",
        description=f"{event.title_en} of {couple}. {event.notes or ''}".strip(),
        location=f"{event.venue_name}, {event.venue_address}",
        starts_at=event.starts_at,
        ends_at=event.ends_at,
        url=f"{settings.app_base_url.rstrip('/')}/i/{invitation.token}",
    )

    return Response(
        content=body,
        media_type="text/calendar; charset=utf-8",
        headers={
            "Content-Disposition": f'attachment; filename="{event.slug}.ics"',
            "Cache-Control": "private, no-store",
            "Referrer-Policy": "no-referrer",
        },
    )
