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

# 1. Config Import
from app.core.config import settings

# 2. Database Imports (FIXED PATHS)
# 'Base' contains the model definitions (from app/db/base.py)
from app.db.base import Base
# 'engine' handles the connection (assumed to be in app/db/session.py)
from app.db.session import engine

# 3. Router Import
from app.api.v1.router import api_router

# --- Lifespan Manager (Startup & Shutdown Logic) ---
@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Handles application startup and shutdown events.
    """
    # STARTUP: Create Database Tables (Development Mode)
    # In production, you should use Alembic migrations instead of this.
    async with engine.begin() as conn:
        # We must import models here so that Base.metadata knows about them
        # before we call create_all.
        # Ensure these files exist in app/models/
        from app.models import social, vehicle  # Add 'user', 'logistics' if created
        
        print("--- Checking/Creating Database Tables ---")
        await conn.run_sync(Base.metadata.create_all)
    
    yield # The application runs here
    
    # SHUTDOWN: Cleanup resources
    print("--- Shutting down Traffic Ecosystem SuperApp ---")
    await engine.dispose()

# --- App Initialization ---
app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    lifespan=lifespan
)

# --- Middleware (CORS) ---
# Allows the frontend to communicate with this API
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"], # WARNING: Restrict this in production!
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- Routers ---
app.include_router(api_router, prefix=settings.API_V1_STR)

# --- Root Endpoint ---
@app.get("/")
async def root():
    return {
        "message": "Traffic Ecosystem SuperApp API is Running",
        "version": settings.VERSION,
        "docs_url": "/docs"
    }