"""FastAPI 앱 진입점 — API 서버.

시작 시 DB 초기화 + 시드. CORS 허용. 라우터 등록.
스케줄러는 별도 워커 컨테이너(worker.py)에서 실행한다(중복 방지).
"""
from __future__ import annotations

import logging
from contextlib import asynccontextmanager

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

from .config import settings
from .database import init_db
from .routers import (
    admin,
    comments,
    leaderboard,
    matches,
    predictions,
    share,
    visits,
)
from .scoring import load_scoring_data
from .seed import seed_if_empty

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("triplepick")


@asynccontextmanager
async def lifespan(app: FastAPI):  # noqa: ANN201
    load_scoring_data()  # data/scoring.json → 배점·배제 대상
    await init_db()
    await seed_if_empty()
    log.info("API ready")
    yield


app = FastAPI(title="TriplePick API", version="1.0.0", lifespan=lifespan)

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origin_list,
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(matches.router)
app.include_router(comments.router)
app.include_router(predictions.router)
app.include_router(leaderboard.router)
app.include_router(admin.router)
app.include_router(visits.router)
# 공유 미리보기(OG) 프리렌더 — nginx 가 크롤러 UA 의 /match/:id 만 여기로 보낸다.
app.include_router(share.router)


@app.get("/api/health")
async def health() -> dict:
    return {"ok": True, "service": "triplepick-api"}
