"""
模板引擎高级能力测试。
"""

from pathlib import Path

import pytest
from PIL import Image

from src.symphra_excel.templates.template_workbook import TemplateWorkbook
from src.symphra_excel.utils.exceptions import TemplateError


def _create_dummy_image(tmp_path: Path) -> Path:
    path = tmp_path / "dummy.png"
    image = Image.new("RGB", (10, 10), color="red")
    image.save(path)
    return path


def test_template_loop_and_condition(tmp_path: Path) -> None:
    workbook = TemplateWorkbook()
    sheet = workbook.active

    # Loop structure
    sheet.set_value("A1", "{% for product in products %}")
    sheet.set_value("A2", "{{ product.name }}")
    sheet.set_value("B2", "{{ product.price }}")
    sheet.set_value("A3", "{% endfor %}")

    # Conditional section
    sheet.set_value("A4", "{% if show_total %}")
    sheet.set_value("A5", "Total")
    sheet.set_value("B5", "{{ total }}")
    sheet.set_value("A6", "{% endif %}")

    context = {
        "products": [
            {"name": "Apple", "price": 3},
            {"name": "Orange", "price": 5},
        ],
        "show_total": True,
        "total": 8,
    }

    workbook.render(context)

    assert sheet.get_cell_value("A1") == "Apple"
    assert sheet.get_cell_value("B1") == 3
    assert sheet.get_cell_value("A2") == "Orange"
    assert sheet.get_cell_value("B2") == 5
    assert sheet.get_cell_value("A3") == "Total"
    assert sheet.get_cell_value("B3") == 8


def test_template_loop_condition_false() -> None:
    workbook = TemplateWorkbook()
    sheet = workbook.active

    sheet.set_value("A1", "{% if show %}")
    sheet.set_value("A2", "Visible")
    sheet.set_value("A3", "{% else %}")
    sheet.set_value("A4", "Hidden")
    sheet.set_value("A5", "{% endif %}")

    workbook.render({"show": False})
    assert sheet.get_cell_value("A1") == "Hidden"
    assert sheet.max_row == 1


def test_template_image_placeholder(tmp_path: Path) -> None:
    image_path = _create_dummy_image(tmp_path)

    workbook = TemplateWorkbook()
    sheet = workbook.active

    sheet.set_value("A1", "{{ insert_image(image_path, width=12, height=12) }}")
    workbook.render({"image_path": str(image_path)})

    # 值被清除成 None，同时图片被挂载到 openpyxl 工作表中
    assert sheet.get_cell_value("A1") is None
    assert len(sheet._worksheet._images) == 1


def test_template_disallows_callable_context() -> None:
    workbook = TemplateWorkbook()
    sheet = workbook.active
    sheet.set_value("A1", "{{ value }}")

    with pytest.raises(TemplateError):
        workbook.render({"value": lambda: 1})


def test_template_disallows_unknown_filters() -> None:
    workbook = TemplateWorkbook()
    sheet = workbook.active
    sheet.set_value("A1", "{{ name|urlencode }}")

    with pytest.raises(TemplateError):
        workbook.render({"name": "foo"})
