#!/usr/bin/env python3
"""
Test script for the watchlist & auto-download system
"""

import asyncio
import sys
from pathlib import Path

# Add project to path
sys.path.insert(0, str(Path(__file__).parent))

from app.watchlist import watchlist_manager
from app.episode_checker import episode_checker
from app.auto_download_scheduler import auto_download_scheduler
from app.models.watchlist import (
    WatchlistItemCreate,
    WatchlistStatus,
    QualityPreference
)


async def test_watchlist_manager():
    """Test basic watchlist operations"""
    print("\n" + "="*60)
    print("🧪 TEST 1: Watchlist Manager")
    print("="*60)

    # Test user ID
    test_user = "test_user_1"

    # Create a test item
    print("\n1. Creating watchlist item...")
    item_data = WatchlistItemCreate(
        anime_title="Test Anime",
        anime_url="https://anime-sama.si/catalogue/test/vostfr/",
        provider_id="animesama",
        lang="vostfr",
        auto_download=True,
        quality_preference=QualityPreference.AUTO
    )

    try:
        item = watchlist_manager.create(test_user, item_data)
        print(f"   ✅ Item created: {item.id}")
        print(f"   Title: {item.anime_title}")
        print(f"   Status: {item.status}")
    except Exception as e:
        print(f"   ❌ Create failed: {e}")
        import traceback
        traceback.print_exc()
        return False

    # Get all items
    print("\n2. Getting all items...")
    try:
        items = watchlist_manager.get_all(test_user)
        print(f"   ✅ Found {len(items)} items")
    except Exception as e:
        print(f"   ❌ Get all failed: {e}")
        return False

    # Get stats
    print("\n3. Getting statistics...")
    try:
        stats = watchlist_manager.get_stats(test_user)
        print(f"   ✅ Stats: {stats}")
    except Exception as e:
        print(f"   ❌ Stats failed: {e}")
        return False

    # Update item
    print("\n4. Updating item...")
    try:
        updated = watchlist_manager.update(item.id, {"status": WatchlistStatus.PAUSED})
        print(f"   ✅ Item updated to status: {updated.status}")
    except Exception as e:
        print(f"   ❌ Update failed: {e}")
        return False

    # Delete item
    print("\n5. Deleting item...")
    try:
        result = watchlist_manager.delete(item.id)
        print(f"   ✅ Item deleted: {result}")
    except Exception as e:
        print(f"   ❌ Delete failed: {e}")
        return False

    print("\n✅ Watchlist Manager tests PASSED")
    return True


async def test_episode_checker():
    """Test episode checker (without actual downloads)"""
    print("\n" + "="*60)
    print("🧪 TEST 2: Episode Checker")
    print("="*60)

    print("\n1. Testing EpisodeChecker initialization...")
    try:
        # Episode checker should be initialized
        print(f"   ✅ EpisodeChecker ready")
        print(f"   Note: Actual episode checking requires valid anime URLs")
    except Exception as e:
        print(f"   ❌ EpisodeChecker failed: {e}")
        return False

    print("\n✅ Episode Checker tests PASSED")
    return True


async def test_scheduler():
    """Test scheduler controls"""
    print("\n" + "="*60)
    print("🧪 TEST 3: Auto-Download Scheduler")
    print("="*60)

    print("\n1. Testing scheduler initialization...")
    try:
        # Get settings
        settings = watchlist_manager.get_settings()
        print(f"   ✅ Settings loaded: check_interval={settings.check_interval_hours}h")
    except Exception as e:
        print(f"   ❌ Settings failed: {e}")
        return False

    print("\n2. Testing scheduler status...")
    try:
        status = auto_download_scheduler.get_status()
        print(f"   ✅ Scheduler status: running={status['running']}")
    except Exception as e:
        print(f"   ❌ Status failed: {e}")
        return False

    print("\n3. Testing scheduler start/stop...")
    try:
        # Start scheduler
        await auto_download_scheduler.start()
        print("   ✅ Scheduler started")

        status = auto_download_scheduler.get_status()
        if not status['running']:
            print("   ❌ Scheduler not running after start")
            return False

        # Stop scheduler
        await auto_download_scheduler.stop()
        print("   ✅ Scheduler stopped")

        status = auto_download_scheduler.get_status()
        if status['running']:
            print("   ❌ Scheduler still running after stop")
            return False

    except Exception as e:
        print(f"   ❌ Start/stop failed: {e}")
        return False

    print("\n✅ Scheduler tests PASSED")
    return True


async def test_settings():
    """Test settings management"""
    print("\n" + "="*60)
    print("🧪 TEST 4: Settings Management")
    print("="*60)

    print("\n1. Testing settings update...")
    try:
        # Update settings
        new_settings = {
            "check_interval_hours": 12,
            "auto_download_enabled": True,
            "max_concurrent_auto_downloads": 3
        }
        watchlist_manager.update_settings(new_settings)
        print(f"   ✅ Settings updated")

        # Verify
        settings = watchlist_manager.get_settings()
        if settings.check_interval_hours != 12:
            print(f"   ❌ Settings not saved correctly")
            return False

        print(f"   ✅ Settings verified: check_interval={settings.check_interval_hours}h")

    except Exception as e:
        print(f"   ❌ Settings failed: {e}")
        import traceback
        traceback.print_exc()
        return False

    print("\n✅ Settings tests PASSED")
    return True


async def run_all_tests():
    """Run all tests"""
    print("\n" + "="*60)
    print("🚀 WATCHLIST SYSTEM TEST SUITE")
    print("="*60)

    tests = [
        ("Watchlist Manager", test_watchlist_manager),
        ("Episode Checker", test_episode_checker),
        ("Scheduler", test_scheduler),
        ("Settings", test_settings)
    ]

    results = []

    for name, test_func in tests:
        try:
            result = await test_func()
            results.append((name, result))
        except Exception as e:
            print(f"\n❌ {name} test crashed: {e}")
            import traceback
            traceback.print_exc()
            results.append((name, False))

    # Summary
    print("\n" + "="*60)
    print("📊 TEST SUMMARY")
    print("="*60)

    passed = sum(1 for _, result in results if result)
    total = len(results)

    for name, result in results:
        status = "✅ PASSED" if result else "❌ FAILED"
        print(f"{status}: {name}")

    print(f"\nTotal: {passed}/{total} tests passed")

    if passed == total:
        print("\n🎉 ALL TESTS PASSED! The watchlist system is ready to use.")
        return True
    else:
        print("\n⚠️  Some tests failed. Please review the errors above.")
        return False


if __name__ == "__main__":
    success = asyncio.run(run_all_tests())
    sys.exit(0 if success else 1)
