"""
캘린더 연동 API 라우터
- API 라우터 기준: 최대 400줄
- 간결함 원칙: 캘린더 설정 및 동기화 기능만 포함
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Dict, Any, Optional
from uuid import UUID
import logging

from ...core.database import get_db
from ...models.user import User
from ...models.todo import TodoItem
from ..dependencies import get_current_active_user
from ...integrations.calendar import get_calendar_router, CalendarProvider

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


@router.post("/providers/register")
async def register_calendar_provider(
    provider_data: Dict[str, Any],
    current_user: User = Depends(get_current_active_user)
):
    """캘린더 제공자 등록"""
    try:
        provider_name = provider_data.get("provider")
        credentials = provider_data.get("credentials", {})
        set_as_default = provider_data.get("default", False)
        
        if not provider_name:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Provider name is required"
            )
        
        provider = CalendarProvider(provider_name)
        calendar_router = get_calendar_router()
        
        success = await calendar_router.register_provider(
            provider, credentials, set_as_default
        )
        
        if success:
            return {"message": f"{provider_name} 캘린더 등록 성공"}
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"{provider_name} 캘린더 등록 실패"
            )
            
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="지원하지 않는 캘린더 제공자"
        )
    except Exception as e:
        logger.error(f"캘린더 제공자 등록 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.get("/providers")
async def get_registered_providers(
    current_user: User = Depends(get_current_active_user)
):
    """등록된 캘린더 제공자 목록 조회"""
    try:
        calendar_router = get_calendar_router()
        providers = calendar_router.get_registered_providers()
        
        return {
            "providers": providers,
            "default": calendar_router.default_provider.value if calendar_router.default_provider else None
        }
        
    except Exception as e:
        logger.error(f"캘린더 제공자 조회 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.get("/calendars")
async def get_all_calendars(
    current_user: User = Depends(get_current_active_user)
):
    """모든 등록된 제공자의 캘린더 목록 조회"""
    try:
        calendar_router = get_calendar_router()
        calendars = await calendar_router.get_all_calendars()
        
        return calendars
        
    except Exception as e:
        logger.error(f"캘린더 목록 조회 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.post("/sync/{todo_id}")
async def sync_todo_to_calendar(
    todo_id: UUID,
    sync_config: Optional[Dict[str, Any]] = None,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """특정 할일을 캘린더에 동기화"""
    try:
        from sqlalchemy import select, and_
        
        # 할일 조회
        result = await db.execute(
            select(TodoItem).where(
                and_(
                    TodoItem.id == todo_id,
                    TodoItem.user_id == current_user.id
                )
            )
        )
        todo_item = result.scalar_one_or_none()
        
        if not todo_item:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Todo item not found"
            )
        
        # 캘린더 동기화
        calendar_router = get_calendar_router()
        calendar_configs = sync_config.get("calendars") if sync_config else None
        
        result = await calendar_router.sync_todo_to_calendars(
            todo_item, calendar_configs
        )
        
        return {
            "message": "캘린더 동기화 완료",
            "result": result
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"캘린더 동기화 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.get("/health")
async def calendar_health_check(
    current_user: User = Depends(get_current_active_user)
):
    """캘린더 서비스 상태 확인"""
    try:
        calendar_router = get_calendar_router()
        health_status = await calendar_router.health_check()
        
        return health_status
        
    except Exception as e:
        logger.error(f"캘린더 상태 확인 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )
