from fastapi import FastAPI
from .routes import auth, charts, conversations
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError
from src.config import settings

app = FastAPI(
    debug=True,
    title="Chart Analyzer API",
    description="API for analyzing charts and managing users.",
    version="1.0.0",
)

@app.on_event("startup")
async def startup_event():
    engine = create_engine(settings.DATABASE_URL)
    try:
        with engine.connect() as conn:
            print("✅ Database connection successful")
            print(f"🔗 Connection string: {settings.DATABASE_URL}")
    except OperationalError as e:
        print("❌ Database connection failed")
        print(f"Error: {e}")

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],  # Your Vite frontend URL
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(auth.router, prefix="/auth")
app.include_router(charts.router, prefix="/charts")
app.include_router(conversations.router, prefix="/conversations")

@app.get("/")
async def root():
    return {
        "message": "Welcome to Chart Analyzer API",
        "version": "1.0.0",
        "endpoints": {
            "authentication": "/auth",
            "chart_analysis": "/charts"
        }
    }
