import importlib
import os
from typing import Optional

from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse

from core.environment import Environment
from core.logger import APILogger

logger = APILogger(__name__)


class API:
    app: Optional[Starlette] = None

    @classmethod
    def create(cls, app: Starlette):
        cls.app = app

    @staticmethod
    async def handle_exception(request: Request, exc: Exception):
        logger.error(f"Request {request.state.request_id}", exc)
        return JSONResponse({"error": str(exc)}, status_code=500)

    @staticmethod
    def get_allowed_origins():
        client_urls = Environment.get("CLIENT_URLS", str)
        if client_urls is None or client_urls == "":
            allowed_origins = ["*"]
            logger.warning("No allowed origins specified, allowing all origins")
        else:
            allowed_origins = client_urls.split(",")

        return allowed_origins

    @staticmethod
    def import_routes():
        # used to import all routes
        routes_dir = os.path.join(os.path.dirname(__file__), "routes")
        for filename in os.listdir(routes_dir):
            if filename.endswith(".py") and filename != "__init__.py":
                module_name = f"api.routes.{filename[:-3]}"
                importlib.import_module(module_name)
