"""Tests for Auditor quality check integration."""

import polars as pl

from axm.catalog.entries.column import Column, ColumnRuleConfig, TabularSchema
from axm.catalog.rules.engine import RuleEngine
from axm_audit.auditor import Auditor


class TestAuditorQualityCheck:
    """Tests for Auditor.on_quality_check method."""

    def test_on_quality_check_records_report(self):
        """Quality check should record report in metrics."""
        auditor = Auditor()

        # Create a simple report
        schema = TabularSchema(
            columns=[
                Column(
                    name="age",
                    type="int",
                    rules=[ColumnRuleConfig(rule="range", min=0, max=120)],
                ),
            ]
        )
        df = pl.DataFrame({"age": [25, 30, 45]})
        engine = RuleEngine()
        report = engine.validate(df, schema)

        # Call on_quality_check
        auditor.on_quality_check(report, duration_ns=1_000_000)

        assert auditor.metrics.quality_checks == 1
        assert len(auditor.metrics.quality_reports) == 1
        assert auditor.metrics.quality_reports[0] == report

    def test_on_quality_check_counts_violations(self):
        """Should count total violations across all rules."""
        auditor = Auditor()

        schema = TabularSchema(
            columns=[
                Column(
                    name="age",
                    type="int",
                    rules=[ColumnRuleConfig(rule="range", min=0, max=120)],
                ),
            ]
        )
        df = pl.DataFrame({"age": [25, -5, 150]})  # 2 violations
        engine = RuleEngine()
        report = engine.validate(df, schema)

        auditor.on_quality_check(report, duration_ns=1_000_000)

        assert auditor.metrics.quality_violations == 1  # 1 failed rule

    def test_on_quality_check_accumulates(self):
        """Multiple quality checks should accumulate."""
        auditor = Auditor()

        schema = TabularSchema(
            columns=[
                Column(
                    name="value",
                    type="int",
                    rules=[ColumnRuleConfig(rule="range", min=0, max=100)],
                ),
            ]
        )
        engine = RuleEngine()

        # First check - pass
        df1 = pl.DataFrame({"value": [50, 60]})
        report1 = engine.validate(df1, schema)
        auditor.on_quality_check(report1, duration_ns=500_000)

        # Second check - fail
        df2 = pl.DataFrame({"value": [50, -10]})
        report2 = engine.validate(df2, schema)
        auditor.on_quality_check(report2, duration_ns=600_000)

        assert auditor.metrics.quality_checks == 2
        assert auditor.metrics.quality_violations == 1
        assert len(auditor.metrics.quality_reports) == 2
