import os

import aiohttp
import boto3
from fastapi import HTTPException
from fastapi.responses import JSONResponse


async def get_google_fonts_without_cache():
    """Fallback function to get fonts without caching if Redis fails"""
    try:
        GOOGLE_FONTS_API_KEY = os.getenv("GOOGLE_FONTS_API_KEY")
        if not GOOGLE_FONTS_API_KEY:
            raise HTTPException(
                status_code=500, detail="Google Fonts API key not configured"
            )

        url = f"https://www.googleapis.com/webfonts/v1/webfonts?key={GOOGLE_FONTS_API_KEY}"

        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                if response.status != 200:
                    raise HTTPException(
                        status_code=response.status,
                        detail="Failed to fetch Google Fonts",
                    )

                fonts_data = await response.json()
                font_families = [font["family"] for font in fonts_data.get("items", [])]

                return JSONResponse(
                    status_code=200,
                    content={"fonts": font_families, "total": len(font_families)},
                )

    except aiohttp.ClientError as e:
        raise HTTPException(
            status_code=500, detail=f"Error connecting to Google Fonts API: {str(e)}"
        )
