"""
할일관리 API 라우터 (간결 버전)
- API 라우터 기준: 최대 400줄
- 간결함 원칙: 라우팅만 담당, 비즈니스 로직은 서비스로 분리
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from uuid import UUID
import logging

from ...core.database import get_db
from ...models.user import User
from ...schemas.todo import (
    TodoItemCreate, TodoItemSchedule, TodoItemDelay, TodoItemSplit,
    TodoItemResponse, TodoCommentCreate, TodoCommentResponse
)
from ..dependencies import get_current_active_user
from ...services.todo_service import TodoService
from ...services.calendar_sync_service import get_calendar_sync_service
from ...services.file_service import save_base64_image

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


# ============================================================================
# 이미지 업로드
# ============================================================================

@router.post("/upload-image")
async def upload_image(
    image: UploadFile = File(...),
    current_user: User = Depends(get_current_active_user)
):
    """이미지 업로드"""
    try:
        # 파일 형식 확인
        if not image.content_type.startswith('image/'):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="이미지 파일만 업로드 가능합니다."
            )
        
        # 파일 크기 확인 (5MB 제한)
        contents = await image.read()
        if len(contents) > 5 * 1024 * 1024:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="파일 크기는 5MB를 초과할 수 없습니다."
            )
        
        # Base64로 변환하여 저장
        import base64
        base64_string = f"data:{image.content_type};base64,{base64.b64encode(contents).decode()}"
        
        # 파일 저장
        file_url = save_base64_image(base64_string)
        if not file_url:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="이미지 저장에 실패했습니다."
            )
        
        return {"url": file_url}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"이미지 업로드 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="이미지 업로드에 실패했습니다."
        )


# ============================================================================
# 할일 아이템 관리
# ============================================================================

@router.post("/", response_model=TodoItemResponse)
async def create_todo_item(
    todo_data: TodoItemCreate,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """새 할일 생성"""
    try:
        service = TodoService(db)
        return await service.create_todo(todo_data, current_user.id)
        
    except Exception as e:
        await db.rollback()
        logger.error(f"할일 생성 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.post("/{todo_id}/schedule", response_model=TodoItemResponse)
async def schedule_todo_item(
    todo_id: UUID,
    schedule_data: TodoItemSchedule,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """할일 일정 설정 및 캘린더 동기화"""
    try:
        service = TodoService(db)
        result = await service.schedule_todo(todo_id, schedule_data, current_user.id)
        
        # 🔄 캘린더 동기화 (백그라운드)
        sync_service = get_calendar_sync_service()
        todo_item = await service._get_user_todo(todo_id, current_user.id)
        await sync_service.sync_todo_create(todo_item)
        
        return result
        
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        await db.rollback()
        logger.error(f"할일 일정 설정 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.put("/{todo_id}/complete", response_model=TodoItemResponse)
async def complete_todo_item(
    todo_id: UUID,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """할일 완료 및 캘린더 업데이트"""
    try:
        service = TodoService(db)
        result = await service.complete_todo(todo_id, current_user.id)
        
        # 🔄 캘린더 동기화 (완료 태그 변경)
        sync_service = get_calendar_sync_service()
        todo_item = await service._get_user_todo(todo_id, current_user.id)
        await sync_service.sync_todo_complete(todo_item)
        
        return result
        
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        await db.rollback()
        logger.error(f"할일 완료 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.put("/{todo_id}/delay", response_model=TodoItemResponse)
async def delay_todo_item(
    todo_id: UUID,
    delay_data: TodoItemDelay,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """할일 지연 및 캘린더 날짜 수정"""
    try:
        service = TodoService(db)
        result = await service.delay_todo(todo_id, delay_data, current_user.id)
        
        # 🔄 캘린더 동기화 (날짜 수정)
        sync_service = get_calendar_sync_service()
        todo_item = await service._get_user_todo(todo_id, current_user.id)
        await sync_service.sync_todo_delay(todo_item)
        
        return result
        
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        await db.rollback()
        logger.error(f"할일 지연 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.post("/{todo_id}/split", response_model=List[TodoItemResponse])
async def split_todo_item(
    todo_id: UUID,
    split_data: TodoItemSplit,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """할일 분할"""
    try:
        service = TodoService(db)
        return await service.split_todo(todo_id, split_data, current_user.id)
        
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        await db.rollback()
        logger.error(f"할일 분할 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.get("/", response_model=List[TodoItemResponse])
async def get_todo_items(
    status: Optional[str] = Query(None, regex="^(draft|scheduled|active|completed|delayed)$"),
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """할일 목록 조회"""
    try:
        service = TodoService(db)
        return await service.get_todos(current_user.id, status)
        
    except Exception as e:
        logger.error(f"할일 목록 조회 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.get("/active", response_model=List[TodoItemResponse])
async def get_active_todos(
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """오늘 활성화된 할일들 조회"""
    try:
        service = TodoService(db)
        return await service.get_active_todos(current_user.id)
        
    except Exception as e:
        logger.error(f"활성 할일 조회 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


# ============================================================================
# 댓글 관리
# ============================================================================

@router.post("/{todo_id}/comments", response_model=TodoCommentResponse)
async def create_todo_comment(
    todo_id: UUID,
    comment_data: TodoCommentCreate,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """할일에 댓글 추가"""
    try:
        service = TodoService(db)
        return await service.create_comment(todo_id, comment_data, current_user.id)
        
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        await db.rollback()
        logger.error(f"댓글 생성 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.get("/{todo_id}/comments", response_model=List[TodoCommentResponse])
async def get_todo_comments(
    todo_id: UUID,
    current_user: User = Depends(get_current_active_user),
    db: AsyncSession = Depends(get_db)
):
    """할일 댓글 목록 조회"""
    try:
        service = TodoService(db)
        return await service.get_comments(todo_id, current_user.id)
        
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"댓글 조회 실패: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )