# pyright: reportMissingImports=false
"""IDS Phase 1 — 한글 100% OCR 회귀 검증 (구조 + 폰트 fallback 차단).

목적:
1. 출력 PNG가 존재할 경우 OCR로 한글 추출, 입력과 100% 일치 확인
2. OCR 라이브러리 미설치 환경에서는 graceful skip
3. 폰트 fallback 차단 — 시스템 sans-serif/Arial이 HTML/CSS에 절대 들어가지 않음
4. 실패 시 폰트 fallback 차단 + 명확한 에러 (assert 메시지)

OCR 도구는 환경 의존이므로 미설치 시 skip — 단, 폰트 차단 검증은 항상 수행.
"""

from __future__ import annotations

import sys
from pathlib import Path

import pytest

WORKSPACE_ROOT = Path("/home/jay/workspace")
SATORI_SKILL = WORKSPACE_ROOT / "skills" / "satori-cardnews"
HYBRID_SKILL = WORKSPACE_ROOT / "skills" / "hybrid-image"

sys.path.insert(0, str(SATORI_SKILL))
sys.path.insert(0, str(HYBRID_SKILL))


# ---------------------------------------------------------------------------
# 폰트 fallback 차단 (항상 수행, OCR 도구 미설치 무관)
# ---------------------------------------------------------------------------

# 한글 깨짐 유발 fallback 폰트 — HTML/CSS 어디에도 등장하면 FAIL
FORBIDDEN_FALLBACK_TOKENS = [
    "Arial",
    "Helvetica",
    "Open Sans",
    "Roboto",
    "Malgun Gothic",
]


def _scan_html_files() -> list[Path]:
    return list((SATORI_SKILL / "templates").glob("*.html"))


@pytest.mark.parametrize("html_path", _scan_html_files())
def test_template_no_forbidden_fallback(html_path):
    """템플릿 HTML에 시스템 fallback 폰트가 명시되어 있으면 한글 깨짐."""
    text = html_path.read_text(encoding="utf-8")
    for token in FORBIDDEN_FALLBACK_TOKENS:
        # font-family 컨텍스트에서만 차단
        for line in text.splitlines():
            if "font-family" not in line.lower():
                continue
            assert token not in line, (
                f"{html_path.name}: 한글 fallback 차단 위반 — '{token}' 발견. "
                f"line={line.strip()!r}. Pretendard/Noto Sans KR 외 사용 금지."
            )


def test_pattern_modules_use_korean_font_stack():
    """hybrid-image 패턴 모듈은 KOREAN_FONT_STACK ('Pretendard', 'Noto Sans KR')를 사용해야 한다."""
    from patterns import _satori

    stack = _satori.KOREAN_FONT_STACK
    assert "Pretendard" in stack
    assert "Noto Sans KR" in stack
    # system fallback 미포함
    for token in FORBIDDEN_FALLBACK_TOKENS:
        assert token not in stack, f"KOREAN_FONT_STACK에 forbidden 폰트 발견: {token}"


# ---------------------------------------------------------------------------
# OCR 회귀 (도구 설치 시만 수행)
# ---------------------------------------------------------------------------


def _have_ocr() -> bool:
    import importlib.util

    if importlib.util.find_spec("pytesseract") is not None:
        return True
    if importlib.util.find_spec("paddleocr") is not None:
        return True
    return False


@pytest.mark.skipif(not _have_ocr(), reason="OCR 도구 미설치 — pytesseract/paddleocr 필요")
def test_korean_ocr_roundtrip(tmp_path):
    """H4 (gradient, 외부 호출 0) 패턴으로 한글 PNG 생성 → OCR → 입력 일치 확인."""
    from patterns import render_h4_gradient_card

    title = "보험은 안심"
    body = "가족을 지키는 첫걸음입니다"
    out = tmp_path / "ocr_test.png"
    result = render_h4_gradient_card(title, body, out, size=(1080, 1080))
    assert result.exists(), "PNG 생성 실패"
    assert result.stat().st_size > 1000, "PNG 너무 작음 — 렌더 실패 의심"

    try:
        import pytesseract
        from PIL import Image
        text = pytesseract.image_to_string(Image.open(result), lang="kor")
    except ImportError:
        pytest.skip("pytesseract 미설치")

    # OCR이 완벽하지 않으므로 핵심 키워드 포함 여부로 판정
    assert "보험" in text or "안심" in text, (
        f"OCR 한글 추출 실패: 입력=({title!r}, {body!r}), 출력={text!r}"
    )


# ---------------------------------------------------------------------------
# 한글 입력 raw 보존 검증 (OCR 무관, HTML 빌드 단계)
# ---------------------------------------------------------------------------


def test_h4_html_preserves_korean_raw():
    """H4 패턴이 만든 HTML 안에 입력 한글이 그대로 들어있어야 한다."""
    from patterns._backgrounds import default_gradient
    from patterns._satori import build_text_overlay_html

    title = "한글 테스트 헤드라인"
    body = "본문 한글이 깨지지 않아야 한다"
    html = build_text_overlay_html(
        title=title,
        body=body,
        width=1080,
        height=1350,
        background_layer=f'<div style="background:{default_gradient("navy")};width:100%;height:100%;"></div>',
        title_color="#ffffff",
        body_color="#e8e8ec",
        overlay_bg="rgba(0,0,0,0.5)",
        title_size=72,
        body_size=38,
    )
    assert title in html, f"제목 한글이 HTML에 보존되지 않음: title={title!r}"
    assert body in html, f"본문 한글이 HTML에 보존되지 않음: body={body!r}"
    # Pretendard 명시 보장
    assert "Pretendard" in html, "Pretendard 폰트 명시 누락"
