from __future__ import annotations

from pathlib import Path

from aicd.tools.raster_document_fit import (
    augment_img_tags_for_story,
    fit_display_pt,
    strip_br_inside_html_tables,
)


def test_fit_display_caps_height() -> None:
    # 宽图：先满宽再压高度
    w, h = fit_display_pt(1600, 2400, max_width_pt=400, max_height_pt=300)
    assert w < 400 - 0.01
    assert abs(h - 300) < 0.02


def test_fit_display_full_width_short_image() -> None:
    w, h = fit_display_pt(800, 200, max_width_pt=400, max_height_pt=500)
    assert abs(w - 400) < 0.02
    assert h < 150


def test_strip_br_inside_tables() -> None:
    html = "<table><tr><td>a<br/>b</td></tr></table><p>x<br>y</p>"
    out = strip_br_inside_html_tables(html)
    assert "<br" not in out.split("</table>")[0]
    assert "<br" in out.split("</table>")[1]


def test_augment_img_wraps(tmp_path: Path) -> None:
    from PIL import Image

    png = tmp_path / "f.png"
    Image.new("RGB", (400, 1200), color=(255, 0, 0)).save(png)
    frag = '<p>x</p><img src="f.png" alt="n">'
    new_f, meta = augment_img_tags_for_story(
        frag, tmp_path, body_width_pt=400, body_height_pt=700
    )
    assert "aicd-figure" in new_f
    assert meta.get("wrapped_images") == 1
    assert "width:" in new_f and "pt" in new_f
    assert not meta.get("missing_srcs")
    assert "<p><div" not in new_f
