# app/main.py

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from pathlib import Path
import importlib.util
import sys

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],             # Allows requests from these origins
    allow_credentials=True,        # Allow cookies, authorization headers, etc.
    allow_methods=["*"],           # Allow all HTTP methods (GET, POST, etc.)
    allow_headers=["*"],           # Allow all headers
)

API_DIR = Path(__file__).parent / "api"

def import_module_from_path(path: Path):
    module_name = ".".join(path.relative_to(Path(__file__).parent).with_suffix('').parts)
    spec = importlib.util.spec_from_file_location(module_name, str(path))
    if spec and spec.loader:
        mod = importlib.util.module_from_spec(spec)
        sys.modules[module_name] = mod
        spec.loader.exec_module(mod)
        return mod
    return None

def include_all_routers(api_dir: Path):
    for py_file in api_dir.rglob("*.py"):
        mod = import_module_from_path(py_file)
        if mod and hasattr(mod, "router"):
            router = getattr(mod, "router")
            app.include_router(router)

include_all_routers(API_DIR)
