"""markdown_to_pdf：默认 CSS 与可选源快照。"""

from __future__ import annotations

import base64
from pathlib import Path

import pytest

from aicd.tools import markdown_to_pdf as mtp

# 最小 1×1 PNG（有效 zlib）
_MIN_PNG = base64.b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
)


def test_story_css_avoids_black_header_defaults() -> None:
    css = mtp.DEFAULT_STORY_CSS
    assert "thead" in css
    assert "border-collapse: separate" in css
    assert "hr" in css
    assert "#e8e8e8" in css or "#eeeeee" in css


def _allow(_p: Path) -> None:
    return None


def test_export_with_source_snapshot(tmp_path: Path) -> None:
    pytest.importorskip("fitz")
    pytest.importorskip("markdown")
    md = "| Col1 | Col2 |\n| --- | --- |\n| a | b |\n"
    pdf = tmp_path / "out.pdf"
    snap = tmp_path / "out_source.md"
    r = mtp.export_markdown_to_pdf(
        output_pdf_path=pdf,
        policy_check=_allow,
        markdown_text=md,
        source_snapshot_path=snap,
    )
    assert r.get("ok"), r
    assert pdf.is_file() and pdf.stat().st_size > 0
    assert snap.is_file()
    assert "Col1" in snap.read_text(encoding="utf-8")
    assert r.get("source_snapshot_path")


def test_pymupdf_story_embeds_image_when_archive_matches_file_parent(
    tmp_path: Path,
) -> None:
    """相对路径图片：archive 须含 png 所在目录；误用 PDF 父目录时 Story 不嵌入图块。"""
    pytest.importorskip("fitz")
    pytest.importorskip("markdown")
    root = tmp_path
    (root / "fig.png").write_bytes(_MIN_PNG)
    out_dir = root / "deliverables"
    out_dir.mkdir()
    pdf_wrong = out_dir / "report_wrong.pdf"
    pdf_right = out_dir / "report_right.pdf"
    md = "![](fig.png)\n"
    r_wrong = mtp.export_markdown_to_pdf(
        output_pdf_path=pdf_wrong,
        policy_check=_allow,
        markdown_text=md,
        archive_path=out_dir,
    )
    r_right = mtp.export_markdown_to_pdf(
        output_pdf_path=pdf_right,
        policy_check=_allow,
        markdown_text=md,
        archive_path=root,
    )
    assert r_wrong.get("ok") and r_right.get("ok"), (r_wrong, r_right)
    import fitz

    bad = fitz.open(str(pdf_wrong))
    good = fitz.open(str(pdf_right))
    try:
        assert bad[0].get_images() == []
        assert len(good[0].get_images()) >= 1
    finally:
        bad.close()
        good.close()
