from unittest.mock import MagicMock, patch

import pytest

from axm.catalog.entries import Identity, Location, Owner, SchemaFormat
from axm.catalog.validation.validator import SchemaValidator
from axm_image.entries.image import ImageEntry, ImageSchema, ImageSpec


@pytest.fixture
def image_entry():
    """Create a minimal valid ImageEntry for testing."""
    return ImageEntry(
        name="test_image_dataset",
        version="1.0.0",
        identity=Identity(
            display_name="Test Images",
            description="Unit test images",
            domain="test",
            owner=Owner(team="unit-test", contact="none"),
        ),
        data_schema=ImageSchema(
            spec=ImageSpec(
                encoding="jpg",
                width=100,
                height=100,
            )
        ),
        location=Location(storage="filesystem", path_template="/var/data/{YYYY}.jpg"),
    )


def test_image_entry_validation_instantiation(image_entry):
    """Test that SchemaValidator acts correctly with ImageEntry."""
    validator = SchemaValidator(image_entry)
    assert validator.entry.data_schema.format == SchemaFormat.IMAGE
    # We can't check validator.entry is ImageEntry easily if generic type used?
    # SchemaValidator takes DataEntry. ImageEntry is subclass.
    assert isinstance(validator.entry, ImageEntry)


@patch("PIL.Image.open")
def test_validate_image_success(mock_open, image_entry):
    """Test successful image validation."""
    # Mock image context manager
    mock_img = MagicMock()
    mock_img.size = (100, 100)
    mock_open.return_value.__enter__.return_value = mock_img

    validator = SchemaValidator(image_entry)

    # Test valid input (correct ext, mock logic checks resolution)
    data = ["/path/to/valid.jpg"]
    result = validator.validate(data)

    assert result.is_valid
    assert not result.errors


@patch("PIL.Image.open")
def test_validate_image_failure_resolution(mock_open, image_entry):
    """Test image validation failure (wrong resolution)."""
    mock_img = MagicMock()
    mock_img.size = (50, 50)  # Wrong size
    mock_open.return_value.__enter__.return_value = mock_img

    validator = SchemaValidator(image_entry)

    data = ["/path/to/wrong_res.jpg"]
    result = validator.validate(data)

    assert not result.is_valid
    assert "Resolution mismatch" in result.errors[0].message


def test_validate_image_failure_extension(image_entry):
    """Test image validation failure (wrong extension)."""
    validator = SchemaValidator(image_entry)

    data = ["/path/to/wrong.png"]  # Expecting .jpg
    result = validator.validate(data)

    assert not result.is_valid
    assert "Extension mismatch" in result.errors[0].message
