"""
TripTalley FastAPI Application.
Main entry point for the backend server.
"""

import logging
from contextlib import asynccontextmanager
from typing import AsyncGenerator

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

from app.core.config import settings
from app.core.db import engine, SessionLocal
from app.routers import auth, trips, expenses, settlements, sync

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """
    Application lifespan manager.
    Handles startup/shutdown events.
    """
    logger.info("Starting TripTalley backend...")
    
    # Create database tables
    async with engine.begin() as conn:
        from app.models.models import Base
        await conn.run_sync(Base.metadata.create_all)
    
    logger.info("Database tables created/verified")
    
    yield
    
    logger.info("Shutting down TripTalley backend...")


# Create FastAPI app
app = FastAPI(
    title="TripTalley API",
    description="Backend API for TripTalley - travel money tracking",
    version="1.0.0",
    contact={
        "name": "TripTalley Support",
        "email": "support@triptalley.com"
    },
    lifespan=lifespan
)

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


@app.get("/health")
async def health_check():
    """Health check endpoint."""
    return {"status": "healthy", "version": "1.0.0"}


@app.get("/")
async def root():
    """Root endpoint with API info."""
    return {
        "name": "TripTalley",
        "version": "1.0.0",
        "description": "Travel money tracking API",
        "endpoints": {
            "health": "/health",
            "docs": "/docs",
            "auth": "/api/v1/auth",
            "trips": "/api/v1/trips",
            "expenses": "/api/v1/expenses",
            "settlements": "/api/v1/settlements",
            "sync": "/api/v1/sync"
        }
    }


# Include routers
app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
app.include_router(trips.router, prefix="/api/v1/trips", tags=["trips"])
app.include_router(expenses.router, prefix="/api/v1/expenses", tags=["expenses"])
app.include_router(settlements.router, prefix="/api/v1/settlements", tags=["settlements"])
app.include_router(sync.router, prefix="/api/v1/sync", tags=["sync"])


if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level="info"
    )