"""
간단한 캘린더 API 라우터
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_
from typing import List
from datetime import datetime, date
from uuid import UUID
import logging

from ...core.database import get_db
from ...models.user import User
from ...models.todo import Todo
from ...schemas.todo import TodoResponse
from ..dependencies import get_current_active_user

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/calendar", tags=["calendar"])


@router.get("/todos", response_model=List[TodoResponse])
async def get_calendar_todos(
    start_date: date,
    end_date: date,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """캘린더용 Todo 목록 조회"""
    try:
        # 날짜 범위 내의 Todo들 조회
        query = select(Todo).where(
            and_(
                Todo.user_id == current_user.id,
                Todo.due_date >= start_date,
                Todo.due_date <= end_date
            )
        ).order_by(Todo.due_date.asc())
        
        result = await db.execute(query)
        todos = result.scalars().all()
        
        return todos
        
    except Exception as e:
        logger.error(f"캘린더 Todo 조회 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="캘린더 데이터 조회에 실패했습니다."
        )


@router.get("/today", response_model=List[TodoResponse])
async def get_today_todos(
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """오늘의 Todo 목록 조회"""
    try:
        today = date.today()
        
        query = select(Todo).where(
            and_(
                Todo.user_id == current_user.id,
                Todo.due_date == today
            )
        ).order_by(Todo.created_at.desc())
        
        result = await db.execute(query)
        todos = result.scalars().all()
        
        return todos
        
    except Exception as e:
        logger.error(f"오늘 Todo 조회 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="오늘 Todo 조회에 실패했습니다."
        )