#!/usr/bin/env python3
"""Test audio/video sync integration."""

from providers.audio_sync import DurationReconciler, build_atempo_filter
from providers.export_utils import calculate_total_video_duration

def test_atempo_chaining():
    """Test production FFmpeg atempo filter chaining."""
    tests = [
        (1.0, False),  # No change - empty
        (0.8, False),  # Single filter
        (1.25, False), # Single filter
        (0.25, True),  # Chained - has comma
        (3.0, True),   # Chained - has comma
        (4.0, True),   # Chained - has comma
    ]
    
    for speed, should_be_chained in tests:
        result = build_atempo_filter(speed)
        is_chained = "," in result
        status = "chained" if is_chained else ("no-op" if result == "" else "single")
        expected_status = "chained" if should_be_chained else "single/no-op"
        assert is_chained == should_be_chained, f"Speed {speed}: expected {expected_status}, got {status}"
        print(f"✓ Speed {speed}x: {status} → {result}")

def test_duration_reconciler():
    """Test duration mismatch analysis."""
    # Within 5% tolerance (small mismatch)
    rec = DurationReconciler(10.0, 10.5)  # 4.7% difference - within tolerance
    assert not rec.get_mismatch().requires_adjustment
    print(f"✓ Within tolerance (10s audio, 10.5s video): no adjustment needed")
    
    # Outside tolerance (large mismatch)
    rec = DurationReconciler(10.0, 8.0)  # 20% difference - exceeds tolerance
    assert rec.get_mismatch().requires_adjustment
    assert rec.get_mismatch().strategy == "audio_adjust"
    audio_filters = rec.get_audio_filters()
    assert len(audio_filters) > 0
    summary = rec.summary()
    print(f"✓ Mismatch detected (10s audio, 8s video): {summary['strategy']} with factor {summary['adjustment_factor']:.3f}")

def test_video_duration_calculation():
    """Test video duration with transition overlap."""
    clips = [{"duration": 3.0}, {"duration": 4.0}, {"duration": 5.0}]
    transitions = [{"duration": 0.3}, {"duration": 0.3}]
    
    total = calculate_total_video_duration(clips, transitions)
    expected = 11.4
    assert abs(total - expected) < 0.01
    print(f"✓ Video duration: 3s + 4s + 5s - 0.3s - 0.3s = {total:.2f}s")

if __name__ == "__main__":
    print("Running audio/video sync tests...\n")
    test_atempo_chaining()
    test_duration_reconciler()
    test_video_duration_calculation()
    print("\n✅ All tests passed!")
