import uuid

from fastapi import APIRouter, Depends
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from src.auth.dependencies import get_current_user_id, get_db_session
from src.models import GitRepository
from src.models.project import Project
from src.models import SSHKey

router = APIRouter(prefix="/dashboard", tags=["dashboard"])


@router.get(
    "/summary",
    summary="Get dashboard summary",
    description="Get a summary of the user's projects, repositories, SSH keys, and recent activity.",
)
async def get_dashboard_summary(
    user_id: uuid.UUID = Depends(get_current_user_id),
    session: AsyncSession = Depends(get_db_session),
) -> dict:
    """Get a summary of the user's dashboard data.

    Args:
        user_id: ID of the authenticated user.
        session: Database session.

    Returns:
        Dictionary with counts of projects, repositories, SSH keys, and recent activity.
    """
    # Count user's projects
    projects_result = await session.execute(
        select(func.count()).select_from(Project).where(Project.owner_id == user_id)
    )
    projects_count = projects_result.scalar() or 0

    # Count user's repositories
    repos_result = await session.execute(
        select(func.count()).select_from(GitRepository).where(GitRepository.owner_id == user_id)
    )
    repos_count = repos_result.scalar() or 0

    # Count user's SSH keys
    ssh_keys_result = await session.execute(
        select(func.count()).select_from(SSHKey).where(SSHKey.user_id == user_id)
    )
    ssh_keys_count = ssh_keys_result.scalar() or 0

    # Get recent activity (latest 5 projects)
    recent_projects = await session.execute(
        select(Project)
        .where(Project.owner_id == user_id)
        .order_by(Project.created_at.desc())
        .limit(5)
    )
    recent_activity = [f"Created project: {p.name}" for p in recent_projects.scalars().all()]

    return {
        "projects": projects_count,
        "repositories": repos_count,
        "sshKeys": ssh_keys_count,
        "recentActivity": recent_activity,
    }
