"""Tests for Bug 1 fix: instance override nodes resolved instead of orphaned."""

from __future__ import annotations

from pathlib import Path
import tempfile

from godotiq.parsers.tscn_parser import parse_tscn, TscnNode


FIXTURE = (
    Path(__file__).resolve().parent.parent
    / "fixtures"
    / "instance_override.tscn"
)


class TestInstanceOverrideNodes:
    """Nodes inside instanced scenes are attached under the instance node."""

    def test_override_nodes_attached_to_instance(self) -> None:
        """Terrain, Marker3D, Human are children of Map (instance node), not lost."""
        scene = parse_tscn(str(FIXTURE))
        assert scene.root is not None

        # Find the Map instance node (direct child of root)
        map_node: TscnNode | None = None
        for child in scene.root.children:
            if child.name == "Map":
                map_node = child
                break
        assert map_node is not None, "Map node must exist as child of root"
        assert map_node.instance is not None, "Map must be an instance node"

        # All override nodes should be attached under Map
        map_child_names = {c.name for c in map_node.children}
        assert "Terrain" in map_child_names, "Terrain must be under Map"
        assert "Marker3D" in map_child_names, "Marker3D must be under Map"
        assert "Human" in map_child_names, "Human must be under Map"

    def test_override_nodes_flagged(self) -> None:
        """Override nodes have is_instance_override = True."""
        scene = parse_tscn(str(FIXTURE))
        assert scene.root is not None

        map_node = next(c for c in scene.root.children if c.name == "Map")
        for child in map_node.children:
            assert child.is_instance_override is True, (
                f"Node '{child.name}' should have is_instance_override=True"
            )

    def test_no_orphan_warnings(self, caplog) -> None:
        """No 'Parent not found' warnings for instance override nodes."""
        import logging

        with caplog.at_level(logging.WARNING, logger="godotiq.parsers.tscn_parser"):
            parse_tscn(str(FIXTURE))

        parent_not_found = [
            r for r in caplog.records if "Parent not found" in r.message
        ]
        assert len(parent_not_found) == 0, (
            f"Should not log 'Parent not found' for override nodes, "
            f"got: {[r.message for r in parent_not_found]}"
        )

    def test_non_instance_orphan_still_warns(self, caplog) -> None:
        """A truly orphaned node (no instance parent) still triggers a warning."""
        import logging

        tscn_content = '[gd_scene format=3]\n\n[node name="Root" type="Node3D"]\n\n[node name="Child" type="Node3D" parent="NonExistent"]\n'
        with tempfile.NamedTemporaryFile(
            mode="w", suffix=".tscn", delete=False
        ) as f:
            f.write(tscn_content)
            tmp_path = f.name

        with caplog.at_level(logging.WARNING, logger="godotiq.parsers.tscn_parser"):
            parse_tscn(tmp_path)

        parent_not_found = [
            r for r in caplog.records if "Parent not found" in r.message
        ]
        assert len(parent_not_found) == 1

        Path(tmp_path).unlink(missing_ok=True)
