# app/main.py
import logging
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import sentry_sdk
from sentry_sdk.integrations.fastapi import FastApiIntegration

from app.api.api_router import api_router
from app.config import settings
from app.core.api_config import API_METADATA, API_TAGS
# Import database and models if needed for startup/shutdown events later
# from . import database, models

# Initialize Sentry
sentry_sdk.init(
    dsn=settings.SENTRY_DSN,
    integrations=[
        FastApiIntegration(),
    ],
    # Set traces_sample_rate to 1.0 to capture 100% of transactions for performance monitoring.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,
    # If you wish to associate users to errors (assuming you are using
    # FastAPI's users system) you may enable sending PII data.
    send_default_pii=True
)

# --- Logging Setup ---
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL),
    format=settings.LOG_FORMAT
)
logger = logging.getLogger(__name__)

# --- FastAPI App Instance ---
app = FastAPI(
    **API_METADATA,
    openapi_tags=API_TAGS
)

# --- CORS Middleware ---
# Define allowed origins. Be specific in production!
# Use ["*"] for wide open access during early development if needed,
# but restrict it as soon as possible.
# SvelteKit default dev port is 5173
origins = [
    "http://localhost:5174",
    "http://localhost:8000", # Allow requests from the API itself (e.g., Swagger UI)
    # Add your deployed frontend URL here later
    # "https://your-frontend-domain.com",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# --- End CORS Middleware ---


# --- Include API Routers ---
# All API endpoints will be prefixed with /api
app.include_router(api_router, prefix=settings.API_PREFIX)
# --- End Include API Routers ---


# --- Root Endpoint (Optional - outside the main API structure) ---
@app.get("/", tags=["Root"])
async def read_root():
    """
    Provides a simple welcome message at the root path.
    Useful for basic reachability checks.
    """
    logger.info("Root endpoint '/' accessed.")
    return {"message": settings.ROOT_MESSAGE}
# --- End Root Endpoint ---


# --- Application Startup/Shutdown Events (Optional) ---
# @app.on_event("startup")
# async def startup_event():
#     logger.info("Application startup: Connecting to database...")
#     # You might perform initial checks or warm-up here
#     # await database.engine.connect() # Example check (get_db handles sessions per request)
#     logger.info("Application startup complete.")

# @app.on_event("shutdown")
# async def shutdown_event():
#     logger.info("Application shutdown: Disconnecting from database...")
#     # await database.engine.dispose() # Close connection pool
#     logger.info("Application shutdown complete.")
# --- End Events ---


# --- Direct Run (for simple local testing if needed) ---
# It's better to use `uvicorn app.main:app --reload` from the terminal
# if __name__ == "__main__":
#     logger.info("Starting Uvicorn server directly from main.py")
#     uvicorn.run(app, host="0.0.0.0", port=8000)
# ------------------------------------------------------