#!/usr/bin/env python3
"""
Test script for Kiwy-Signage authentication with DigiServer v2
Run this to verify authentication is working before updating main.py
"""

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
import json

def load_app_config():
    """Load existing app_config.json"""
    # Try multiple possible locations
    possible_paths = [
        'config/app_config.json',
        'resources/app_config.txt',
        'src/config/app_config.json',
        '../config/app_config.json'
    ]
    
    for config_file in possible_paths:
        if os.path.exists(config_file):
            print(f"   Found config: {config_file}")
            with open(config_file, 'r') as f:
                return json.load(f)
    
    print(f"❌ Config file not found! Tried:")
    for path in possible_paths:
        print(f"   - {path}")
    return None

def test_authentication():
    """Test authentication with DigiServer v2"""
    print("=" * 60)
    print("Kiwy-Signage Authentication Test")
    print("=" * 60)
    print()
    
    # Load config
    print("📁 Loading configuration...")
    config = load_app_config()
    if not config:
        return False
    
    server_ip = config.get('server_ip', '')
    hostname = config.get('screen_name', '')
    quickconnect = config.get('quickconnect_key', '')
    port = config.get('port', '')
    
    print(f"   Server: {server_ip}:{port}")
    print(f"   Hostname: {hostname}")
    print(f"   Quick Connect: {'*' * len(quickconnect)}")
    print()
    
    # Build server URL
    import re
    ip_pattern = r'^\d+\.\d+\.\d+\.\d+$'
    if re.match(ip_pattern, server_ip):
        server_url = f'http://{server_ip}:{port}'
    else:
        server_url = f'http://{server_ip}'
    
    print(f"🌐 Server URL: {server_url}")
    print()
    
    # Test server connection
    print("🔌 Testing server connection...")
    try:
        import requests
        response = requests.get(f"{server_url}/api/health", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"   ✅ Server is healthy (version: {data.get('version')})")
        else:
            print(f"   ⚠️  Server responded with status: {response.status_code}")
    except Exception as e:
        print(f"   ❌ Cannot connect to server: {e}")
        print()
        print("💡 Make sure DigiServer v2 is running and accessible!")
        return False
    print()
    
    # Initialize auth
    print("🔐 Initializing authentication...")
    auth = PlayerAuth(config_file='src/player_auth.json')
    
    # Check if already authenticated
    if auth.is_authenticated():
        print(f"   ℹ️  Found existing authentication")
        print(f"   Player: {auth.get_player_name()}")
        print()
        
        print("✓ Verifying saved authentication...")
        valid, info = auth.verify_auth()
        
        if valid:
            print(f"   ✅ Authentication is valid!")
            print(f"   Player ID: {info['player_id']}")
            print(f"   Player Name: {info['player_name']}")
            print(f"   Group ID: {info.get('group_id', 'None')}")
            print(f"   Orientation: {info.get('orientation', 'Landscape')}")
            print()
            
            # Test playlist fetch
            print("📋 Testing playlist fetch...")
            playlist_data = auth.get_playlist()
            if playlist_data:
                version = playlist_data.get('playlist_version', 0)
                content_count = len(playlist_data.get('playlist', []))
                print(f"   ✅ Playlist received!")
                print(f"   Version: {version}")
                print(f"   Content items: {content_count}")
            else:
                print(f"   ⚠️  Could not fetch playlist")
            print()
            
            # Test heartbeat
            print("💓 Testing heartbeat...")
            if auth.send_heartbeat(status='online'):
                print(f"   ✅ Heartbeat sent successfully")
            else:
                print(f"   ⚠️  Heartbeat failed")
            print()
            
            print("=" * 60)
            print("✅ All tests passed! Player is ready to use.")
            print("=" * 60)
            return True
        else:
            print(f"   ❌ Saved authentication is expired or invalid")
            print(f"   Re-authenticating...")
            print()
    
    # Need to authenticate
    print("🔑 Authenticating with server...")
    success, error = auth.authenticate(
        server_url=server_url,
        hostname=hostname,
        quickconnect_code=quickconnect
    )
    
    if success:
        print(f"   ✅ Authentication successful!")
        print(f"   Player: {auth.get_player_name()}")
        print(f"   Player ID: {auth.get_player_id()}")
        print()
        
        # Save confirmation
        print(f"💾 Authentication saved to: src/player_auth.json")
        print()
        
        print("=" * 60)
        print("✅ Authentication successful! Player is ready to use.")
        print("=" * 60)
        return True
    else:
        print(f"   ❌ Authentication failed: {error}")
        print()
        print("💡 Troubleshooting:")
        print("   1. Check player exists in DigiServer v2 (hostname must match)")
        print("   2. Verify quickconnect_key matches server configuration")
        print("   3. Check server logs for authentication attempts")
        print()
        print("=" * 60)
        print("❌ Authentication test failed")
        print("=" * 60)
        return False

if __name__ == '__main__':
    try:
        success = test_authentication()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n⚠️  Test cancelled by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
