"""
Projects API - Episodes Module

包含剧集管理相关的 API 路由。
"""

import logging
import uuid

from fastapi import APIRouter, Depends

from src.models.schemas import (
    ResponseModel,
    Episode, CreateEpisodeRequest, UpdateEpisodeRequest,
)
from src.auth.dependencies import get_current_user
from src.auth.models import UserAuth
from src.services.project_service import project_manager
from src.utils.errors import ErrorCode, AppException

logger = logging.getLogger(__name__)

router = APIRouter(tags=["projects-episodes"])


def _check_project_access(project_id: str, user_id: str):
    """检查用户是否有权限访问项目"""
    project = project_manager.get_project(project_id, user_id=user_id)
    return project


# --- Episode Management ---
@router.post("/projects/{project_id}/episodes", response_model=ResponseModel)
async def create_episode(
    project_id: str,
    request: CreateEpisodeRequest,
    current_user: UserAuth = Depends(get_current_user)
):
    """Create a new episode"""
    try:
        # Check project access
        if not _check_project_access(project_id, current_user.id):
            raise AppException(
                message="Project not found or access denied",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        episode_id = str(uuid.uuid4())
        new_episode = Episode(
            id=episode_id,
            title=request.title,
            order=request.order,
            desc=request.desc,
            status=request.status
        )
        updated_project = project_manager.add_episode(project_id, new_episode)
        if not updated_project:
            raise AppException(
                message="Project not found or operation failed",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
        return ResponseModel(data=updated_project)
    except Exception as e:
        raise AppException(
                message=str(e),
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )

@router.put("/projects/{project_id}/episodes/{episode_id}", response_model=ResponseModel)
async def update_episode(
    project_id: str,
    episode_id: str,
    request: UpdateEpisodeRequest,
    current_user: UserAuth = Depends(get_current_user)
):
    """Update an episode"""
    try:
        project = project_manager.get_project(project_id, user_id=current_user.id)
        if not project:
             raise AppException(
                message="Project not found or access denied",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        existing_ep = next((ep for ep in project.episodes if ep.id == episode_id), None)
        if not existing_ep:
             raise AppException(
                message="Episode not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        update_data = request.model_dump(exclude_unset=True, by_alias=True)
        updated_ep = existing_ep.model_copy(update=update_data)

        updated_project = project_manager.update_episode(project_id, episode_id, updated_ep)
        return ResponseModel(data=updated_project)
    except Exception as e:
        raise AppException(
                message=str(e),
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )

@router.delete("/projects/{project_id}/episodes/{episode_id}", response_model=ResponseModel)
async def delete_episode(
    project_id: str,
    episode_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """Delete an episode"""
    try:
        project = project_manager.get_project(project_id, user_id=current_user.id)
        if not project:
            raise AppException(
                message="Project not found or access denied",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        updated_project = project_manager.delete_episode(project_id, episode_id)
        if not updated_project:
            raise AppException(
                message="Project not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
        return ResponseModel(data=updated_project)
    except Exception as e:
        raise AppException(
                message=str(e),
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )


@router.post("/projects/{project_id}/episodes/{episode_id}/analyze", response_model=ResponseModel)
async def analyze_episode(
    project_id: str,
    episode_id: str,
    current_user: UserAuth = Depends(get_current_user)
):
    """
    Analyze a specific episode: extract summary, characters/scenes/props, storyboards.
    """
    try:
        from src.services.episode_analysis_service import analyze_episode as analyze_episode_service
        final_project = await analyze_episode_service(project_id, episode_id, current_user.id)
        return ResponseModel(data=final_project)
    except ValueError as e:
        msg = str(e)
        if "not found" in msg.lower():
            raise AppException(
                message=msg,
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )
        if "empty" in msg.lower():
            raise AppException(
                message=msg,
                code=ErrorCode.INVALID_PARAMETER,
                status_code=400
            )
        raise AppException(
            message=msg,
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )
    except Exception as e:
        logger.error("Episode analysis failed: %s", e, exc_info=True)
        raise AppException(
                message=str(e),
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )
