from pathlib import Path

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

from app.api.health import router as health_router
from app.api.auth import router as auth_router
from app.api.chats import router as chats_router
from app.core.config import settings
from app.db.init_db import init_db
from app.db.session import SessionLocal


def ensure_dirs() -> None:
    for path in [settings.upload_root, settings.temp_root, settings.log_root]:
        Path(path).mkdir(parents=True, exist_ok=True)


ensure_dirs()

app = FastAPI(
    title="AI Chat MVP Backend",
    version="0.1.0",
)


@app.on_event("startup")
def on_startup():
    db = SessionLocal()
    try:
        init_db(db)
    finally:
        db.close()


app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://127.0.0.1:13000",
        "http://localhost:13000",
        "http://192.168.149.194:13000",
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(health_router, prefix="/api")
app.include_router(auth_router, prefix="/api/auth", tags=["auth"])
app.include_router(chats_router, prefix="/api", tags=["chats"])


@app.get("/")
def root() -> dict:
    return {
        "service": "ai-chat-backend",
        "env": settings.app_env,
        "docs": "/docs",
    }
