from __future__ import annotations

from os import getenv

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

from backend.app.api import routes_config, routes_debug, routes_products, routes_scrape, routes_stats
from backend.app.core.logging import logger
from backend.app.core.scheduler import start_scheduler
from backend.app.db.database import Base, engine

load_dotenv()

app = FastAPI(title="suivi_produit")

app_env = getenv("APP_ENV", "development")

# CORS pour le frontend
cors_kwargs = {
    "allow_credentials": True,
    "allow_methods": ["*"],
    "allow_headers": ["*"],
}
if app_env == "development":
    cors_kwargs["allow_origin_regex"] = r"https?://(localhost|127\\.0\\.0\\.1|10\\.0\\.1\\.109)(:\\d+)?"
else:
    cors_kwargs["allow_origins"] = ["http://localhost:5173", "http://127.0.0.1:5173"]

app.add_middleware(CORSMiddleware, **cors_kwargs)

app.include_router(routes_products.router)
app.include_router(routes_scrape.router)
app.include_router(routes_config.router)
app.include_router(routes_debug.router)
app.include_router(routes_stats.router)


@app.on_event("startup")
def on_startup() -> None:
    Base.metadata.create_all(bind=engine)
    # démarrer le scheduler APScheduler en chargeant la config
    start_scheduler()
    logger.info("Application démarrée (%s)", getenv("APP_ENV", "development"))


@app.get("/health")
def health() -> dict[str, str]:
    # endpoint de santé minimal
    return {"statut": "ok"}


@app.get("/version")
def version() -> dict[str, str]:
    """Retourne la version du backend."""
    return {"version": "0.1.0"}


def main() -> FastAPI:
    return app
