"""
Test script for Phase 6 task queue and scheduler implementation.

This script tests the sequential execution of tasks and verifies that
the task queue and scheduler are working correctly.
"""

import time
import sys
import os

# Add the current directory to Python path to import core modules
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from core.config import get_config
from core.logger import setup_logging
from core.task_queue import start_task_queue, stop_task_queue, enqueue_task, get_queue_status
from core.scheduler import start_scheduler, stop_scheduler, get_scheduler_status
from core.tasks import create_custom_task


def test_task_queue():
    """Test the task queue functionality."""
    print("Testing task queue...")
    
    # Start task queue
    if not start_task_queue():
        print("✗ Failed to start task queue")
        return False
    
    print("✓ Task queue started")
    
    # Create test tasks
    def test_task_1():
        print("  Executing test task 1...")
        time.sleep(1)
        print("  Test task 1 completed")
        return "Task 1 result"
    
    def test_task_2():
        print("  Executing test task 2...")
        time.sleep(1)
        print("  Test task 2 completed")
        return "Task 2 result"
    
    def test_task_3():
        print("  Executing test task 3...")
        time.sleep(1)
        print("  Test task 3 completed")
        return "Task 3 result"
    
    # Enqueue tasks
    task1 = create_custom_task("TestTask1", test_task_1, "First test task")
    task2 = create_custom_task("TestTask2", test_task_2, "Second test task")
    task3 = create_custom_task("TestTask3", test_task_3, "Third test task")
    
    if enqueue_task(task1):
        print("✓ Task 1 enqueued")
    else:
        print("✗ Failed to enqueue task 1")
        return False
    
    if enqueue_task(task2):
        print("✓ Task 2 enqueued")
    else:
        print("✗ Failed to enqueue task 2")
        return False
    
    if enqueue_task(task3):
        print("✓ Task 3 enqueued")
    else:
        print("✗ Failed to enqueue task 3")
        return False
    
    # Wait for tasks to complete
    print("Waiting for tasks to complete...")
    time.sleep(5)
    
    # Check queue status
    status = get_queue_status()
    print(f"Queue status: {status}")
    
    if status["statistics"]["total_completed"] == 3:
        print("✓ All tasks completed successfully")
    else:
        print(f"✗ Expected 3 completed tasks, got {status['statistics']['total_completed']}")
        return False
    
    # Stop task queue
    if not stop_task_queue():
        print("✗ Failed to stop task queue")
        return False
    
    print("✓ Task queue stopped")
    return True


def test_scheduler():
    """Test the scheduler functionality."""
    print("Testing scheduler...")
    
    # Start scheduler
    if not start_scheduler():
        print("✗ Failed to start scheduler")
        return False
    
    print("✓ Scheduler started")
    
    # Check scheduler status
    status = get_scheduler_status()
    print(f"Scheduler status: {status}")
    
    if status["running"]:
        print("✓ Scheduler is running")
    else:
        print("✗ Scheduler is not running")
        return False
    
    # Stop scheduler
    if not stop_scheduler():
        print("✗ Failed to stop scheduler")
        return False
    
    print("✓ Scheduler stopped")
    return True


def main():
    """Main test function."""
    print("Starting Phase 6 tests...")
    print("=" * 50)
    
    # Initialize configuration and logging
    config = get_config()
    setup_logging()
    
    # Test task queue
    if not test_task_queue():
        print("✗ Task queue test failed")
        return 1
    
    print()
    
    # Test scheduler
    if not test_scheduler():
        print("✗ Scheduler test failed")
        return 1
    
    print()
    print("=" * 50)
    print("✓ All Phase 6 tests passed!")
    print("✓ Task queue processes tasks sequentially")
    print("✓ Scheduler starts and stops correctly")
    print("✓ Queue status reporting works")
    print("✓ Error handling is working")
    
    return 0


if __name__ == "__main__":
    sys.exit(main())