import json
import os

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

from utils.google_fonts import get_google_fonts_without_cache


async def get_google_fonts_list():
    """
    Retrieves a list of all available Google Font families.
    Caches the response for 7 days to minimize API calls.

    Returns:
        dict: A dictionary containing font families and total count
    """
    try:
        # Create Redis client
        redis_client = redis.Redis(
            host=os.getenv("REDIS_HOST", "localhost"),
            port=int(os.getenv("REDIS_PORT", 6379)),
            db=0,
            decode_responses=True,
        )

        cached_fonts = redis_client.get("google_fonts_cache")
        if cached_fonts:
            return json.loads(cached_fonts)

        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", [])]

                response_data = {"fonts": font_families, "total": len(font_families)}

                # Cache the response for 7 days
                redis_client.setex(
                    "google_fonts_cache",
                    60 * 60 * 24 * 7,  # 7 days in seconds
                    json.dumps(response_data),
                )

                return response_data

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

    except redis.RedisError as e:
        print("Redis error: %s", str(e))
        return await get_google_fonts_without_cache()

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")
