"""Recipe use cases."""

from __future__ import annotations

import uuid
from dataclasses import dataclass
from typing import List, Optional

from packages.adapters.sqlalchemy_impl.recipe_repository import SQLAlchemyRecipeRepository
from packages.application.recipe.commands import (
    CreateRecipeCommand,
    RecipeItemCommand,
    UpdateRecipeCommand,
)
from packages.domain.recipe import Recipe, RecipeItem
from packages.infrastructure.feature_flags import FeatureScope, feature_flags


class NotFoundError(Exception):
    pass


class FeatureDisabledError(Exception):
    pass


@dataclass
class MissingAssetWarning:
    """使用配方时缺失的素材警告"""

    item_type: str
    item_id: str
    position: int


class CreateRecipeUseCase:
    def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
        self.repository = repository

    def execute(self, command: CreateRecipeCommand) -> Recipe:
        recipe_id = uuid.uuid4().hex
        recipe = Recipe(
            id=recipe_id,
            user_id=command.user_id,
            name=command.name,
            description=command.description,
            template_id=command.template_id,
            generation_params=command.generation_params,
            metadata_=command.metadata_,
        )
        recipe = self.repository.create(recipe)

        # Create items
        if command.items:
            items = [
                RecipeItem(
                    id=uuid.uuid4().hex,
                    recipe_id=recipe.id,
                    item_type=ic.item_type,
                    item_id=ic.item_id,
                    position=ic.position,
                    metadata_=ic.metadata_,
                )
                for ic in command.items
            ]
            self.repository.create_items(items)
            recipe.items = items

        return recipe


class ListRecipesUseCase:
    def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
        self.repository = repository

    def execute(
        self,
        user_id: str,
        *,
        skip: int = 0,
        limit: int = 50,
    ) -> List[Recipe]:
        return self.repository.list_by_user(user_id, skip=skip, limit=limit)


class GetRecipeUseCase:
    def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
        self.repository = repository

    def execute(self, recipe_id: str, user_id: str) -> Optional[Recipe]:
        return self.repository.get(recipe_id, user_id)


class UpdateRecipeUseCase:
    def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
        self.repository = repository

    def execute(self, command: UpdateRecipeCommand) -> Recipe:
        existing = self.repository.get(command.recipe_id, command.user_id)
        if existing is None:
            raise NotFoundError(f"Recipe {command.recipe_id} not found")

        if command.name is not None:
            existing.name = command.name
        if command.description is not None:
            existing.description = command.description
        if command.template_id is not None:
            existing.template_id = command.template_id
        if command.generation_params is not None:
            existing.generation_params = command.generation_params
        if command.metadata_ is not None:
            existing.metadata_ = command.metadata_

        self.repository.update(existing)

        # Replace items if provided
        if command.items is not None:
            self.repository.delete_items_by_recipe(existing.id)
            items = [
                RecipeItem(
                    id=uuid.uuid4().hex,
                    recipe_id=existing.id,
                    item_type=ic.item_type,
                    item_id=ic.item_id,
                    position=ic.position,
                    metadata_=ic.metadata_,
                )
                for ic in command.items
            ]
            self.repository.create_items(items)
            existing.items = items
        else:
            existing.items = self.repository.list_items(existing.id)

        return existing


class DeleteRecipeUseCase:
    def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
        self.repository = repository

    def execute(self, recipe_id: str, user_id: str) -> bool:
        return self.repository.delete(recipe_id, user_id)


@dataclass
class UseRecipeResult:
    """使用配方的结果"""

    recipe: Recipe
    warnings: List[MissingAssetWarning]


class UseRecipeUseCase:
    """使用配方 — 校验 Feature Flag + 检查素材可用性"""

    def __init__(self, repository: SQLAlchemyRecipeRepository) -> None:
        self.repository = repository

    def execute(
        self,
        recipe_id: str,
        user_id: str,
        *,
        user_plan: str = "free",
    ) -> UseRecipeResult:
        # 1. 校验 Feature Flag（仅 basic/premium 可用）
        if not feature_flags.is_enabled(
            FeatureScope.RECIPE_REUSE,
            user_plan=user_plan,
        ):
            raise FeatureDisabledError("配方复用功能仅对基础版和高级版用户开放")

        # 2. 获取配方
        recipe = self.repository.get(recipe_id, user_id)
        if recipe is None:
            raise NotFoundError(f"Recipe {recipe_id} not found")

        # 3. 校验引用的素材/标题/配音是否仍存在
        warnings: List[MissingAssetWarning] = []
        # Note: 实际项目中这里需要注入 asset/title/voice repository
        # 来校验每个 item 是否仍然存在。当前版本返回空警告列表，
        # 由调用方（路由层）决定是否传入额外的校验逻辑。

        return UseRecipeResult(recipe=recipe, warnings=warnings)
