# -*- coding: utf-8 -*-
"""o2o-ssulbox 백엔드 (FastAPI, API 전용).

인증(dev/카카오) · 피드/생성 · 좋아요 · 댓글 · 크레딧 · 업장명 자동완성 · SNS 연동.
DB는 개발 기본 SQLite. 생성 엔진은 저장소 내장(backend/generator/).
프론트(React/Vite)는 별도 실행하며 dev 프록시(/api,/videos)로 붙는다.
"""
from contextlib import asynccontextmanager

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

from .config import GEMINI_API_KEY, GENERATOR_DIR, OUTPUT_DIR, SCENARIO_ENGINE, settings
from .content_sync import sync_output
from .database import create_tables
from .routers import auth, comments, content, credit, sns


@asynccontextmanager
async def lifespan(app: FastAPI):
    await create_tables()          # SQLite: 없으면 생성
    await sync_output()            # 기존 output → content 반영
    yield


app = FastAPI(title="o2o-ssulbox API", version="0.1.0", lifespan=lifespan)
app.add_middleware(
    CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True,
)

app.include_router(auth.router)
app.include_router(auth.compat_router)   # /user/auth/kakao/callback (카카오 앱 등록 경로)
app.include_router(content.router)
app.include_router(comments.router)
app.include_router(credit.router)
app.include_router(sns.router)
app.include_router(sns.compat_router)   # /social/oauth/youtube/callback (Google 앱 등록 경로)


@app.get("/api/health")
def health():
    return {
        "ok": True,
        "gemini_key": bool(GEMINI_API_KEY),
        "generator_dir": str(GENERATOR_DIR),
        "output_exists": OUTPUT_DIR.is_dir(),
        "db": settings.DATABASE_URL.split("://")[0],
        "scenarios": list(SCENARIO_ENGINE),
    }


# 완성 mp4 정적 서빙
if OUTPUT_DIR.is_dir():
    app.mount("/videos", StaticFiles(directory=str(OUTPUT_DIR)), name="videos")
