"""
Projects API - Storyboards Module

包含分镜管理相关的 API 路由。
"""

import logging
import uuid
from typing import List

from fastapi import APIRouter

from pydantic import TypeAdapter

from src.models.schemas import (
    ResponseModel,
    Storyboard, CreateStoryboardRequest, UpdateStoryboardRequest,
    GenerationRecord,
)
from src.utils.errors import ErrorCode, AppException

logger = logging.getLogger(__name__)

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


# --- Storyboard Management ---
@router.post("/projects/{project_id}/storyboards", response_model=ResponseModel)
async def create_storyboard(project_id: str, request: CreateStoryboardRequest):
    """Create a new storyboard"""
    try:
        from src.services.project_service import project_manager

        sb_id = str(uuid.uuid4())
        sb_data = request.model_dump(by_alias=True)
        sb_data['id'] = sb_id

        new_sb = Storyboard(**sb_data)

        updated_project = project_manager.add_storyboard(project_id, new_sb)
        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.put("/projects/{project_id}/storyboards/{storyboard_id}", response_model=ResponseModel)
async def update_storyboard(project_id: str, storyboard_id: str, request: UpdateStoryboardRequest):
    """Update a storyboard"""
    try:
        from src.services.project_service import project_manager

        project = project_manager.get_project(project_id)
        if not project:
             raise AppException(
                message="Project not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        existing_sb = next((sb for sb in project.storyboards if sb.id == storyboard_id), None)
        if not existing_sb:
             raise AppException(
                message="Storyboard not found",
                code=ErrorCode.NOT_FOUND,
                status_code=404
            )

        update_data = request.model_dump(exclude_unset=True, by_alias=True)

        # Manually validate generations if present to ensure they are model instances not dicts
        if 'generations' in update_data and update_data['generations']:
            update_data['generations'] = TypeAdapter(List[GenerationRecord]).validate_python(update_data['generations'])

        updated_sb = existing_sb.model_copy(update=update_data)

        updated_project = project_manager.update_storyboard(project_id, storyboard_id, updated_sb)
        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}/storyboards/{storyboard_id}", response_model=ResponseModel)
async def delete_storyboard(project_id: str, storyboard_id: str):
    """Delete a storyboard"""
    try:
        from src.services.project_service import project_manager

        updated_project = project_manager.delete_storyboard(project_id, storyboard_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
            )
