"""Voice library use cases."""

from __future__ import annotations

import uuid
from typing import List, Optional

from packages.adapters.sqlalchemy_impl.voice_library_repository import SQLAlchemyVoiceLibraryRepository
from packages.application.voice_library.commands import (
    CreateVoiceLibraryCommand,
    UpdateVoiceLibraryCommand,
)
from packages.domain.quota import QuotaDimension, quota_checker
from packages.domain.voice_library import VoiceLibraryItem


class ListVoiceLibraryUseCase:
    def __init__(self, repository: SQLAlchemyVoiceLibraryRepository) -> None:
        self.repository = repository

    def execute(
        self,
        user_id: str,
        *,
        status: Optional[str] = None,
        skip: int = 0,
        limit: int = 50,
    ) -> tuple[List[VoiceLibraryItem], int]:
        """返回 (items, total_count)，避免调用方再单独查一次 count。"""
        items = self.repository.list_by_user(user_id, status=status, skip=skip, limit=limit)
        total = (
            self.repository.count_by_user(user_id, status=status) if status else self.repository.count_by_user(user_id)
        )
        return items, total


class GetVoiceLibraryUseCase:
    def __init__(self, repository: SQLAlchemyVoiceLibraryRepository) -> None:
        self.repository = repository

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


class CreateVoiceLibraryUseCase:
    def __init__(self, repository: SQLAlchemyVoiceLibraryRepository) -> None:
        self.repository = repository

    def execute(self, command: CreateVoiceLibraryCommand, plan_name: str = "free") -> VoiceLibraryItem:
        # Quota check
        current_count = self.repository.count_by_user(command.user_id)
        result = quota_checker.check(plan_name, QuotaDimension.MAX_VOICEOVERS.value, current_count)
        if not result.allowed:
            raise QuotaExceededError(
                dimension=QuotaDimension.MAX_VOICEOVERS.value,
                limit=result.limit,
                used=result.used,
            )

        item = VoiceLibraryItem(
            id=uuid.uuid4().hex,
            user_id=command.user_id,
            name=command.name,
            text=command.text,
            voice_provider=command.voice_provider,
            voice_id=command.voice_id,
            voice_name=command.voice_name,
            audio_url=command.audio_url,
            duration=command.duration,
            file_size=command.file_size,
            status=command.status,
            project_id=command.project_id,
            tags=command.tags,
            metadata_=command.metadata_,
        )
        return self.repository.create(item)


class UpdateVoiceLibraryUseCase:
    def __init__(self, repository: SQLAlchemyVoiceLibraryRepository) -> None:
        self.repository = repository

    def execute(self, command: UpdateVoiceLibraryCommand) -> VoiceLibraryItem:
        existing = self.repository.get(command.id, command.user_id)
        if existing is None:
            raise NotFoundError(f"Voice {command.id} not found")

        if command.name is not None:
            existing.name = command.name
        if command.text is not None:
            existing.text = command.text
        if command.voice_provider is not None:
            existing.voice_provider = command.voice_provider
        if command.voice_id is not None:
            existing.voice_id = command.voice_id
        if command.voice_name is not None:
            existing.voice_name = command.voice_name
        if command.audio_url is not None:
            existing.audio_url = command.audio_url
        if command.duration is not None:
            existing.duration = command.duration
        if command.file_size is not None:
            existing.file_size = command.file_size
        if command.status is not None:
            existing.status = command.status
        if command.tags is not None:
            existing.tags = command.tags
        if command.metadata_ is not None:
            existing.metadata_ = command.metadata_

        return self.repository.update(existing)


class DeleteVoiceLibraryUseCase:
    def __init__(self, repository: SQLAlchemyVoiceLibraryRepository) -> None:
        self.repository = repository

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


class QuotaExceededError(Exception):
    def __init__(self, dimension: str, limit: float, used: float) -> None:
        self.dimension = dimension
        self.limit = limit
        self.used = used
        super().__init__(f"Quota exceeded for {dimension}: {used}/{limit}")


class NotFoundError(Exception):
    pass
