from __future__ import annotations

from sqlalchemy.ext.asyncio import AsyncSession

from app.enums.generation_task import ChatGenerationTaskStatus, GenerationMode
from app.models.chat_generation_task import ChatGenerationTask


async def notify_chat_generation_task_finished(db: AsyncSession, task: ChatGenerationTask) -> None:
    """通知业务模块 ChatGenerationTask 已进入终态。

    该方法必须幂等：下载恢复任务、重试任务、服务重启补偿都可能重复调用。
    具体模块服务需要自行判断 step/project 是否已经完成或失败，避免重复推进。
    """
    if not task:
        return

    status = getattr(task, "status", None)
    generation_mode = getattr(task, "generation_mode", None)

    if generation_mode == GenerationMode.HOT_OPENING_REPLICATE.value:
        from app.services.hot_opening_replicate_service import (
            handle_chat_generation_task_completed,
            handle_chat_generation_task_failed,
        )
        if status == ChatGenerationTaskStatus.COMPLETED.value:
            await handle_chat_generation_task_completed(db, task)
        elif status == ChatGenerationTaskStatus.FAILED.value:
            await handle_chat_generation_task_failed(db, task)
        return

    if generation_mode == GenerationMode.SHOT_REPLICATE.value:
        from app.services.shot_replicate_flow_service import (
            handle_chat_generation_task_completed,
            handle_chat_generation_task_failed,
        )
        if status == ChatGenerationTaskStatus.COMPLETED.value:
            await handle_chat_generation_task_completed(db, task)
        elif status == ChatGenerationTaskStatus.FAILED.value:
            await handle_chat_generation_task_failed(db, task)
        return
