"""H4. 그래디언트 카드 — Satori CSS gradient 배경 + Satori 한글.

용도: 미니멀, 매거진 스타일.
배경: Satori CSS gradient (외부 API 호출 0건).
텍스트: Satori 한글 (100% 정확).

외부 호출 0 — 가장 빠르고 가벼운 패턴.

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

from __future__ import annotations

from pathlib import Path

from ._backgrounds import default_gradient
from ._pil_render import render_h4_procedural
from ._satori import KOREAN_FONT_STACK, as_int, 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,  # H4에서는 미사용 (gradient 전용)
    prompt_hint: str | None = None,  # H4에서는 미사용
) -> Path:
    """H4 그래디언트 카드를 렌더링한다.

    Args:
        title: 한글 헤드라인.
        body: 한글 본문.
        output_path: 출력 PNG 경로.
        size: (width, height) 픽셀.
        design_tokens: 디자인 토큰 dict (`gradient_theme`: navy/warm/mint/rose/mono,
            또는 `gradient`: 직접 CSS gradient 문자열).
        background_path: H4에서 사용하지 않음 (시그니처 일관성용).
        prompt_hint: H4에서 사용하지 않음 (시그니처 일관성용).

    Returns:
        저장된 PNG 경로.
    """
    del background_path, prompt_hint  # H4는 외부 호출 0건
    width, height = size
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    tokens = design_tokens or {}
    # task-2428 Phase 2-1: 결정성 보장을 위해 procedural PIL render 사용.
    return render_h4_procedural(
        title,
        body,
        output_path,
        width=width,
        height=height,
        design_tokens=dict(tokens),
    )


def _legacy_html_render(title: str, body: str, output_path: Path, *,
                        width: int, height: int, design_tokens: dict) -> Path:
    """Legacy Satori HTML render path (task-2421). 보존용 (호출처 없음)."""
    tokens = design_tokens or {}
    custom_gradient = tokens.get("gradient")
    if isinstance(custom_gradient, str) and custom_gradient.strip():
        gradient_css = custom_gradient
    else:
        theme = str(tokens.get("gradient_theme", "navy"))
        gradient_css = default_gradient(theme)

    title_color = str(tokens.get("title_color", "#fafaf8"))
    body_color = str(tokens.get("body_color", "#d4d8e0"))
    accent_color = str(tokens.get("accent_color", "#d4a853"))
    title_size = as_int(tokens.get("title_size"), 80)
    body_size = as_int(tokens.get("body_size"), 38)

    # 매거진 스타일: 좌측 정렬, 큰 헤드라인, 얇은 악센트 라인
    html = (
        f'<div style="display:flex; flex-direction:column; '
        f"width:{width}px; height:{height}px; "
        f"background:{gradient_css}; "
        f'font-family:{KOREAN_FONT_STACK}; padding:96px; '
        f'box-sizing:border-box; justify-content:center; word-break:keep-all;">'
        f'<div style="display:flex; width:80px; height:6px; '
        f'background:{accent_color}; margin-bottom:48px;"></div>'
        f'<div style="font-size:{title_size}px; font-weight:700; '
        f'color:{title_color}; line-height:1.25; margin-bottom:32px;">'
        f"{_esc(title)}</div>"
        f'<div style="font-size:{body_size}px; color:{body_color}; '
        f'line-height:1.55; max-width:880px;">{_esc(body)}</div>'
        f"</div>"
    )

    return render_html_to_png(html, output_path, width=width, height=height)


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