"""从小说文本初始化剧本项目的业务逻辑（后台管道）。"""
import logging
from typing import Callable, Optional

from src.services.project_service import project_manager
from src.services.script import script_service

logger = logging.getLogger(__name__)

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


async def run_script_project_initialization(
    project_id: str,
    novel_text: str,
    progress_callback: ProgressCallback,
    user_id: Optional[str] = None,
    model_name: Optional[str] = None,
    provider: Optional[str] = None,
) -> None:
    """
    在后台执行剧本项目初始化：分析小说 -> 多 Agent 讨论改编 -> 生成文字剧本。
    """
    try:
        logger.info("Starting script project initialization for project %s", project_id)

        progress_callback("starting", 5, "正在启动剧本改编流程...", None)

        result = await script_service.run_script_initialization(
            novel_text=novel_text,
            project_id=project_id,
            progress_callback=progress_callback,
            user_id=user_id,
            model_name=model_name,
            provider=provider,
        )

        progress_callback("finalizing", 95, "正在保存剧本项目...", None)
        project_manager.update_project(
            project_id,
            {
                "description": result.get("description"),
                "chapters": result.get("chapters", []),
                "status": "active",
                "progress": None,
            },
        )
        logger.info("Script project initialization completed for project %s", project_id)
    except Exception as e:
        logger.error(
            "Script project initialization failed for project %s: %s",
            project_id,
            e,
            exc_info=True,
        )
        project_manager.update_project(
            project_id,
            {
                "status": "failed",
                "description": f"Script initialization failed: {str(e)}",
                "error": {"message": str(e), "type": type(e).__name__},
                "progress": None,
            },
        )
        raise
