"""将剧本项目转换为画布项目的后台服务。"""
import logging
from typing import Callable, Optional

from src.services.project_service import project_manager
from src.services.episode_analysis_service import analyze_episode

logger = logging.getLogger(__name__)

ProgressCallback = Callable[[str, int, str, Optional[dict]], None]


async def convert_script_project_to_canvas(
    source_project_id: str,
    target_project_id: str,
    progress_callback: ProgressCallback,
    user_id: Optional[str] = None,
) -> None:
    """
    将 script 项目的文字剧本逐集转换为 canvas 项目的素材和分镜。
    """
    try:
        source_project = project_manager.get_project(source_project_id, user_id=user_id)
        target_project = project_manager.get_project(target_project_id, user_id=user_id)
        if not source_project or source_project.type != "script":
            raise ValueError("Source script project not found")
        if not target_project:
            raise ValueError("Target canvas project not found")

        total_episodes = len(target_project.episodes or [])
        if total_episodes == 0:
            project_manager.update_project(
                target_project_id,
                {
                    "description": source_project.description,
                    "status": "active",
                    "progress": None,
                },
            )
            return

        progress_callback("preparing", 10, "正在准备画布项目...", {"episodes_count": total_episodes})

        for index, episode in enumerate(target_project.episodes, start=1):
            start = 10 + int((index - 1) / total_episodes * 75)
            end = 10 + int(index / total_episodes * 75)
            progress_callback(
                "converting_episode",
                start,
                f"正在转换第 {index}/{total_episodes} 集为画布素材...",
                {
                    "episode_id": episode.id,
                    "episode_title": episode.title,
                    "episode_index": index,
                    "episodes_count": total_episodes,
                },
            )
            await analyze_episode(target_project_id, episode.id, user_id=user_id)
            progress_callback(
                "converting_episode",
                end,
                f"第 {index}/{total_episodes} 集转换完成",
                {
                    "episode_id": episode.id,
                    "episode_title": episode.title,
                    "episode_index": index,
                    "episodes_count": total_episodes,
                },
            )

        progress_callback("finalizing", 95, "正在完成画布项目整理...", None)
        project_manager.update_project(
            target_project_id,
            {
                "description": source_project.description,
                "status": "active",
                "progress": None,
            },
        )
    except Exception as e:
        logger.error("Script to canvas conversion failed: %s", e, exc_info=True)
        project_manager.update_project(
            target_project_id,
            {
                "status": "failed",
                "description": f"Canvas conversion failed: {str(e)}",
                "error": {"message": str(e), "type": type(e).__name__},
                "progress": None,
            },
        )
        raise
