"""H3. GPT 스타일 카드 — Codex CLI 통합 GPT image 배경 + 한글 텍스트.

용도: 다양한 스타일 (Gemini로 어려운 영역 — 추상, 아트, 특정 컨셉 등).
배경: GPT image, **반드시** Codex CLI 통합 경로 한정.
   ✅ subprocess.run(["codex", "exec", "--image-out", path, prompt])
   ❌ import openai 직접 호출 절대 금지
   ❌ HTTP requests로 api.openai.com 호출 절대 금지
텍스트: 한글 100% 정확 (Pretendard/Noto Sans KR).

IDS Phase 1 §3.2.1 / §0.2 Hybrid Pattern Standard 준수.
task-2428 Phase 2-1: 결정성 보장을 위해 procedural PIL render 사용.
"""

from __future__ import annotations

from pathlib import Path

from ._backgrounds import (
    build_background_layer_html,
    default_gradient,
    generate_codex_gpt_background,
)
from ._pil_render import render_h3_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:
    """H3 GPT 스타일 카드를 렌더링한다 (procedural PIL).

    Args:
        title: 한글 헤드라인.
        body: 한글 본문.
        output_path: 출력 PNG 경로.
        size: (width, height) 픽셀.
        design_tokens: 디자인 토큰 dict (gradient_theme/primary_hex/hint_*).
        background_path: 사전 생성된 배경 이미지.
        prompt_hint: GPT image 프롬프트 힌트 (Codex CLI로 전달, 옵셔널).

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

    tokens = design_tokens or {}

    # Codex CLI 통합 시도 (배경 옵션) — procedural render는 hint 없이도 분화 보장
    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}_h3_bg.png"
        bg_path = generate_codex_gpt_background(prompt_hint, gen_path)

    return render_h3_procedural(
        title,
        body,
        output_path,
        width=width,
        height=height,
        design_tokens=dict(tokens),
    )


_BACKWARD_COMPAT_HTML_BUILDER = (
    build_background_layer_html,
    default_gradient,
    build_text_overlay_html,
    render_html_to_png,
    as_int,
)
