"""Sessions API endpoints (running instances for current user)."""

import uuid

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

from src.auth.dependencies import _get_user, get_current_user_id, get_db_session
from src.models import GitRepository
from src.models import Project
from src.models import ToolInstance
from src.models import ToolType

sessions_router = APIRouter(prefix="/users", tags=["sessions"])


@sessions_router.get(
    "/me/sessions",
    summary="Get user sessions",
    description="Get all active sessions (running instances) for the current user.",
)
async def get_user_sessions(
    user_id: uuid.UUID = Depends(get_current_user_id),
    session: AsyncSession = Depends(get_db_session),
) -> dict:
    """Get all active sessions for the current user.

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

    Returns:
        Dictionary containing list of active sessions with instance details.
    """
    _user = await _get_user(session, user_id)

    result = await session.execute(
        select(ToolInstance)
        .where(ToolInstance.owner_id == user_id)
        .where(
            ToolInstance.status.in_(
                ["running", "building", "pending", "stopped", "error"]
            )
        )
        .order_by(ToolInstance.created_at.desc())
    )
    instances = result.scalars().all()

    sessions = []
    for instance in instances:
        tool_type = await session.get(ToolType, instance.tool_type_id)
        repo = await session.get(GitRepository, instance.repository_id)
        project = await session.get(Project, instance.project_id)

        workspace_name = None
        if instance.workspace_id:
            from src.models import Workspace as WorkspaceModel
            workspace = await session.get(WorkspaceModel, instance.workspace_id)
            if workspace:
                workspace_name = workspace.name

        sessions.append(
            {
                "id": str(instance.id),
                "display_name": instance.display_name,
                "tool_type_name": tool_type.name if tool_type else "unknown",
                "tool_icon": tool_type.name if tool_type else "code",
                "tool_type_interfaces": [tool_type.interface_type] if tool_type else [],
                "repository_name": repo.name if repo else "unknown",
                "repository_id": str(instance.repository_id),
                "project_name": project.name if project else "unknown",
                "project_id": str(instance.project_id),
                "workspace_name": workspace_name,
                "status": instance.status,
                "url": instance.url,
                "selected_config_profile_id": str(instance.selected_config_profile_id)
                if instance.selected_config_profile_id
                else None,
                "created_at": instance.created_at.isoformat()
                if instance.created_at
                else None,
            }
        )

    return {"sessions": sessions}
