from contextlib import asynccontextmanager

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

from app.config import get_settings

settings = get_settings()


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    print("🚀 DWA AI Adoption Tracker starting up...")
    yield
    # Shutdown
    print("👋 Shutting down...")


app = FastAPI(
    title="DWA AI Adoption Tracker",
    description="Enterprise platform for tracking and gamifying AI adoption across DWA",
    version="0.1.0",
    lifespan=lifespan,
)

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


# Health check
@app.get("/health")
async def health():
    return {"status": "healthy", "service": "dwa-ai-tracker"}


# Include API routes
from app.api.router import api_router  # noqa: E402
app.include_router(api_router, prefix=settings.api_prefix)

# Include the content redirect route at root level (no /api prefix)
from app.api.content import router as content_redirect_router  # noqa: E402
# The /r/{short_code} redirect needs to be accessible without /api prefix
# It's also included in api_router under /api for the CRUD endpoints

from fastapi import Request
from fastapi.responses import RedirectResponse

@app.get("/r/{short_code}")
async def root_redirect(short_code: str, uid: str | None = None, request: Request = None):
    """Root-level redirect for tracked links (no /api prefix needed)."""
    from app.database import async_session
    from app.services.content_tracker import log_content_access
    async with async_session() as db:
        link = await log_content_access(
            db,
            short_code=short_code,
            user_email=uid,
            user_agent=request.headers.get("user-agent") if request else None,
            ip_address=request.client.host if request and request.client else None,
        )
        await db.commit()
        if not link:
            from fastapi import HTTPException
            raise HTTPException(status_code=404, detail="Link not found")
        return RedirectResponse(url=link.destination_url, status_code=302)
