"""Test hybrid xlsxwriter + import_sheet functionality.

This test verifies that workbooks with import_sheet() can be saved using
engine="xlsxwriter" via the hybrid save path (xlsxwriter for SheetNodes,
openpyxl for ImportedSheetNodes with post-merge).
"""

from __future__ import annotations

import sys
import tempfile
from pathlib import Path

# Add src directory to Python path before importing xpyxl
_project_root = Path(__file__).resolve().parent.parent
_src_dir = _project_root / "src"
if str(_src_dir) not in sys.path:
    sys.path.insert(0, str(_src_dir))

import openpyxl

import xpyxl as x


def _create_template(path: Path) -> None:
    """Create a template workbook with specific properties for testing."""
    wb = openpyxl.Workbook()
    ws = wb.active
    if ws is None:
        raise RuntimeError("Expected an active worksheet")
    ws.title = "Template"

    # Add content with a merge
    ws["A1"] = "Template Title"
    ws["A1"].style = "Title"
    ws.merge_cells("A1:C1")

    # Add more content
    ws["A3"] = "Notes"
    ws["A4"] = "Static content from template"

    # Set dimensions
    ws.column_dimensions["A"].width = 24
    ws.column_dimensions["B"].width = 16
    ws.row_dimensions[1].height = 28

    # Set freeze panes and auto filter
    ws.freeze_panes = "A3"
    ws.auto_filter.ref = "A3:C10"

    wb.save(path)


def test_xlsxwriter_with_import_sheet() -> None:
    """Test that xlsxwriter engine works with import_sheet via hybrid save."""
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        template_path = tmppath / "template.xlsx"
        output_path = tmppath / "output.xlsx"

        # Create template
        _create_template(template_path)

        # Build workbook with imported sheet + generated sheets
        workbook = x.workbook()[
            x.sheet("Before")[
                x.row(style=[x.bold])["Generated Before"],
                x.row()["A", 1],
            ],
            x.import_sheet(template_path, "Template", name="Imported"),
            x.sheet("After")[
                x.row(style=[x.bold])["Generated After"],
                x.row()["B", 2],
            ],
        ]

        # Save with xlsxwriter engine (should use hybrid save)
        workbook.save(output_path, engine="xlsxwriter")

        # Verify the output
        result_wb = openpyxl.load_workbook(output_path)

        # Check sheet order matches declaration order
        expected_order = ["Before", "Imported", "After"]
        actual_order = result_wb.sheetnames
        assert actual_order == expected_order, (
            f"Sheet order mismatch: expected {expected_order}, got {actual_order}"
        )

        # Check generated sheets have content
        before_ws = result_wb["Before"]
        assert before_ws["A1"].value == "Generated Before"
        assert before_ws["A2"].value == "A"
        assert before_ws["B2"].value == 1

        after_ws = result_wb["After"]
        assert after_ws["A1"].value == "Generated After"
        assert after_ws["A2"].value == "B"
        assert after_ws["B2"].value == 2

        # Check imported sheet preserves properties
        imported_ws = result_wb["Imported"]
        assert imported_ws["A1"].value == "Template Title"
        assert imported_ws["A3"].value == "Notes"
        assert imported_ws["A4"].value == "Static content from template"

        # Check merge was preserved
        merged_ranges = list(imported_ws.merged_cells.ranges)
        assert len(merged_ranges) == 1
        assert str(merged_ranges[0]) == "A1:C1"

        # Check freeze panes
        assert imported_ws.freeze_panes == "A3"

        # Check auto filter
        assert imported_ws.auto_filter.ref == "A3:C10"

        # Check dimensions (with tolerance for float comparison)
        col_a_width = imported_ws.column_dimensions["A"].width
        assert col_a_width is not None and abs(col_a_width - 24) < 1, (
            f"Column A width should be ~24, got {col_a_width}"
        )

        row_1_height = imported_ws.row_dimensions[1].height
        assert row_1_height is not None and abs(row_1_height - 28) < 1, (
            f"Row 1 height should be ~28, got {row_1_height}"
        )

        print("✓ All assertions passed!")


def test_xlsxwriter_only_imported_sheets() -> None:
    """Test hybrid save when workbook has only imported sheets (no SheetNodes)."""
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        template_path = tmppath / "template.xlsx"
        output_path = tmppath / "output.xlsx"

        # Create template
        _create_template(template_path)

        # Build workbook with only imported sheet
        workbook = x.workbook()[
            x.import_sheet(template_path, "Template", name="OnlyImported"),
        ]

        # Save with xlsxwriter engine
        workbook.save(output_path, engine="xlsxwriter")

        # Verify the output
        result_wb = openpyxl.load_workbook(output_path)
        assert result_wb.sheetnames == ["OnlyImported"]
        assert result_wb["OnlyImported"]["A1"].value == "Template Title"

        print("✓ Only-imported test passed!")


def test_xlsxwriter_no_imported_sheets() -> None:
    """Test that xlsxwriter works normally when no import_sheet is used."""
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        output_path = tmppath / "output.xlsx"

        # Build workbook with only generated sheets
        workbook = x.workbook()[
            x.sheet("Sheet1")[x.row()["Hello", "World"]],
            x.sheet("Sheet2")[x.row()["Foo", "Bar"]],
        ]

        # Save with xlsxwriter engine (should use standard path)
        workbook.save(output_path, engine="xlsxwriter")

        # Verify the output
        result_wb = openpyxl.load_workbook(output_path)
        assert result_wb.sheetnames == ["Sheet1", "Sheet2"]
        assert result_wb["Sheet1"]["A1"].value == "Hello"
        assert result_wb["Sheet2"]["A1"].value == "Foo"

        print("✓ No-imported test passed!")


def test_xlsxwriter_bytes_output() -> None:
    """Test hybrid save returns bytes when target is None."""
    with tempfile.TemporaryDirectory() as tmpdir:
        tmppath = Path(tmpdir)
        template_path = tmppath / "template.xlsx"

        # Create template
        _create_template(template_path)

        # Build workbook with imported sheet
        workbook = x.workbook()[
            x.sheet("Gen")[x.row()["Data"]],
            x.import_sheet(template_path, "Template"),
        ]

        # Save with xlsxwriter engine, no target (returns bytes)
        result_bytes = workbook.save(engine="xlsxwriter")

        assert result_bytes is not None
        assert isinstance(result_bytes, bytes)
        assert len(result_bytes) > 0

        # Verify the bytes are a valid xlsx
        from io import BytesIO

        result_wb = openpyxl.load_workbook(BytesIO(result_bytes))
        assert "Gen" in result_wb.sheetnames
        assert "Template" in result_wb.sheetnames

        print("✓ Bytes output test passed!")


if __name__ == "__main__":
    print("Running xlsxwriter + import_sheet tests...\n")
    test_xlsxwriter_with_import_sheet()
    test_xlsxwriter_only_imported_sheets()
    test_xlsxwriter_no_imported_sheets()
    test_xlsxwriter_bytes_output()
    print("\n✓ All tests passed!")
