# backend/app/main.py
from contextlib import asynccontextmanager

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

from .config import get_settings
from .db import init_db
from .routers import dashboard, inbox, llm, people, tasks, tree

settings = get_settings()
health_router = APIRouter()  # 내부 prefix 없음. /health → /api/health


@asynccontextmanager
async def lifespan(app: FastAPI):
    init_db()  # 개발 편의(운영은 alembic). 테이블 보장.
    yield


app = FastAPI(title="아리 Ari API", lifespan=lifespan)
app.add_middleware(
    CORSMiddleware,
    allow_origins=[o.strip() for o in settings.frontend_origin.split(",")],
    allow_methods=["*"],
    allow_headers=["*"],
    allow_credentials=True,
)


# health: 라우터 내부 prefix 없이 "/health" 로 정의 → prefix="/api" 등록 시 /api/health.
@health_router.get("/health")
def health():
    return {"status": "ok"}


# 모든 라우터를 prefix="/api" 로 등록(라우터 내부 prefix 없음).
app.include_router(health_router, prefix="/api", tags=["health"])
app.include_router(people.router, prefix="/api", tags=["people"])
app.include_router(tree.router, prefix="/api", tags=["tree"])
app.include_router(tasks.router, prefix="/api", tags=["tasks"])
app.include_router(inbox.router, prefix="/api", tags=["inbox"])
app.include_router(dashboard.router, prefix="/api", tags=["dashboard"])
app.include_router(llm.router, prefix="/api", tags=["llm"])
