from typing import Any

from app.auth import AuthenticatedUser, get_current_user
from app.dependencies import (
    get_asset_repository,
    get_generation_task_repository,
    get_project_repository,
    get_title_library_repository,
    get_voice_library_repository,
)
from app.schemas.dashboard import DashboardOverviewResponse, RecentTaskItem, SubscriptionInfo
from fastapi import APIRouter, Depends

router = APIRouter()


def _status_value(status) -> str:
    return status.value if hasattr(status, "value") else str(status)


def _generation_step(status: str) -> str:
    if status == "pending":
        return "等待 Worker 执行"
    if status == "running":
        return "正在生成成片"
    if status == "completed":
        return "生成完成"
    if status == "failed":
        return "生成失败"
    return status


@router.get("/overview", response_model=DashboardOverviewResponse)
def get_dashboard_overview(
    authenticated_user: AuthenticatedUser = Depends(get_current_user),
    project_repository: Any = Depends(get_project_repository),
    asset_repository: Any = Depends(get_asset_repository),
    generation_task_repository: Any = Depends(get_generation_task_repository),
    title_library_repository: Any = Depends(get_title_library_repository),
    voice_library_repository: Any = Depends(get_voice_library_repository),
) -> DashboardOverviewResponse:
    """Dashboard 概览：用户级汇总数据。"""
    user_id = authenticated_user.user.id

    # 获取用户可访问的所有 project
    projects = project_repository.find_accessible_projects(user_id)
    project_ids = [p.id for p in projects]

    # 素材统计
    total_assets = asset_repository.count_by_project_ids(project_ids)
    used_storage_bytes = asset_repository.sum_storage_by_project_ids(project_ids)

    # 标题库 / 配音库统计
    total_titles = title_library_repository.count_by_user(user_id)
    total_voices = voice_library_repository.count_by_user(user_id)

    # 生成任务统计
    total_tasks = generation_task_repository.count_by_user(user_id)

    # 最近任务（SQL 层 LIMIT 5）
    recent = generation_task_repository.list_recent_by_user(user_id, limit=5)
    recent_tasks = []
    for task in recent:
        s = _status_value(task.status)
        recent_tasks.append(
            RecentTaskItem(
                id=task.id,
                task_type="generation",
                status=s,
                current_step=_generation_step(s),
                error_message=task.error_message or "",
                updated_at=task.completed_at or task.started_at or task.created_at,
            )
        )

    # 订阅信息
    user = authenticated_user.user
    subscription = SubscriptionInfo(
        plan=getattr(user, "subscription_plan", "free") or "free",
        is_active=getattr(user, "subscription_status", "") == "active",
    )

    return DashboardOverviewResponse(
        total_assets=total_assets,
        used_storage_bytes=used_storage_bytes,
        total_titles=total_titles,
        total_voices=total_voices,
        total_tasks=total_tasks,
        total_products=len(projects),
        subscription=subscription,
        recent_tasks=recent_tasks,
    )
