"""
Test: Analyze Consecutive Values in Delta Table

This test connects to tmp/data.lakehouse and analyzes the deltars.summary table
for consecutive runs in the 'time' column.
"""

import sys
from pathlib import Path

# Add parent directory to path to import duckrun
sys.path.insert(0, str(Path(__file__).parent.parent))

import duckrun
from duckrun.rle import analyze_consecutive_values


def test_consecutive_values():
    """Test consecutive value analysis on deltars.summary table"""
    
    lakehouse_path = "tmp/data.lakehouse"
    
    print("=" * 80)
    print("CONSECUTIVE VALUES ANALYSIS TEST")
    print("=" * 80)
    print(f"Lakehouse: {lakehouse_path}")
    print(f"Table: deltars.summary")
    print(f"Column: time")
    
    try:
        # Connect to lakehouse
        print("\nConnecting to lakehouse...")
        con = duckrun.connect(lakehouse_path)
        
        # Analyze consecutive values in the 'time' column
        print("\n" + "=" * 80)
        print("ANALYZING CONSECUTIVE VALUES")
        print("=" * 80)
        
        df = analyze_consecutive_values(
            duckrun_con=con,
            table_name='summary',
            column_name='time',
            min_consecutive=3,
            schema_name='deltars'
        )
        
        # Display results
        if not df.empty:
            print("\n" + "=" * 80)
            print("RESULTS")
            print("=" * 80)
            print(f"\nFound {len(df)} consecutive sequences")
            print("\nTop 20 longest sequences:")
            print(df.head(20).to_string(index=False))
            
            # Statistics
            print("\n" + "=" * 80)
            print("STATISTICS")
            print("=" * 80)
            total_in_sequences = df['consecutive_count'].sum()
            longest = df['consecutive_count'].max()
            shortest = df['consecutive_count'].min()
            avg = df['consecutive_count'].mean()
            
            print(f"Total values in sequences: {total_in_sequences:,}")
            print(f"Longest sequence: {longest:,}")
            print(f"Shortest sequence: {shortest:,}")
            print(f"Average sequence length: {avg:.2f}")
            
            # File distribution
            print("\n" + "=" * 80)
            print("FILE DISTRIBUTION")
            print("=" * 80)
            file_counts = df.groupby('filename').agg({
                'consecutive_count': ['count', 'sum', 'max']
            }).reset_index()
            file_counts.columns = ['filename', 'num_sequences', 'total_values', 'max_sequence']
            
            # Extract just filename from path
            file_counts['filename'] = file_counts['filename'].apply(
                lambda x: x.split('/')[-1] if '/' in str(x) else x
            )
            
            print(f"\nSequences across {len(file_counts)} files:")
            print(file_counts.to_string(index=False))
            
            print("\n✅ Test completed successfully!")
            return True
        else:
            print("\n⚠ No consecutive sequences found")
            return True
        
    except Exception as e:
        print(f"\n❌ Error during analysis: {e}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    print("\n" + "=" * 80)
    print("STARTING CONSECUTIVE VALUES TEST")
    print("=" * 80)
    
    success = test_consecutive_values()
    
    print("\n" + "=" * 80)
    if success:
        print("✅ TEST PASSED")
    else:
        print("❌ TEST FAILED")
    print("=" * 80)
    
    sys.exit(0 if success else 1)
