"""Tests for Validator rule integration — RED phase."""

import polars as pl
import pytest

from axm.catalog.entries import (
    Identity,
    Location,
    Owner,
)
from axm.catalog.rules.common import is_positive, not_empty
from axm.catalog.rules.registry import RuleRegistry
from axm.catalog.validation import SchemaValidator
from axm_tabular.entries.tabular import TabularEntry, TabularSchema, TabularSpec


@pytest.fixture(autouse=True)
def setup_registry():
    """Register standard rules for testing."""
    RuleRegistry.reset()
    RuleRegistry.register(not_empty)
    RuleRegistry.register(is_positive)


class TestValidatorRules:
    """Tests for rule application in SchemaValidator."""

    def test_validate_with_rules(self) -> None:
        """Should apply column-level validation rules."""
        entry = TabularEntry(
            name="rules_test",
            version="1.0",
            identity=Identity(
                display_name="T",
                description="d",
                domain="d",
                owner=Owner(team="t", contact="c"),
            ),
            data_schema=TabularSchema(
                spec=TabularSpec(
                    columns=[
                        {"name": "id", "type": "int64", "rules": ["is_positive"]},
                        {"name": "name", "type": "string", "rules": ["not_empty"]},
                    ]
                )
            ),
            location=Location(storage="fs", path_template="/"),
        )
        validator = SchemaValidator(entry)

        # Valid data
        valid_df = pl.DataFrame(
            {"id": [1, 2], "name": ["alice", "bob"]},
            schema={"id": pl.Int64, "name": pl.String},
        )

        assert validator.validate(valid_df).is_valid

        # Invalid data (id=0 fails is_positive, name="" fails not_empty)
        invalid_df = pl.DataFrame(
            {"id": [0, -1], "name": ["", "charlie"]},
            schema={"id": pl.Int64, "name": pl.String},
        )

        result = validator.validate(invalid_df)
        assert not result.is_valid

        errors = [e.message for e in result.errors]
        assert any("Rule 'is_positive' failed" in e for e in errors)
        assert any("Rule 'not_empty' failed" in e for e in errors)
