"""insta-render FastAPI entry — health + lifespan (Browser pool + worker loop)."""
from __future__ import annotations

import asyncio
import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI

import card_renderer
import worker

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Browser pool 초기화 (Chromium launch)
    await card_renderer.init_browser()
    # 큐 워커 백그라운드 시작
    worker_task = asyncio.create_task(worker.worker_loop())
    logger.info("insta-render lifespan 시작")
    try:
        yield
    finally:
        worker_task.cancel()
        try:
            await worker_task
        except asyncio.CancelledError:
            pass
        await card_renderer.shutdown_browser()
        logger.info("insta-render lifespan 종료")


app = FastAPI(lifespan=lifespan)


@app.get("/health")
def health():
    return {"ok": True, "service": "insta-render"}
