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.image_engine import ImageEngine
from app.schemas.image_engine import ImageEngineListResponse

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


@router.get("", response_model=ImageEngineListResponse)
async def list_active_engines(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """Public endpoint returning active image engine capabilities."""
    result = await db.execute(
        select(ImageEngine)
        .where(ImageEngine.is_active == True)
        .order_by(ImageEngine.priority.desc())
    )
    engines = result.scalars().all()
    items = []
    for e in engines:
        models = []
        sizes = {}
        try:
            models = json.loads(e.supported_models) if e.supported_models else []
        except Exception:
            pass
        try:
            sizes = json.loads(e.supported_sizes) if e.supported_sizes else {}
        except Exception:
            pass
        items.append({
            "id": e.id,
            "name": e.name,
            "provider": e.provider,
            "supported_models": models,
            "supported_sizes": sizes,
            "default_size": e.default_size,
        })
    return {"items": items}