"""H1. 포토 카드 — Gemini photoreal 배경 + Satori 한글 헤드라인.

용도: 보험 광고, 상품 소개.
배경: Gemini photoreal (gemini-image 스킬 / Gemini CLI 통합 경로).
텍스트: Satori 한글 (100% 정확, 폰트 fallback 차단).

외부 API 직접 호출 절대 금지 — Gemini CLI / Satori (Node.js) 통합 경로만 사용.

IDS Phase 1 §3.2.1 / §0.2 Hybrid Pattern Standard 준수.
"""

from __future__ import annotations

from pathlib import Path

from ._backgrounds import (
    build_background_layer_html,
    default_gradient,
    generate_gemini_background,
)
from ._pil_render import render_h1_procedural
from ._satori import as_int, build_text_overlay_html, render_html_to_png


def render(
    title: str,
    body: str,
    output_path: Path | str,
    *,
    size: tuple[int, int] = (1080, 1350),
    design_tokens: dict[str, object] | None = None,
    background_path: Path | str | None = None,
    prompt_hint: str | None = None,
) -> Path:
    """H1 포토 카드를 렌더링한다.

    Args:
        title: 한글 헤드라인.
        body: 한글 본문.
        output_path: 출력 PNG 경로.
        size: (width, height) 픽셀.
        design_tokens: 디자인 토큰 dict (color, typography 등). 선택.
        background_path: 사전 생성된 배경 이미지 (있으면 Gemini 호출 생략).
        prompt_hint: Gemini 배경 생성 프롬프트 힌트 (영문 prefix 권장).

    Returns:
        저장된 PNG 경로.
    """
    width, height = size
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    tokens = design_tokens or {}

    # 1. 배경 확보 — 우선순위: 사용자 제공 > Gemini CLI > procedural PIL
    bg_path: Path | None = None
    if background_path is not None:
        candidate = Path(background_path)
        if candidate.exists():
            bg_path = candidate

    if bg_path is None and prompt_hint:
        gen_path = output_path.parent / f"{output_path.stem}_h1_bg.jpg"
        bg_path = generate_gemini_background(
            prompt_hint, gen_path, style="photoreal cinematic"
        )

    # 2. Satori HTML 경로는 환경 호환성으로 인해 결정성 보장 안 됨.
    #    photo_card 임계(edge_density>0.05) 충족 procedural PIL render를 사용한다.
    #    배경 이미지가 있으면 procedural render는 디스크 사진 모자이크 영역에 합성 가능.
    return render_h1_procedural(
        title,
        body,
        output_path,
        width=width,
        height=height,
        design_tokens=dict(tokens),
    )


# 사용되지 않는 _backgrounds/_satori 헬퍼는 task-2421 SKILL.md 예제 호환성을 위해 보존.
_BACKWARD_COMPAT_HTML_BUILDER = (
    build_background_layer_html,
    default_gradient,
    build_text_overlay_html,
    render_html_to_png,
    as_int,
)
