"""
E2E tests for Export functionality.

Tests export-related tools using real Godot demo projects:
- project_export
- project_list_export_presets
- resource_export_mesh_library
"""

from pathlib import Path


from godot_mcp.server import resource_export_mesh_library, project_export, project_list_export_presets


class TestListExportPresets:
    """E2E tests for project_list_export_presets tool."""

    def test_list_presets_on_demo_project(self, any_demo_project: Path) -> None:
        """Test listing export presets on a real demo project."""
        result = project_list_export_presets(
            project_path=str(any_demo_project),
        )

        # Demo projects may or may not have presets configured
        assert isinstance(result, str)
        # Should return valid response (list or "no presets")

    def test_list_presets_with_config(self, demo_project_copy: Path) -> None:
        """Test listing presets after creating export_presets.cfg."""
        # Create export presets configuration
        export_presets_content = """[preset.0]

name="Windows Desktop"
platform="Windows Desktop"
runnable=true
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter=""
exclude_filter=""
export_path=""
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false

[preset.0.options]

custom_template/debug=""
custom_template/release=""

[preset.1]

name="Linux/X11"
platform="Linux"
runnable=true

[preset.1.options]

custom_template/debug=""
custom_template/release=""
"""
        presets_file = demo_project_copy / "export_presets.cfg"
        presets_file.write_text(export_presets_content, encoding="utf-8")

        result = project_list_export_presets(
            project_path=str(demo_project_copy),
        )

        # Should list the presets
        assert "Windows" in result or "windows" in result.lower()
        assert "Linux" in result or "linux" in result.lower()


class TestExportProject:
    """E2E tests for project_export tool."""

    def test_export_without_preset(self, demo_project_copy: Path) -> None:
        """Test export without configured presets."""
        result = project_export(
            project_path=str(demo_project_copy),
            preset_name="Windows Desktop",
            output_path=str(demo_project_copy / "builds" / "game.exe"),
        )

        # Should fail gracefully (no presets configured)
        assert isinstance(result, str)

    def test_export_with_preset_config(self, demo_project_copy: Path) -> None:
        """Test export with configured preset."""
        # Create export presets
        export_presets_content = """[preset.0]

name="E2E Test Export"
platform="Windows Desktop"
runnable=true
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter=""
exclude_filter=""
export_path=""
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false

[preset.0.options]

custom_template/debug=""
custom_template/release=""
"""
        presets_file = demo_project_copy / "export_presets.cfg"
        presets_file.write_text(export_presets_content, encoding="utf-8")

        # Create builds directory
        builds_dir = demo_project_copy / "builds"
        builds_dir.mkdir(exist_ok=True)

        result = project_export(
            project_path=str(demo_project_copy),
            preset_name="E2E Test Export",
            output_path=str(builds_dir / "game.exe"),
        )

        # May fail due to missing export templates, but should attempt
        assert isinstance(result, str)

    def test_export_pck_only(self, demo_project_copy: Path) -> None:
        """Test exporting as PCK file only."""
        # Create export presets
        export_presets_content = """[preset.0]

name="PCK Export"
platform="Windows Desktop"
runnable=true

[preset.0.options]

custom_template/debug=""
custom_template/release=""
"""
        presets_file = demo_project_copy / "export_presets.cfg"
        presets_file.write_text(export_presets_content, encoding="utf-8")

        builds_dir = demo_project_copy / "builds"
        builds_dir.mkdir(exist_ok=True)

        result = project_export(
            project_path=str(demo_project_copy),
            preset_name="PCK Export",
            output_path=str(builds_dir / "game.pck"),
            export_pack=True,
        )

        assert isinstance(result, str)

    def test_export_debug_mode(self, demo_project_copy: Path) -> None:
        """Test export with debug mode enabled."""
        export_presets_content = """[preset.0]

name="Debug Export"
platform="Windows Desktop"
runnable=true

[preset.0.options]

custom_template/debug=""
custom_template/release=""
"""
        presets_file = demo_project_copy / "export_presets.cfg"
        presets_file.write_text(export_presets_content, encoding="utf-8")

        result = project_export(
            project_path=str(demo_project_copy),
            preset_name="Debug Export",
            output_path=str(demo_project_copy / "builds" / "game_debug.exe"),
            debug=True,
        )

        assert isinstance(result, str)


class TestExportMeshLibrary:
    """E2E tests for resource_export_mesh_library tool."""

    def test_resource_export_mesh_library_invalid_scene(self, demo_project_copy: Path) -> None:
        """Test export mesh library with non-existent scene."""
        result = resource_export_mesh_library(
            project_path=str(demo_project_copy),
            scene_path="nonexistent_scene.tscn",
            output_path="mesh_library.tres",
        )

        # Should fail gracefully
        assert "error" in result.lower() or "not" in result.lower()

    def test_resource_export_mesh_library_from_3d_scene(self, demo_project_copy: Path) -> None:
        """Test export mesh library from a 3D scene."""
        from godot_mcp.server import node_add, scene_create

        # Create a 3D scene with mesh instances
        scene_create(
            project_path=str(demo_project_copy),
            scene_path="e2e_mesh_lib_source.tscn",
            root_node_type="Node3D",
        )

        # Add some mesh instances
        node_add(
            project_path=str(demo_project_copy),
            scene_path="e2e_mesh_lib_source.tscn",
            node_type="MeshInstance3D",
            node_name="Mesh1",
            parent_node_path="root",
        )
        node_add(
            project_path=str(demo_project_copy),
            scene_path="e2e_mesh_lib_source.tscn",
            node_type="MeshInstance3D",
            node_name="Mesh2",
            parent_node_path="root",
        )

        result = resource_export_mesh_library(
            project_path=str(demo_project_copy),
            scene_path="e2e_mesh_lib_source.tscn",
            output_path="e2e_mesh_library.tres",
        )

        # May succeed or fail depending on mesh setup
        assert isinstance(result, str)


class TestExportWorkflow:
    """Integration tests for export workflows."""

    def test_complete_export_setup_workflow(self, demo_project_copy: Path) -> None:
        """Test a complete export setup workflow."""
        # Step 1: List existing presets (should be empty/none)
        list_result = project_list_export_presets(
            project_path=str(demo_project_copy),
        )
        assert isinstance(list_result, str)

        # Step 2: Create export presets
        export_presets_content = """[preset.0]

name="Windows Desktop"
platform="Windows Desktop"
runnable=true
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter=""
exclude_filter=""
export_path=""
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false

[preset.0.options]

custom_template/debug=""
custom_template/release=""

[preset.1]

name="macOS"
platform="macOS"
runnable=true

[preset.1.options]

custom_template/debug=""
custom_template/release=""

[preset.2]

name="Linux/X11"
platform="Linux/X11"
runnable=true

[preset.2.options]

custom_template/debug=""
custom_template/release=""
"""
        presets_file = demo_project_copy / "export_presets.cfg"
        presets_file.write_text(export_presets_content, encoding="utf-8")

        # Step 3: List presets again (should show all three)
        list_result_after = project_list_export_presets(
            project_path=str(demo_project_copy),
        )
        assert "Windows" in list_result_after
        assert "macOS" in list_result_after or "macos" in list_result_after.lower()
        assert "Linux" in list_result_after

        # Step 4: Create builds directory
        builds_dir = demo_project_copy / "builds"
        builds_dir.mkdir(exist_ok=True)

        # Step 5: Attempt exports (will fail without templates, but tests the flow)
        for preset, output_name in [
            ("Windows Desktop", "game_win.exe"),
            ("macOS", "game_mac.app"),
            ("Linux/X11", "game_linux"),
        ]:
            result = project_export(
                project_path=str(demo_project_copy),
                preset_name=preset,
                output_path=str(builds_dir / output_name),
            )
            # Should complete (even if export fails due to missing templates)
            assert isinstance(result, str)
