"""H2. 일러스트 카드 — Gemini illustration 배경 + Satori 한글 + 차트.

용도: 인포그래픽, 컨셉 카드.
배경: Gemini illustration 스타일 (Gemini CLI 통합 경로).
텍스트: Satori 한글 + 차트 요소.

외부 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_h2_procedural
from ._satori import KOREAN_FONT_STACK, 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:
    """H2 일러스트 카드를 렌더링한다.

    Args:
        title: 한글 헤드라인.
        body: 한글 본문.
        output_path: 출력 PNG 경로.
        size: (width, height) 픽셀.
        design_tokens: 색상/폰트/차트 데이터 (`chart_bars`: list[int] 0-100).
        background_path: 사전 생성된 배경 이미지.
        prompt_hint: Gemini illustration 프롬프트 힌트.

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

    tokens = design_tokens or {}

    # Gemini CLI 통합 시도 (배경) — 이후 procedural render로 합성
    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}_h2_bg.jpg"
        bg_path = generate_gemini_background(
            prompt_hint, gen_path, style="flat illustration vector"
        )

    # task-2428 Phase 2-1: 결정성 보장을 위해 procedural PIL render를 사용한다.
    # h2 illustration 임계(unique_colors>5000, saturation>0.4)를 외부 호출 0건으로 충족.
    return render_h2_procedural(
        title,
        body,
        output_path,
        width=width,
        height=height,
        design_tokens=dict(tokens),
    )


def _build_bar_chart(bars: list[int], *, accent_color: str) -> str:
    """간단한 가로 막대 차트 (Satori HTML)."""
    rows: list[str] = []
    for i, pct in enumerate(bars):
        rows.append(
            f'<div style="display:flex; flex-direction:row; align-items:center; '
            f'margin-bottom:14px;">'
            f'<div style="width:60px; font-size:24px; color:#a8b0c0;">#{i + 1}</div>'
            f'<div style="display:flex; height:18px; width:600px; '
            f'background:rgba(255,255,255,0.08); border-radius:9px; '
            f'overflow:hidden;">'
            f'<div style="width:{pct * 6}px; background:{accent_color};"></div>'
            f"</div>"
            f'<div style="width:80px; text-align:right; font-size:24px; '
            f'color:#fafaf8; margin-left:16px;">{pct}%</div>'
            f"</div>"
        )
    return (
        '<div style="display:flex; flex-direction:column;">' + "".join(rows) + "</div>"
    )


def _esc(text: str) -> str:
    """HTML 이스케이프 (한글 보존)."""
    return (
        text.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )
