"""Tests for Parquet trade-ID continuity validation (D-07)."""

from __future__ import annotations

import polars as pl
import pytest

from opendeviationbar.storage.parquet_io import validate_trade_id_continuity


def _make_df(agg_trade_ids: list[int]) -> pl.DataFrame:
    """Build a minimal DataFrame with the given agg_trade_ids."""
    n = len(agg_trade_ids)
    return pl.DataFrame(
        {
            "agg_trade_id": agg_trade_ids,
            "price": [100.0] * n,
            "quantity": [1.0] * n,
            "timestamp": [1700000000000 + i for i in range(n)],
            "is_buyer_maker": [True] * n,
            "first_trade_id": agg_trade_ids,
            "last_trade_id": agg_trade_ids,
        }
    )


class TestValidateTradeIdContinuity:
    """Tests for validate_trade_id_continuity()."""

    def test_consecutive_ids_returns_true(self) -> None:
        """Test 1: Consecutive agg_trade_ids [100..103] → True."""
        df = _make_df([100, 101, 102, 103])
        assert validate_trade_id_continuity(df) is True

    def test_gap_returns_false(self) -> None:
        """Test 2: Gap [100, 101, 103, 104] (missing 102) → False."""
        df = _make_df([100, 101, 103, 104])
        assert validate_trade_id_continuity(df) is False

    def test_duplicate_returns_false(self) -> None:
        """Test 3: Duplicate [100, 101, 101, 102] → False."""
        df = _make_df([100, 101, 101, 102])
        assert validate_trade_id_continuity(df) is False

    def test_single_row_returns_true(self) -> None:
        """Test 4: Single-row df → True (trivially valid)."""
        df = _make_df([42])
        assert validate_trade_id_continuity(df) is True

    def test_empty_df_returns_true(self) -> None:
        """Test 5: Empty df → True (trivially valid)."""
        df = pl.DataFrame(
            {
                "agg_trade_id": pl.Series([], dtype=pl.Int64),
                "price": pl.Series([], dtype=pl.Float64),
            }
        )
        assert validate_trade_id_continuity(df) is True

    def test_unsorted_input_returns_true(self) -> None:
        """Test 6: Unsorted input [103, 100, 102, 101] → True (sorts before checking)."""
        df = _make_df([103, 100, 102, 101])
        assert validate_trade_id_continuity(df) is True

    def test_no_agg_trade_id_column_returns_true(self) -> None:
        """Edge case: No agg_trade_id column → True (cannot validate)."""
        df = pl.DataFrame({"price": [1.0, 2.0], "quantity": [1.0, 1.0]})
        assert validate_trade_id_continuity(df) is True
