# tests/test_yaml_writer.py
import pytest
import yaml


@pytest.fixture
def sample_modules():
    from django_apcore.scanners.base import ScannedModule

    return [
        ScannedModule(
            module_id="api.v1.users.list",
            description="List all users with pagination support.",
            input_schema={
                "type": "object",
                "properties": {
                    "page": {"type": "integer"},
                    "limit": {"type": "integer"},
                },
                "required": [],
            },
            output_schema={
                "type": "object",
                "properties": {
                    "items": {"type": "array"},
                    "total": {"type": "integer"},
                },
                "required": ["items", "total"],
            },
            tags=["users", "read"],
            target="myapp.api:list_users",
        ),
        ScannedModule(
            module_id="api.v1.users.create",
            description="Create a new user.",
            input_schema={
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                },
                "required": ["name", "email"],
            },
            output_schema={
                "type": "object",
                "properties": {
                    "id": {"type": "integer"},
                    "name": {"type": "string"},
                },
                "required": ["id", "name"],
            },
            tags=["users", "write"],
            target="myapp.api:create_user",
        ),
    ]


class TestYAMLWriter:
    """Test YAML binding file generation."""

    def test_write_creates_files(self, tmp_path, sample_modules):
        from django_apcore.output.yaml_writer import YAMLWriter

        writer = YAMLWriter()
        writer.write(sample_modules, str(tmp_path))

        yaml_files = list(tmp_path.glob("*.binding.yaml"))
        assert len(yaml_files) == 2

    def test_write_creates_directory_if_missing(self, tmp_path, sample_modules):
        from django_apcore.output.yaml_writer import YAMLWriter

        output_dir = tmp_path / "new_dir" / "nested"
        writer = YAMLWriter()
        writer.write(sample_modules, str(output_dir))

        assert output_dir.exists()

    def test_yaml_is_valid(self, tmp_path, sample_modules):
        from django_apcore.output.yaml_writer import YAMLWriter

        writer = YAMLWriter()
        writer.write(sample_modules, str(tmp_path))

        for yaml_file in tmp_path.glob("*.binding.yaml"):
            data = yaml.safe_load(yaml_file.read_text())
            assert "bindings" in data

    def test_yaml_contains_module_fields(self, tmp_path, sample_modules):
        from django_apcore.output.yaml_writer import YAMLWriter

        writer = YAMLWriter()
        writer.write(sample_modules, str(tmp_path))

        yaml_file = tmp_path / "api.v1.users.list.binding.yaml"
        data = yaml.safe_load(yaml_file.read_text())
        binding = data["bindings"][0]

        assert binding["module_id"] == "api.v1.users.list"
        assert binding["target"] == "myapp.api:list_users"
        assert binding["description"] == "List all users with pagination support."
        assert binding["tags"] == ["users", "read"]
        assert binding["version"] == "1.0.0"
        assert "input_schema" in binding
        assert "output_schema" in binding

    def test_yaml_has_header_comment(self, tmp_path, sample_modules):
        from django_apcore.output.yaml_writer import YAMLWriter

        writer = YAMLWriter()
        writer.write(sample_modules, str(tmp_path))

        yaml_file = tmp_path / "api.v1.users.list.binding.yaml"
        content = yaml_file.read_text()
        assert "Auto-generated by django-apcore" in content

    def test_write_empty_list(self, tmp_path):
        from django_apcore.output.yaml_writer import YAMLWriter

        writer = YAMLWriter()
        writer.write([], str(tmp_path))

        yaml_files = list(tmp_path.glob("*.binding.yaml"))
        assert len(yaml_files) == 0

    def test_overwrite_existing_file(self, tmp_path, sample_modules):
        from django_apcore.output.yaml_writer import YAMLWriter

        writer = YAMLWriter()
        writer.write(sample_modules, str(tmp_path))
        # Write again -- should overwrite
        writer.write(sample_modules, str(tmp_path))

        yaml_files = list(tmp_path.glob("*.binding.yaml"))
        assert len(yaml_files) == 2

    def test_dry_run_does_not_write(self, tmp_path, sample_modules):
        from django_apcore.output.yaml_writer import YAMLWriter

        writer = YAMLWriter()
        result = writer.write(sample_modules, str(tmp_path), dry_run=True)

        yaml_files = list(tmp_path.glob("*.binding.yaml"))
        assert len(yaml_files) == 0
        # Should still return the content that would be written
        assert len(result) == 2
