import json
import os

import aiohttp
from fastapi import HTTPException

from utils.url_parser import parsed_url


async def fetch_brand_details(url: str):
    """
    Fetch brand details for a given URL using the Brandfetch API.

    Args:
        url (str): The URL of the company to fetch brand details for.

    Returns:
        dict: The brand details retrieved from the Brandfetch API.
    """
    BRAND_FETCH_API = os.getenv("BRAND_FETCH_API_KEY")

    if not BRAND_FETCH_API:
        raise HTTPException(
            status_code=500,
            detail="Brand Fetch API key not configured",
        )

    url = parsed_url(url, check_redirect=False).domain

    request_header = {
        "accept": "application/json",
        "Authorization": f"Bearer {BRAND_FETCH_API}",
    }

    request_url = f"https://api.brandfetch.io/v2/brands/{url}"

    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(
                request_url, headers=request_header, timeout=20
            ) as response:
                response.raise_for_status()
                return await response.json()
    except aiohttp.ClientTimeout:
        raise HTTPException(
            status_code=504,
            detail="Request to Brandfetch API timed out.",
        )
    except aiohttp.ClientResponseError as http_err:
        raise HTTPException(
            status_code=http_err.status,
            detail=f"Brandfetch API error: {http_err}",
        )
    except aiohttp.ClientError as req_err:
        raise HTTPException(
            status_code=500,
            detail=f"An error occurred while fetching brand data: {req_err}",
        )
    except json.JSONDecodeError as e:
        raise HTTPException(
            status_code=500,
            detail="Failed to decode JSON response from Brandfetch API.",
        ) from e
