from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import os

from .db import Base, engine
from .routers import assistants, voices, workflows, history, knowledge, llm, asr, tools


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时创建表
    Base.metadata.create_all(bind=engine)
    yield


app = FastAPI(
    title="AI VideoAssistant API",
    description="Backend API for AI VideoAssistant",
    version="1.0.0",
    lifespan=lifespan
)

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

# 路由
app.include_router(assistants.router, prefix="/api")
app.include_router(voices.router, prefix="/api")
app.include_router(workflows.router, prefix="/api")
app.include_router(history.router, prefix="/api")
app.include_router(knowledge.router, prefix="/api")
app.include_router(llm.router, prefix="/api")
app.include_router(asr.router, prefix="/api")
app.include_router(tools.router, prefix="/api")


@app.get("/")
def root():
    return {"message": "AI VideoAssistant API", "version": "1.0.0"}


@app.get("/health")
def health():
    return {"status": "ok"}
