from typing import Any

from app.auth import AuthenticatedUser, get_current_user
from app.dependencies import get_asset_library_repository, get_project_repository
from app.schemas.asset_library import (
    AssetLibraryResponse,
    CreateAssetLibraryRequest,
    EnsureDefaultLibraryRequest,
    ListAssetLibrariesResponse,
)
from fastapi import APIRouter, Depends, HTTPException, Query, status

from packages.application import (
    CreateAssetLibraryCommand,
    CreateAssetLibraryUseCase,
    GetProjectUseCase,
    ListAssetLibrariesUseCase,
)
from packages.domain import AssetLibrary, AssetLibraryKind

router = APIRouter()


def _check_project_access(project_id: str, user_id: str, project_repository) -> None:
    """检查用户是否有项目访问权限"""
    project = project_repository.find_by_id(project_id)
    if project is None:
        raise HTTPException(status_code=404, detail=f"Project {project_id} not found")
    if not project.can_access(user_id):
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied to project")


def _to_asset_library_response(item) -> AssetLibraryResponse:
    return AssetLibraryResponse(
        id=item.id,
        project_id=item.project_id,
        name=item.name,
        kind=item.kind.value,
        asset_count=item.asset_count,
        total_size=item.total_size,
    )


@router.get("", response_model=ListAssetLibrariesResponse)
def list_asset_libraries(
    project_id: str | None = Query(None),
    kind: str | None = Query(None, pattern="^(video|voice|image)$"),
    authenticated_user: AuthenticatedUser = Depends(get_current_user),
    asset_library_repository: Any = Depends(get_asset_library_repository),
    project_repository: Any = Depends(get_project_repository),
) -> ListAssetLibrariesResponse:
    user_id = authenticated_user.user.id
    use_case = ListAssetLibrariesUseCase(asset_library_repository)

    if project_id:
        # If project_id provided, check access and filter by project
        project = GetProjectUseCase(project_repository).execute(project_id)
        if project is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Project not found")
        if not project.can_access(user_id):
            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied to project")
        items = use_case.execute(project_id)
    else:
        # If no project_id, list all libraries from accessible projects
        accessible_projects = project_repository.find_accessible_projects(user_id)
        all_items = []
        for proj in accessible_projects:
            all_items.extend(use_case.execute(proj.id))
        items = all_items

    # 按 kind 过滤（可选）
    if kind:
        kind_enum = AssetLibraryKind(kind)
        items = [item for item in items if item.kind == kind_enum]

    return ListAssetLibrariesResponse(items=[_to_asset_library_response(item) for item in items])


@router.post("", response_model=AssetLibraryResponse)
def create_asset_library(
    request: CreateAssetLibraryRequest,
    authenticated_user: AuthenticatedUser = Depends(get_current_user),
    asset_library_repository: Any = Depends(get_asset_library_repository),
    project_repository: Any = Depends(get_project_repository),
) -> AssetLibraryResponse:
    project = project_repository.find_by_id(request.project_id)
    if project is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Project not found")
    if not project.can_access(authenticated_user.user.id):
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied to project")
    use_case = CreateAssetLibraryUseCase(asset_library_repository)
    item = use_case.execute(
        CreateAssetLibraryCommand(
            project_id=request.project_id,
            name=request.name,
            kind=AssetLibraryKind(request.kind),
        )
    )
    return _to_asset_library_response(item)


# 默认素材库名称映射
_DEFAULT_LIBRARY_NAMES = {
    "video": "视频素材库",
    "voice": "配音素材库",
    "image": "图片素材库",
}


@router.post("/ensure-default", response_model=AssetLibraryResponse)
def ensure_default_library(
    request: EnsureDefaultLibraryRequest,
    authenticated_user: AuthenticatedUser = Depends(get_current_user),
    asset_library_repository: Any = Depends(get_asset_library_repository),
    project_repository: Any = Depends(get_project_repository),
) -> AssetLibraryResponse:
    """确保项目下指定 kind 的默认素材库存在，已存在则直接返回，不存在则自动创建。"""
    project = project_repository.find_by_id(request.project_id)
    if project is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Project not found")
    if not project.can_access(authenticated_user.user.id):
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied to project")

    kind = AssetLibraryKind(request.kind)

    # 查找该项目下同 kind 的素材库，返回第一个
    existing = asset_library_repository.find_by_project(request.project_id)
    for lib in existing:
        if lib.kind == kind:
            return _to_asset_library_response(lib)

    # 不存在 → 自动创建
    import uuid
    from datetime import datetime, timezone

    now = datetime.now(timezone.utc)
    default_name = _DEFAULT_LIBRARY_NAMES.get(request.kind, f"{request.kind}素材库")
    library = AssetLibrary(
        id=str(uuid.uuid4()),
        project_id=request.project_id,
        name=default_name,
        kind=kind,
        asset_count=0,
        total_size=0,
        created_at=now,
        updated_at=now,
    )
    created = asset_library_repository.create(library)
    return _to_asset_library_response(created)
