"""프레임 생성 모듈.

IDS Phase 5 — 모션 카드뉴스 (HTML→MP4)
- PIL 기반 솔리드 프레임 생성 (테스트/폴백용)
- Playwright 기반 HTML→PNG 변환 (프로덕션)
"""
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

from PIL import Image, ImageDraw, ImageFont

if TYPE_CHECKING:
    pass

_FONT_SEARCH_PATHS = [
    "/home/jay/workspace/tools/ai-image-gen/satori-test/fonts/NotoSansCJKkr-Regular.otf",
    "/home/jay/workspace/tools/ai-image-gen/satori-test/fonts/NotoSansCJKkr-Bold.otf",
    "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
]


def _get_korean_font(size: int = 36) -> "ImageFont.FreeTypeFont | ImageFont.ImageFont":
    """한글 폰트를 로드합니다. 실패 시 기본 폰트를 반환합니다."""
    for font_path in _FONT_SEARCH_PATHS:
        if Path(font_path).exists():
            try:
                return ImageFont.truetype(font_path, size)
            except Exception:
                continue
    return ImageFont.load_default()


def generate_solid_frame(
    width: int,
    height: int,
    color: tuple[int, int, int],
    text: str,
    output_path: Path,
) -> Path:
    """솔리드 컬러 배경에 텍스트를 그린 PNG 프레임을 생성합니다.

    Args:
        width: 이미지 너비 (픽셀)
        height: 이미지 높이 (픽셀)
        color: RGB 배경색 튜플, 예: (220, 50, 50)
        text: 프레임에 표시할 텍스트
        output_path: 저장할 PNG 파일 경로

    Returns:
        저장된 PNG 파일의 Path 객체
    """
    img = Image.new("RGB", (width, height), color=color)
    draw = ImageDraw.Draw(img)
    font = _get_korean_font(size=max(24, min(width // 10, 72)))

    # 텍스트 크기 계산 (textsize 제거됨 → textbbox 사용)
    bbox = draw.textbbox((0, 0), text, font=font)
    text_w = bbox[2] - bbox[0]
    text_h = bbox[3] - bbox[1]

    # 중앙 배치
    x = (width - text_w) // 2
    y = (height - text_h) // 2

    # 그림자 효과
    draw.text((x + 2, y + 2), text, fill=(0, 0, 0, 128), font=font)
    draw.text((x, y), text, fill=(255, 255, 255), font=font)

    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    img.save(str(output_path), "PNG")
    return output_path


def frames_from_html(
    html_paths: list[Path],
    size: tuple[int, int],
    output_dir: Path,
) -> list[Path]:
    """HTML 파일 목록을 Playwright로 PNG 프레임으로 변환합니다.

    Args:
        html_paths: HTML 파일 경로 목록
        size: (width, height) 출력 해상도
        output_dir: PNG를 저장할 디렉토리

    Returns:
        생성된 PNG 파일 경로 목록

    Raises:
        ImportError: playwright가 설치되지 않은 경우
    """
    try:
        from playwright.sync_api import sync_playwright  # type: ignore[import-not-found]
    except ImportError as exc:
        raise ImportError(
            "playwright가 설치되지 않았습니다. "
            "설치: pip install playwright && playwright install chromium"
        ) from exc

    width, height = size
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    frame_paths: list[Path] = []

    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page(viewport={"width": width, "height": height})

        for i, html_path in enumerate(html_paths):
            html_path = Path(html_path)
            page.goto(f"file://{html_path.absolute()}")
            page.wait_for_load_state("networkidle")

            out_path = output_dir / f"frame_{i:04d}.png"
            page.screenshot(path=str(out_path))
            frame_paths.append(out_path)

        browser.close()

    return frame_paths
