"""Test if create_ranking_targets is sensitive to sort order."""
import polars as pl
from crowdcent_challenge.scoring import create_ranking_targets


def main():
    # Create test data
    base_df = pl.DataFrame({
        "date": pl.date_range(pl.date(2024, 1, 1), pl.date(2024, 1, 10), eager=True),
        "ticker": ["BTC"] * 10,
        "close": [100.0, 110.0, 120.0, 115.0, 125.0, 130.0, 140.0, 135.0, 145.0, 150.0]
    })
    
    print("=" * 80)
    print("TEST: Does sort order affect the results?")
    print("=" * 80)
    
    # Test 1: Sorted by date ascending (natural order)
    df_asc = base_df.sort("date")
    result_asc = create_ranking_targets(df_asc, horizons=[2], return_raw_returns=True, drop_incomplete=False)
    
    # Test 2: Sorted by date descending
    df_desc = base_df.sort("date", descending=True)
    result_desc = create_ranking_targets(df_desc, horizons=[2], return_raw_returns=True, drop_incomplete=False)
    
    # Test 3: Random shuffle
    df_shuffled = base_df.sample(fraction=1.0, seed=42)
    result_shuffled = create_ranking_targets(df_shuffled, horizons=[2], return_raw_returns=True, drop_incomplete=False)
    
    print("\n1. Sorted ASCENDING by date:")
    print(result_asc.select(["date", "close", "fwd_return_2d"]))
    
    print("\n2. Sorted DESCENDING by date:")
    print(result_desc.select(["date", "close", "fwd_return_2d"]))
    
    print("\n3. SHUFFLED randomly:")
    print(result_shuffled.sort("date").select(["date", "close", "fwd_return_2d"]))
    
    # Compare results after sorting by date
    print("\n" + "-" * 80)
    print("COMPARISON (all sorted by date for comparison):")
    print("-" * 80)
    
    comparison = (
        result_asc.sort("date").select(["date", pl.col("fwd_return_2d").alias("asc")])
        .join(result_desc.sort("date").select(["date", pl.col("fwd_return_2d").alias("desc")]), on="date")
        .join(result_shuffled.sort("date").select(["date", pl.col("fwd_return_2d").alias("shuffled")]), on="date")
    )
    print(comparison)
    
    # Check if they're all the same
    print("\n" + "=" * 80)
    print("CONCLUSION")
    print("=" * 80)
    
    # Are asc and desc the same?
    asc_vals = result_asc.sort("date")["fwd_return_2d"].to_list()
    desc_vals = result_desc.sort("date")["fwd_return_2d"].to_list()
    shuffled_vals = result_shuffled.sort("date")["fwd_return_2d"].to_list()
    
    def vals_equal(a, b):
        for x, y in zip(a, b):
            if x is None and y is None:
                continue
            if x is None or y is None:
                return False
            if abs(x - y) > 1e-10:
                return False
        return True
    
    print(f"\nAscending == Descending: {vals_equal(asc_vals, desc_vals)}")
    print(f"Ascending == Shuffled: {vals_equal(asc_vals, shuffled_vals)}")
    
    if not vals_equal(asc_vals, desc_vals):
        print("\nThe results DIFFER based on sort order!")
        print("This means the function is NOT robust to input order.")


if __name__ == "__main__":
    main()
