"""
Music Generation Endpoints - 音乐生成模块

包含音乐生成相关端点:
- POST /generations/music - 音乐生成
"""
import logging

from fastapi import APIRouter, Depends

from src.models.schemas import ResponseModel, MusicGenerationRequest
from src.services.provider.registry import ModelType
from src.services.task_manager import task_manager
from src.auth.dependencies import get_current_user, UserAuth

from .helpers import resolve_service, check_user_api_key
from src.utils.errors import ErrorCode, AppException

router = APIRouter()
logger = logging.getLogger(__name__)


@router.post("/generations/music", response_model=ResponseModel)
async def generate_music(
    request: MusicGenerationRequest,
    current_user: UserAuth = Depends(get_current_user)
):
    """统一 Music/Lyrics Generation Endpoint."""
    logger.info("Music unified generation request: mode=%s, model=%s", request.generation_mode, request.model)

    # 1) Resolve model by mode
    model_type = ModelType.LYRICS if request.generation_mode == "lyrics" else ModelType.MUSIC
    music_service = resolve_service(request.model, model_type)

    # 1.5 检查用户是否配置了 API Key
    # 从 music_service 获取 provider_id
    provider = getattr(music_service, 'provider_id', None)
    if provider:
        check_user_api_key(current_user.id, provider)

    if not music_service:
        raise AppException(
            message=f"{request.generation_mode} service not configured",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )

    # 2) Unified async task for both lyrics/music modes
    try:
        model_name = request.model or getattr(music_service, "model_id", "default_music")
        task_params = request.model_dump()

        # Handle project_id from multiple sources
        # Priority 1: request.project_id (from request body, alias="projectId")
        # Priority 2: request.source_id if source=='project' (from extra_params, alias="sourceId")
        project_id = request.project_id
        if not project_id and request.source == "project":
            project_id = request.source_id

        # Get user_id from authenticated user
        user_id = current_user.id

        task = await task_manager.create_task(
            task_type="music",
            model=model_name,
            params=task_params,
            user_id=user_id,
            project_id=project_id
        )
    except Exception as e:
        logger.error("Failed to create unified music task: %s", e)
        raise AppException(
            message=f"Failed to create task: {e}",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )

    return ResponseModel(data={
        "task_id": task.id,
        "status": task.status,
        "mode": request.generation_mode
    })
