import os
import json
import aiohttp

async def load_api_schema_as_json(app_details: dict) -> dict:
    """
    Load the API schema as JSON. If 'api_schema' in app_details is a dictionary containing a 'url' key,
    check if the URL starts with 'https'. If not, treat it as a relative path to the local_directory.
    If it starts with 'https', load JSON from the URL directly. Otherwise, return 'api_schema' directly 
    if it is a JSON object.
    """
    api_schema_str = app_details.get('api_schema', None)
    api_schema = json.loads(api_schema_str)

    if isinstance(api_schema, dict):
        if 'url' in api_schema:
            url = api_schema['url']
            if url.startswith('https://'):
                # Load JSON from the absolute URL
                api_schema =  await load_json_from_url(url)
                
            elif url.startswith('http://'):
                # Return None for HTTP URLs as per requirement
                return None

            else:
                current_directory = os.getcwd()
                local_path = os.path.join(current_directory, 'app/api/v1/apps/sdk/json', url.lstrip('/'))
                try:
                    with open(local_path, 'r', encoding='utf-8') as file:
                        api_schema = json.load(file)
                except FileNotFoundError:
                    print(f"File not found: {local_path}")
                    return None
                except json.JSONDecodeError:
                    print(f"Error decoding JSON from file: {local_path}")
                    return None

        return api_schema
    
    return None


async def load_json_from_url(url: str):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            if response.status == 200:
                return await response.json()
            else:
                raise Exception(f"Failed to load JSON from URL: {url} - Status Code: {response.status}")
