from contextlib import asynccontextmanager

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

from app.routes.account_routes import router as account_router
from app.routes.auth_routes import router
from app.routes.hudl_routes import router as hudl_router, stream_router
from app.automation.browser_manager import browser_manager

from app.core.database import Base, engine, SessionLocal

from app.models.account_model import Account
from app.models.user_model import User
from app.models.role_model import Role
from app.models.otp_model import OTPVerification
from app.models.media_model import MediaVideo  # noqa: F401 — register table for create_all

DEFAULT_ROLES = ("user", "admin")


def seed_roles():
    db = SessionLocal()
    try:
        for role_name in DEFAULT_ROLES:
            exists = db.query(Role).filter(Role.role_name == role_name).first()
            if not exists:
                db.add(Role(role_name=role_name))
        db.commit()
    finally:
        db.close()


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Browser opens on first Hudl API call (or POST /browser/start), not at import.
    yield
    await browser_manager.close()


app = FastAPI(lifespan=lifespan)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Base.metadata.create_all(bind=engine)
seed_roles()

app.include_router(
    router,
    prefix="/api/v1/auth",
    tags=["Authentication"]
)

app.include_router(
    account_router,
    prefix="/api/v1",
    tags=["Accounts"],
)

app.include_router(
    hudl_router,
    prefix="/api/v1/hudl",
    tags=["Hudl Automation"],
)

app.include_router(
    stream_router,
    prefix="/api/v1/hudl",
    tags=["Hudl Automation"],
)

@app.get("/")
def home():

    return {"message": "FastAPI Auth App"}