from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api.v1.api import api_router
from app.core.config import settings
from app.db.session import connect_to_mongo, close_mongo_connection, db_connection
from app.core.security import get_password_hash
from datetime import datetime, timezone
import uuid
import logging

app = FastAPI(title=settings.PROJECT_NAME)

# Set all CORS enabled origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.on_event("startup")
async def startup_event():
    await connect_to_mongo()
    logging.info("Connected to MongoDB")
    
    # Create demo user if it doesn't exist
    demo_email = "demo@trainings24x7.com"
    existing = await db_connection.db.users.find_one({"email": demo_email})
    if not existing:
        hashed_password = await get_password_hash("demo123")
        demo_user = {
            "id": str(uuid.uuid4()),
            "username": "demo_user",
            "email": demo_email,
            "hashed_password": hashed_password,
            "is_active": True,
            "created_at": datetime.now(timezone.utc),
            "total_points": 500,
            "badges": ["first-game"],
            "games_completed": ["otp-fraud"],
            "courses_enrolled": ["foundation-cybersecurity"],
            "level": "warrior"
        }
        await db_connection.db.users.insert_one(demo_user)
        logging.info("Demo user created on startup")

@app.on_event("shutdown")
async def shutdown_event():
    await close_mongo_connection()
    logging.info("Disconnected from MongoDB")

@app.get("/")
async def root():
    return {"message": "Trainings24x7 - Cyber Crime Awareness Platform API", "status": "running"}

app.include_router(api_router, prefix="/api/v1")
# Also include without v1 prefix for backward compatibility with frontend if needed,
# or better, keep it clean. Let's redirect /api to /api/v1 if possible or just use /api.
# The original server.py used @api_router.post("/api/auth/register") essentially.
# So I should probably just mount it at /api.
app.include_router(api_router, prefix="/api")

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