#!/usr/bin/env python3
"""
Test the new YouTube authentication system
"""

import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent / 'src'))

from cookie_manager import CookieManager, get_cookie_stats
from youtube_auth_handler import YouTubeAuthHandler, test_youtube_access

def main():
    print("🔍 Testing new YouTube authentication system")
    print("=" * 60)
    
    # Test cookie manager
    print("\n📄 Cookie Manager Status:")
    manager = CookieManager()
    
    valid_cookies = manager.find_valid_cookies()
    if valid_cookies:
        print(f"✅ Found valid cookies: {valid_cookies}")
    else:
        print("❌ No valid cookies found")
    
    # Get cookie statistics
    stats = get_cookie_stats()
    print(f"\nCookie Statistics:")
    print(f"  Valid files: {len(stats['valid_files'])}")
    print(f"  Invalid files: {len(stats['invalid_files'])}")
    print(f"  Total cookies: {stats['total_cookies']}")
    
    if stats['valid_files']:
        for file_info in stats['valid_files']:
            print(f"    {file_info['path']}: {file_info['cookie_count']} cookies, {file_info['size']} bytes")
    
    # Test authentication handler
    print("\n🔐 Authentication Handler:")
    handler = YouTubeAuthHandler()
    
    status = handler.get_status()
    print(f"  Authenticated: {status['authenticated']}")
    print(f"  Failure count: {status['failure_count']}")
    print(f"  In cooldown: {status['in_cooldown']}")
    print(f"  Has valid cookies: {status['has_valid_cookies']}")
    
    # Test authentication
    print("\n🧪 Testing YouTube access...")
    success = test_youtube_access()
    
    if success:
        print("✅ YouTube authentication working!")
    else:
        print("❌ YouTube authentication failed")
        
        # Try browser cookie extraction
        print("\n🌐 Attempting browser cookie extraction...")
        if handler.update_cookies_from_browser():
            print("✅ Browser cookies extracted - retesting...")
            success = test_youtube_access()
            if success:
                print("✅ Authentication now working with browser cookies!")
        
    # Final status
    print("\n📊 Final Status:")
    final_status = handler.get_status()
    for key, value in final_status.items():
        print(f"  {key}: {value}")

if __name__ == "__main__":
    main()