import json

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from fastapi import APIRouter, Depends

from app.dependencies import get_db, get_current_user
from app.models.user import User
from app.models.video_engine import VideoEngine
from app.schemas.video_engine import VideoEngineListResponse

router = APIRouter(prefix="/video-engines", tags=["video-engines"])


@router.get("", response_model=VideoEngineListResponse)
async def list_active_engines(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """Public endpoint returning active video engine capabilities."""
    result = await db.execute(
        select(VideoEngine)
        .where(VideoEngine.is_active == True)
        .order_by(VideoEngine.priority.desc())
    )
    engines = result.scalars().all()
    items = []
    for e in engines:
        ratios = []
        resolutions = []
        durations = []
        try:
            ratios = json.loads(e.supported_ratios) if e.supported_ratios else []
        except Exception:
            pass
        try:
            resolutions = json.loads(e.supported_resolutions) if e.supported_resolutions else []
        except Exception:
            pass
        try:
            durations = json.loads(e.supported_durations) if e.supported_durations else []
        except Exception:
            pass
        items.append({
            "id": e.id,
            "name": e.name,
            "provider": e.provider,
            "supported_ratios": ratios,
            "supported_resolutions": resolutions,
            "supported_durations": durations,
        })
    return {"items": items}
