"""study_reminders API — 알람 재료 조회 (공부 암기노트 Phase 1, A 워크스트림).

GET /latest = 가장 최근 발화된 알람 1건(현재 due 스냅샷). 없으면 204.
종일 오프라인 후 과거 슬롯(09/13시)은 유실 = 의도("현재 due만"). push 채널·디바이스 UX 는 P3.
별 라우터(prefix=/api/study-reminders)로 /study-topics·/study-questions 경로와 충돌 회피.
"""

from __future__ import annotations

from datetime import datetime
from typing import Annotated

from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from core.auth import get_current_user
from core.database import get_session
from models.study_reminder import StudyReminder
from models.user import User

router = APIRouter()


class ReminderResponse(BaseModel):
    id: int
    due_count: int | None = None
    focus_topic_names: list | None = None
    fired_at: datetime


@router.get("/latest", response_model=ReminderResponse)
async def latest_reminder(
    user: Annotated[User, Depends(get_current_user)],
    session: Annotated[AsyncSession, Depends(get_session)],
):
    """현재 due 요약 1건. 없으면 204 No Content."""
    row = (
        await session.execute(
            select(StudyReminder)
            .where(StudyReminder.user_id == user.id)
            .order_by(StudyReminder.fired_at.desc())
            .limit(1)
        )
    ).scalar_one_or_none()
    if row is None:
        return Response(status_code=204)
    return ReminderResponse(
        id=row.id,
        due_count=row.due_count,
        focus_topic_names=row.focus_topic_names,
        fired_at=row.fired_at,
    )
