"""packages.shared.title_overlay 单元测试。"""

from __future__ import annotations

import tempfile
from pathlib import Path

import pytest

from packages.shared.title_overlay import apply_title_to_image, wrap_title_text


@pytest.fixture
def sample_image():
    """生成一张 640x360 的纯黑测试图片。"""
    from PIL import Image

    tmp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
    tmp.close()
    img = Image.new("RGB", (640, 360), color=(0, 0, 0))
    img.save(tmp.name, "JPEG")
    yield tmp.name
    Path(tmp.name).unlink(missing_ok=True)


def test_apply_title_to_image_empty_text_returns_none(sample_image):
    assert apply_title_to_image(sample_image, "") is None
    assert apply_title_to_image(sample_image, "   ") is None


def test_apply_title_to_image_draws_title(sample_image):
    result = apply_title_to_image(sample_image, "测试标题")
    assert result == sample_image
    assert Path(sample_image).exists()
    assert Path(sample_image).stat().st_size > 0


def test_apply_title_to_image_respects_position(sample_image):
    for pos in ("top", "center", "bottom"):
        result = apply_title_to_image(sample_image, "位置测试", position=pos)
        assert result == sample_image


def test_wrap_title_text_supports_long_text():
    from PIL import ImageFont

    font = ImageFont.load_default()
    lines = wrap_title_text("这是一个比较长的标题需要自动换行处理ABC", font, max_width=40)
    assert isinstance(lines, list)
    assert len(lines) >= 1


def test_wrap_title_text_respects_explicit_newline():
    from PIL import ImageFont

    font = ImageFont.load_default()
    lines = wrap_title_text("第一行\n第二行", font, max_width=10000)
    assert lines == ["第一行", "第二行"]


def test_apply_title_to_image_custom_color(sample_image):
    """自定义颜色参数能正常生成图片。"""
    result = apply_title_to_image(sample_image, "彩色标题", color="#ff0000")
    assert result == sample_image
    assert Path(sample_image).stat().st_size > 0


def test_apply_title_to_image_short_hex_color(sample_image):
    """3 位缩写 hex 颜色也能正常解析。"""
    result = apply_title_to_image(sample_image, "短色", color="#f00")
    assert result == sample_image


def test_apply_title_to_image_invalid_color_fallback(sample_image):
    """无效颜色字符串 fallback 到白色，不报错。"""
    result = apply_title_to_image(sample_image, "异常色", color="not-a-color")
    assert result == sample_image


def test_parse_hex_color():
    from packages.shared.title_overlay import _parse_hex_color

    assert _parse_hex_color("#ffffff") == (255, 255, 255)
    assert _parse_hex_color("#000000") == (0, 0, 0)
    assert _parse_hex_color("#ff0000") == (255, 0, 0)
    assert _parse_hex_color("#f00") == (255, 0, 0)
    assert _parse_hex_color("") == (255, 255, 255)
    assert _parse_hex_color("invalid") == (255, 255, 255)
    assert _parse_hex_color("#gggggg") == (255, 255, 255)
