import config
from bootstrap import init_db
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from api import chat, presets, settings as settings_api, ws


@asynccontextmanager
async def lifespan(app: FastAPI):
    init_db()
    yield


app = FastAPI(
    title="DeepSeek 对话智能体",
    description="带会话记忆与预设问题的 DeepSeek 对话 API",
    version="1.0.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(chat.router)
app.include_router(presets.router)
app.include_router(settings_api.router)
app.include_router(ws.router)


@app.get("/health")
def health():
    key = config.settings.deepseek_api_key
    configured = bool(key and key != "sk-your-key-here")
    ds_key = config.settings.dashscope_api_key
    tts_configured = bool(ds_key and ds_key != "sk-your-dashscope-key")
    return {
        "status": "ok",
        "model": config.settings.deepseek_model,
        "api_key_configured": configured,
        "web_search_enabled": config.settings.web_search_enabled,
        "tts_configured": tts_configured,
        "tts_model": config.settings.tts_model,
        "tts_voice": config.settings.tts_voice,
    }
