"""단일 (브랜드, 패턴, 사이즈) 조합으로 PNG 렌더 + verify L1 evidence 생성용 헬퍼.

IDS Phase 1 task-2401 — L1 smoke test evidence 생성.
"""

from __future__ import annotations

import html as html_lib
import sys
from pathlib import Path
from typing import Any

# workspace sys.path 추가 (하이픈 디렉토리 import 지원)
_WORKSPACE = Path("/home/jay/workspace")
if str(_WORKSPACE) not in sys.path:
    sys.path.insert(0, str(_WORKSPACE))

# 동일 패키지에서 import
_SKILL_DIR = Path(__file__).parent.parent
if str(_SKILL_DIR.parent) not in sys.path:
    sys.path.insert(0, str(_SKILL_DIR.parent))

import importlib.util as _ilu


def _load_satori_module() -> Any:
    """satori-cardnews/_satori.py를 importlib으로 로드 (하이픈 패키지 대응)."""
    satori_path = Path("/home/jay/workspace/skills/satori-cardnews/_satori.py")
    spec = _ilu.spec_from_file_location("satori_cardnews__satori", str(satori_path))
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load _satori module from {satori_path}")
    mod = _ilu.module_from_spec(spec)
    spec.loader.exec_module(mod)  # type: ignore[union-attr]
    return mod


def _load_verify_module() -> Any:
    """satori-cardnews/scripts/verify_korean.py를 importlib으로 로드."""
    verify_path = Path("/home/jay/workspace/skills/satori-cardnews/scripts/verify_korean.py")
    spec = _ilu.spec_from_file_location("satori_cardnews_verify_korean", str(verify_path))
    if spec is None or spec.loader is None:
        raise ImportError(f"Cannot load verify_korean module from {verify_path}")
    mod = _ilu.module_from_spec(spec)
    spec.loader.exec_module(mod)  # type: ignore[union-attr]
    return mod


# ─── 카테고리별 색상 팔레트 ────────────────────────────────────────────────
BRAND_PALETTES: dict[str, dict[str, str]] = {
    "financial": {
        "bg_from": "#0a1628",
        "bg_to": "#1a2a4a",
        "accent": "#C8A96E",
        "title_color": "#ffffff",
        "body_color": "#d4b896",
        "overlay_bg": "rgba(10, 22, 40, 0.85)",
    },
    "saas": {
        "bg_from": "#1a0a3e",
        "bg_to": "#0a2a3a",
        "accent": "#7c3aed",
        "title_color": "#ffffff",
        "body_color": "#a78bfa",
        "overlay_bg": "rgba(26, 10, 62, 0.80)",
    },
    "consumer": {
        "bg_from": "#2d0a1e",
        "bg_to": "#1e0a2d",
        "accent": "#ec4899",
        "title_color": "#ffffff",
        "body_color": "#fde68a",
        "overlay_bg": "rgba(45, 10, 30, 0.80)",
    },
    "luxury": {
        "bg_from": "#0a0a0a",
        "bg_to": "#1a1a1a",
        "accent": "#d4af37",
        "title_color": "#ffffff",
        "body_color": "#c9b96a",
        "overlay_bg": "rgba(10, 10, 10, 0.90)",
    },
    "tech_minimal": {
        "bg_from": "#f8f9fa",
        "bg_to": "#e9ecef",
        "accent": "#212529",
        "title_color": "#212529",
        "body_color": "#495057",
        "overlay_bg": "rgba(248, 249, 250, 0.90)",
    },
    # 브랜드별 별칭
    "supabase": {
        "bg_from": "#1c1c1c",
        "bg_to": "#0f2417",
        "accent": "#3ecf8e",
        "title_color": "#ffffff",
        "body_color": "#a3e6c5",
        "overlay_bg": "rgba(28, 28, 28, 0.85)",
    },
    "linear": {
        "bg_from": "#0f0f1a",
        "bg_to": "#1a1a2e",
        "accent": "#5e6ad2",
        "title_color": "#ffffff",
        "body_color": "#a8adf4",
        "overlay_bg": "rgba(15, 15, 26, 0.85)",
    },
}

# ─── 5가지 패턴 HTML 빌더 ──────────────────────────────────────────────────

def _build_h1_photo_card(
    title: str,
    body: str,
    palette: dict[str, str],
    width: int,
    height: int,
) -> str:
    """h1_photo_card: 대형 헤드라인 + 하단 본문 (포토 카드 스타일)."""
    t = html_lib.escape(title)
    b = html_lib.escape(body)
    bg_from = palette["bg_from"]
    bg_to = palette["bg_to"]
    accent = palette["accent"]
    title_color = palette["title_color"]
    body_color = palette["body_color"]
    overlay_bg = palette["overlay_bg"]

    return (
        f'<div style="display:flex; flex-direction:column; width:{width}px; height:{height}px; '
        f'background:linear-gradient(160deg, {bg_from} 0%, {bg_to} 100%); '
        f'font-family:{_KOREAN_FONT_STACK}; position:relative;">'
        # 상단 accent 바
        f'<div style="display:flex; width:100%; height:6px; background:{accent};"></div>'
        # 메인 컨텐츠
        f'<div style="display:flex; flex:1; flex-direction:column; justify-content:flex-end; '
        f'padding:80px;">'
        f'<div style="display:flex; flex-direction:column; background:{overlay_bg}; '
        f'border-radius:24px; padding:56px; word-break:keep-all;">'
        f'<div style="font-size:72px; font-weight:700; color:{title_color}; '
        f'line-height:1.25; margin-bottom:28px; letter-spacing:-0.02em;">{t}</div>'
        f'<div style="font-size:36px; font-weight:400; color:{body_color}; '
        f'line-height:1.6;">{b}</div>'
        f'</div>'
        f'</div>'
        f'</div>'
    )


def _build_h2_illustration(
    title: str,
    body: str,
    palette: dict[str, str],
    width: int,
    height: int,
) -> str:
    """h2_illustration: 중앙 정렬 + 일러스트 스타일 원형 배경."""
    t = html_lib.escape(title)
    b = html_lib.escape(body)
    bg_from = palette["bg_from"]
    bg_to = palette["bg_to"]
    accent = palette["accent"]
    title_color = palette["title_color"]
    body_color = palette["body_color"]

    circle_size = min(width, height) // 2

    return (
        f'<div style="display:flex; flex-direction:column; align-items:center; '
        f'justify-content:center; width:{width}px; height:{height}px; '
        f'background:linear-gradient(135deg, {bg_from} 0%, {bg_to} 100%); '
        f'font-family:{_KOREAN_FONT_STACK}; padding:80px; position:relative;">'
        # 배경 원형 장식
        f'<div style="display:flex; position:absolute; width:{circle_size}px; '
        f'height:{circle_size}px; border-radius:9999px; '
        f'background:radial-gradient(circle, {accent}22, transparent 70%); '
        f'top:50%; left:50%; margin-top:-{circle_size//2}px; margin-left:-{circle_size//2}px;"></div>'
        # 텍스트
        f'<div style="display:flex; flex-direction:column; align-items:center; '
        f'text-align:center; word-break:keep-all; z-index:1;">'
        f'<div style="display:flex; width:64px; height:4px; background:{accent}; '
        f'margin-bottom:40px; border-radius:2px;"></div>'
        f'<div style="font-size:80px; font-weight:700; color:{title_color}; '
        f'line-height:1.2; margin-bottom:32px; letter-spacing:-0.025em;">{t}</div>'
        f'<div style="font-size:36px; font-weight:400; color:{body_color}; '
        f'line-height:1.55; max-width:80%;">{b}</div>'
        f'</div>'
        f'</div>'
    )


def _build_h3_gpt_style(
    title: str,
    body: str,
    palette: dict[str, str],
    width: int,
    height: int,
) -> str:
    """h3_gpt_style: 미니멀 + 좌측 강조선 (ChatGPT/Claude 스타일)."""
    t = html_lib.escape(title)
    b = html_lib.escape(body)
    bg_from = palette["bg_from"]
    bg_to = palette["bg_to"]
    accent = palette["accent"]
    title_color = palette["title_color"]
    body_color = palette["body_color"]

    return (
        f'<div style="display:flex; flex-direction:column; width:{width}px; height:{height}px; '
        f'background:linear-gradient(180deg, {bg_from} 0%, {bg_to} 100%); '
        f'font-family:{_KOREAN_FONT_STACK}; padding:100px;">'
        # 좌측 강조선 + 텍스트
        f'<div style="display:flex; flex-direction:row; gap:40px; flex:1;">'
        f'<div style="display:flex; width:6px; min-width:6px; background:{accent}; '
        f'border-radius:3px; align-self:stretch;"></div>'
        f'<div style="display:flex; flex-direction:column; justify-content:center; '
        f'word-break:keep-all; gap:32px;">'
        f'<div style="font-size:76px; font-weight:600; color:{title_color}; '
        f'line-height:1.3; letter-spacing:-0.02em;">{t}</div>'
        f'<div style="font-size:38px; font-weight:400; color:{body_color}; '
        f'line-height:1.6;">{b}</div>'
        f'</div>'
        f'</div>'
        f'</div>'
    )


def _build_h4_gradient(
    title: str,
    body: str,
    palette: dict[str, str],
    width: int,
    height: int,
) -> str:
    """h4_gradient: 그라데이션 배경 + 중앙 콘텐츠 박스."""
    t = html_lib.escape(title)
    b = html_lib.escape(body)
    bg_from = palette["bg_from"]
    bg_to = palette["bg_to"]
    accent = palette["accent"]
    title_color = palette["title_color"]
    body_color = palette["body_color"]
    overlay_bg = palette["overlay_bg"]

    return (
        f'<div style="display:flex; flex-direction:column; align-items:center; '
        f'justify-content:center; width:{width}px; height:{height}px; '
        f'background:linear-gradient(135deg, {bg_from} 0%, {accent}44 50%, {bg_to} 100%); '
        f'font-family:{_KOREAN_FONT_STACK}; padding:80px;">'
        f'<div style="display:flex; flex-direction:column; align-items:center; '
        f'background:{overlay_bg}; border-radius:32px; padding:72px 80px; '
        f'word-break:keep-all; text-align:center; width:100%; '
        f'border:1px solid {accent}33;">'
        f'<div style="font-size:78px; font-weight:700; color:{title_color}; '
        f'line-height:1.25; margin-bottom:32px; letter-spacing:-0.025em;">{t}</div>'
        f'<div style="display:flex; width:80px; height:3px; background:{accent}; '
        f'margin-bottom:32px; border-radius:2px;"></div>'
        f'<div style="font-size:38px; font-weight:400; color:{body_color}; '
        f'line-height:1.6;">{b}</div>'
        f'</div>'
        f'</div>'
    )


def _build_h5_user_photo(
    title: str,
    body: str,
    palette: dict[str, str],
    width: int,
    height: int,
) -> str:
    """h5_user_photo: 상단 프로필 영역 + 하단 텍스트 (유저 포토 스타일 시뮬)."""
    t = html_lib.escape(title)
    b = html_lib.escape(body)
    bg_from = palette["bg_from"]
    bg_to = palette["bg_to"]
    accent = palette["accent"]
    title_color = palette["title_color"]
    body_color = palette["body_color"]

    avatar_size = 120

    return (
        f'<div style="display:flex; flex-direction:column; width:{width}px; height:{height}px; '
        f'background:linear-gradient(160deg, {bg_from} 0%, {bg_to} 100%); '
        f'font-family:{_KOREAN_FONT_STACK}; padding:80px; gap:56px;">'
        # 상단 아바타 + 태그
        f'<div style="display:flex; flex-direction:row; align-items:center; gap:32px;">'
        f'<div style="display:flex; width:{avatar_size}px; height:{avatar_size}px; '
        f'border-radius:9999px; background:{accent}44; border:3px solid {accent}; '
        f'align-items:center; justify-content:center;">'
        f'<div style="font-size:48px; color:{accent};">K</div>'
        f'</div>'
        f'<div style="display:flex; flex-direction:column; gap:8px;">'
        f'<div style="font-size:28px; font-weight:600; color:{title_color};">User</div>'
        f'<div style="display:flex; padding:6px 16px; background:{accent}22; '
        f'border-radius:9999px; border:1px solid {accent}44;">'
        f'<div style="font-size:22px; color:{accent};">verified</div>'
        f'</div>'
        f'</div>'
        f'</div>'
        # 메인 텍스트
        f'<div style="display:flex; flex-direction:column; flex:1; '
        f'justify-content:center; word-break:keep-all; gap:28px;">'
        f'<div style="font-size:74px; font-weight:700; color:{title_color}; '
        f'line-height:1.3; letter-spacing:-0.02em;">{t}</div>'
        f'<div style="font-size:36px; font-weight:400; color:{body_color}; '
        f'line-height:1.6;">{b}</div>'
        f'</div>'
        f'</div>'
    )


# ─── 패턴 → 빌더 매핑 ─────────────────────────────────────────────────────
_PATTERN_BUILDERS: dict[str, Any] = {
    "h1_photo_card": _build_h1_photo_card,
    "h2_illustration": _build_h2_illustration,
    "h3_gpt_style": _build_h3_gpt_style,
    "h4_gradient": _build_h4_gradient,
    "h4_gradient_card": _build_h4_gradient,  # 별칭
    "h5_user_photo": _build_h5_user_photo,
}

# lazy-load 후 사용
_KOREAN_FONT_STACK = "'Pretendard', 'Noto Sans KR'"


def render_and_verify(
    *,
    brand: str,
    pattern: str,
    size: tuple[int, int],
    title: str,
    body: str,
    output_path: Path,
) -> dict[str, Any]:
    """templates/<pattern>.html 또는 인라인 HTML을 한글 텍스트로 채워 렌더 + 검증.

    Args:
        brand: 브랜드 식별자 (예: "supabase", "linear", "financial", "saas" 등).
        pattern: 패턴명 (예: "h4_gradient", "h1_photo_card" 등).
        size: (width, height) 픽셀.
        title: 한글 헤드라인.
        body: 한글 본문.
        output_path: 출력 PNG 경로.

    Returns:
        verify_korean.verify_png 결과 + {"render_path": str, "html_used": str}.

    Raises:
        ValueError: 알 수 없는 패턴.
        FileNotFoundError: 폰트 또는 Node.js 미존재.
        RuntimeError: 렌더 실패.
    """
    # 모듈 로드
    satori_mod = _load_satori_module()
    verify_mod = _load_verify_module()

    width, height = size

    # 팔레트 선택
    palette = BRAND_PALETTES.get(brand.lower(), BRAND_PALETTES["saas"])

    # 패턴 빌더 선택
    builder = _PATTERN_BUILDERS.get(pattern)
    if builder is None:
        raise ValueError(
            f"Unknown pattern: {pattern!r}. "
            f"Available: {list(_PATTERN_BUILDERS.keys())}"
        )

    # HTML 빌드
    html_str: str = builder(title, body, palette, width, height)

    # Satori 렌더
    output_path = Path(output_path)
    satori_mod.safe_render_html_to_png(html_str, output_path, width=width, height=height)

    # 검증
    verify_result: dict[str, Any] = verify_mod.verify_png(
        output_path,
        expected_korean=[title, body],
        html_source=html_str,
    )

    verify_result["render_path"] = str(output_path)
    verify_result["html_used"] = html_str[:1000]  # 첫 1000자만 기록

    return verify_result
