from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

from sqlmodel import Session

from app.core.config import get_settings
from app.core.logging import setup_logger
from app.db.session import engine, init_db
from app.db.seeds import run_all_seeders

from app.api.routes import auth, users, product_templates, projects

logger = setup_logger(__name__)

def create_app() -> FastAPI:
    settings = get_settings()

    app = FastAPI(
        title="StoryBook API",
        version="1.0.0",
        description="Backend API for the StoryBook system.",
        # docs_url=None, # Disable Swagger UI on PROD
        # redoc_url=None, # Disable ReDoc on PROD
        # openapi_url=None # Disable OpenAPI schema on PROD
    )

    # STATIC ASSETS DIRECTORY (ROOT_DIR/assets)
    ROOT_DIR = Path(__file__).resolve().parent.parent
    assets_path = ROOT_DIR / "assets"
    assets_path.mkdir(parents=True, exist_ok=True)

    app.mount(
        "/assets",
        StaticFiles(directory=str(assets_path)),
        name="assets",
    )

    # ROUTERS
    app.include_router(auth.router)
    app.include_router(users.router)
    app.include_router(product_templates.router)
    app.include_router(projects.router)

    # CORS CONFIG
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.BACKEND_CORS_ORIGINS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # LIFECYCLE EVENTS
    @app.on_event("startup")
    def startup_event():
        """Initialize DB schema and run seeders."""
        logger.info("Application starting...")

        # Create all tables
        init_db()

        # Run seeders (using manual session, NOT dependency generator)
        try:
            with Session(engine) as session:
                run_all_seeders(session)
        except Exception as exc:
            logger.exception("Error during startup seed execution: %s", exc)

    @app.on_event("shutdown")
    def shutdown_event():
        """Optional graceful cleanup."""
        logger.info("Application shutting down...")

    return app

app = create_app()
