from typing import Dict, List, Set
import os

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

from app.config import settings
from app.routers import api_router, root_router

app = FastAPI(title="Wolai Backend", version="0.1.0-stage0")


def parse_extra_origins(*values: str) -> List[str]:
    out: Set[str] = set()
    for raw in values:
        if not raw:
            continue
        for item in str(raw).split(","):
            origin = item.strip()
            if origin:
                out.add(origin)
    return sorted(out)


extra_origins = parse_extra_origins(
    settings.frontend_url,
    os.getenv("FRONTEND_URLS", ""),
    os.getenv("CORS_ALLOWED_ORIGINS", ""),
)

allow_origins = [
    *extra_origins,
    "http://localhost:3000",
    "http://localhost:3001",
    "http://127.0.0.1:3000",
    "http://127.0.0.1:3001",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=allow_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(root_router)
app.include_router(api_router)


@app.get("/")
async def root() -> Dict[str, str]:
    return {"message": "Wolai backend stage0 up"}
