#!/usr/bin/env python3
"""
Diagnostic script to check why media files might be skipped
"""
import os
import json

# Paths
base_dir = os.path.dirname(os.path.abspath(__file__))
media_dir = os.path.join(base_dir, 'media')
playlists_dir = os.path.join(base_dir, 'playlists')

# Supported extensions
VIDEO_EXTENSIONS = ['.mp4', '.avi', '.mkv', '.mov', '.webm']
IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']
SUPPORTED_EXTENSIONS = VIDEO_EXTENSIONS + IMAGE_EXTENSIONS

def check_playlist():
    """Check playlist for issues"""
    print("=" * 80)
    print("PLAYLIST DIAGNOSTIC TOOL")
    print("=" * 80)
    
    # Find latest playlist file
    playlist_files = [f for f in os.listdir(playlists_dir) 
                     if f.startswith('server_playlist_v') and f.endswith('.json')]
    
    if not playlist_files:
        print("\n❌ ERROR: No playlist files found!")
        return
    
    # Sort by version and get latest
    versions = [(int(f.split('_v')[-1].split('.json')[0]), f) for f in playlist_files]
    versions.sort(reverse=True)
    latest_file = versions[0][1]
    playlist_path = os.path.join(playlists_dir, latest_file)
    
    print(f"\n📋 Latest Playlist: {latest_file}")
    print(f"   Path: {playlist_path}")
    
    # Load playlist
    try:
        with open(playlist_path, 'r') as f:
            data = json.load(f)
        
        playlist = data.get('playlist', [])
        version = data.get('version', 0)
        
        print(f"   Version: {version}")
        print(f"   Total items: {len(playlist)}")
        
    except Exception as e:
        print(f"\n❌ ERROR loading playlist: {e}")
        return
    
    # Check media directory
    print(f"\n📁 Media Directory: {media_dir}")
    if not os.path.exists(media_dir):
        print("   ❌ ERROR: Media directory doesn't exist!")
        return
    
    media_files = os.listdir(media_dir)
    print(f"   Files found: {len(media_files)}")
    for f in media_files:
        print(f"   - {f}")
    
    # Check each playlist item
    print("\n" + "=" * 80)
    print("CHECKING PLAYLIST ITEMS")
    print("=" * 80)
    
    valid_count = 0
    missing_count = 0
    unsupported_count = 0
    
    for idx, item in enumerate(playlist, 1):
        file_name = item.get('file_name', '')
        duration = item.get('duration', 0)
        media_path = os.path.join(media_dir, file_name)
        file_ext = os.path.splitext(file_name)[1].lower()
        
        print(f"\n[{idx}/{len(playlist)}] {file_name}")
        print(f"    Duration: {duration}s")
        
        # Check if file exists
        if not os.path.exists(media_path):
            print(f"    ❌ STATUS: FILE NOT FOUND")
            print(f"    Expected path: {media_path}")
            missing_count += 1
            continue
        
        # Check file size
        file_size = os.path.getsize(media_path)
        print(f"    ✓ File exists ({file_size:,} bytes)")
        
        # Check if supported type
        if file_ext not in SUPPORTED_EXTENSIONS:
            print(f"    ❌ STATUS: UNSUPPORTED FILE TYPE '{file_ext}'")
            print(f"    Supported extensions: {', '.join(SUPPORTED_EXTENSIONS)}")
            unsupported_count += 1
            continue
        
        # Check media type
        if file_ext in VIDEO_EXTENSIONS:
            media_type = "VIDEO"
        elif file_ext in IMAGE_EXTENSIONS:
            media_type = "IMAGE"
        else:
            media_type = "UNKNOWN"
        
        print(f"    ✓ Type: {media_type}")
        print(f"    ✓ Extension: {file_ext}")
        print(f"    ✓ STATUS: SHOULD PLAY OK")
        valid_count += 1
    
    # Summary
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"Total items:      {len(playlist)}")
    print(f"✓ Valid:          {valid_count}")
    print(f"❌ Missing files: {missing_count}")
    print(f"❌ Unsupported:   {unsupported_count}")
    
    if valid_count == len(playlist):
        print("\n✅ All playlist items should play correctly!")
    else:
        print(f"\n⚠️  WARNING: {len(playlist) - valid_count} items may be skipped!")
    
    # Additional checks
    print("\n" + "=" * 80)
    print("ADDITIONAL CHECKS")
    print("=" * 80)
    
    # Check for files in media dir not in playlist
    playlist_files_set = {item.get('file_name', '') for item in playlist}
    orphaned_files = [f for f in media_files if f not in playlist_files_set]
    
    if orphaned_files:
        print(f"\n⚠️  Files in media directory NOT in playlist:")
        for f in orphaned_files:
            print(f"   - {f}")
    else:
        print("\n✓ All media files are in the playlist")
    
    # Check for case sensitivity issues
    print("\n🔍 Checking for case sensitivity issues...")
    media_files_lower = {f.lower(): f for f in media_files}
    case_issues = []
    
    for item in playlist:
        file_name = item.get('file_name', '')
        if file_name.lower() in media_files_lower:
            actual_name = media_files_lower[file_name.lower()]
            if actual_name != file_name:
                case_issues.append((file_name, actual_name))
    
    if case_issues:
        print("⚠️  Case sensitivity mismatches found:")
        for playlist_name, actual_name in case_issues:
            print(f"   Playlist: {playlist_name}")
            print(f"   Actual:   {actual_name}")
    else:
        print("✓ No case sensitivity issues found")

if __name__ == '__main__':
    check_playlist()
