#!/usr/bin/env python3
"""Test server connection and playlist fetch."""

import json
import sys
import os

# Add src directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from player_auth import PlayerAuth

# Load config
config_file = 'config/app_config.json'
with open(config_file, 'r') as f:
    config = json.load(f)

print("=" * 80)
print("SERVER CONNECTION TEST")
print("=" * 80)

server_ip = config.get("server_ip", "")
screen_name = config.get("screen_name", "")
quickconnect_key = config.get("quickconnect_key", "")
port = config.get("port", "")

print(f"\nConfiguration:")
print(f"  Server: {server_ip}")
print(f"  Port: {port}")
print(f"  Screen Name: {screen_name}")
print(f"  QuickConnect: {quickconnect_key}")

# Build server URL
if server_ip.startswith('http://') or server_ip.startswith('https://'):
    server_url = server_ip
    # If it has https but port 443 is specified, ensure port is included if non-standard
    if not ':' in server_ip.replace('https://', '').replace('http://', ''):
        if port and port != '443' and port != '80':
            server_url = f"{server_ip}:{port}"
else:
    # Use https for port 443, http for others
    protocol = "https" if port == "443" else "http"
    server_url = f"{protocol}://{server_ip}:{port}"

print(f"\nServer URL: {server_url}")

# Test authentication
print("\n" + "=" * 80)
print("1. TESTING AUTHENTICATION")
print("=" * 80)

auth = PlayerAuth('src/player_auth.json')

# Check if already authenticated
if auth.is_authenticated():
    print("✓ Found existing authentication")
    valid, message = auth.verify_auth()
    if valid:
        print(f"✓ Auth is valid: {message}")
    else:
        print(f"✗ Auth expired: {message}")
        print("\nRe-authenticating...")
        success, error = auth.authenticate(
            server_url=server_url,
            hostname=screen_name,
            quickconnect_code=quickconnect_key
        )
        if success:
            print(f"✓ Re-authentication successful!")
        else:
            print(f"✗ Re-authentication failed: {error}")
            sys.exit(1)
else:
    print("No existing authentication found. Authenticating...")
    success, error = auth.authenticate(
        server_url=server_url,
        hostname=screen_name,
        quickconnect_code=quickconnect_key
    )
    if success:
        print(f"✓ Authentication successful!")
    else:
        print(f"✗ Authentication failed: {error}")
        sys.exit(1)

# Test playlist fetch
print("\n" + "=" * 80)
print("2. TESTING PLAYLIST FETCH")
print("=" * 80)

playlist_data = auth.get_playlist()

if playlist_data:
    print(f"✓ Playlist fetched successfully!")
    print(f"\nPlaylist Version: {playlist_data.get('playlist_version', 'N/A')}")
    print(f"Number of items: {len(playlist_data.get('playlist', []))}")
    
    print("\n" + "-" * 80)
    print("PLAYLIST ITEMS:")
    print("-" * 80)
    
    for idx, item in enumerate(playlist_data.get('playlist', []), 1):
        print(f"\n{idx}. File: {item.get('file_name', 'N/A')}")
        print(f"   URL: {item.get('url', 'N/A')}")
        print(f"   Duration: {item.get('duration', 'N/A')}s")
        
        # Check if URL is relative or absolute
        url = item.get('url', '')
        if url.startswith('http://') or url.startswith('https://'):
            print(f"   Type: Absolute URL")
        else:
            print(f"   Type: Relative path (will fail to download!)")
    
    # Save full response
    with open('server_response_debug.json', 'w') as f:
        json.dump(playlist_data, f, indent=2)
    print(f"\n✓ Full response saved to: server_response_debug.json")
    
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"Server has: {len(playlist_data.get('playlist', []))} files")
    print(f"Local has: 3 files (from playlists/server_playlist_v8.json)")
    
    if len(playlist_data.get('playlist', [])) > 3:
        print(f"\n⚠️  PROBLEM: Server has {len(playlist_data.get('playlist', []))} files but only 3 were saved!")
        print("\nMissing files are likely:")
        local_files = ['music.jpg', '130414-746934884.mp4', 'IMG_0386.jpeg']
        server_files = [item.get('file_name', '') for item in playlist_data.get('playlist', [])]
        missing = [f for f in server_files if f not in local_files]
        for f in missing:
            print(f"  - {f}")
    
else:
    print("✗ Failed to fetch playlist")
    sys.exit(1)

print("\n" + "=" * 80)
