#!/usr/bin/env python3
"""
测试 Celery Channel Job Mode 超时功能

这个脚本测试 CeleryChannel 的 job_mode_timeout 功能是否正常工作。
"""

import sys
import time
from pathlib import Path
from unittest.mock import Mock, patch

# 添加 sandai 包到路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from sandai.operator.channel import CeleryChannel
from sandai.operator.types import EOFMarker


def test_job_mode_timeout_configuration():
    """测试 job mode 超时配置"""
    print("Testing job mode timeout configuration...")
    
    # 模拟 Celery 应用
    mock_celery_app = Mock()
    mock_celery_app.conf = Mock()
    
    # 测试默认超时
    channel = CeleryChannel(
        celery_app=mock_celery_app,
        job_mode=True,
        debug=True
    )
    assert channel.job_mode_timeout == 30, f"Expected default timeout 30, got {channel.job_mode_timeout}"
    channel.close()
    
    # 测试自定义超时
    channel = CeleryChannel(
        celery_app=mock_celery_app,
        job_mode=True,
        job_mode_timeout=60,
        debug=True
    )
    assert channel.job_mode_timeout == 60, f"Expected custom timeout 60, got {channel.job_mode_timeout}"
    channel.close()

    print("✓ Job mode timeout configuration test passed")


def test_eof_marker_creation():
    """测试 EOF 标记创建"""
    print("Testing EOF marker creation...")
    
    eof_marker = EOFMarker()
    eof_dict = eof_marker.model_dump()
    
    assert eof_dict['marker_type'] == 'eof', f"Expected marker_type 'eof', got {eof_dict['marker_type']}"
    assert 'message' in eof_dict, "EOF marker should have 'message' field"
    
    print("✓ EOF marker creation test passed")


def test_timeout_logic():
    """测试超时逻辑（模拟）"""
    print("Testing timeout logic...")
    
    # 模拟时间流逝
    current_time = time.time()
    last_task_time = current_time - 35  # 35秒前
    timeout = 30
    
    # 检查是否超时
    is_timeout = (current_time - last_task_time) > timeout
    assert is_timeout, "Should detect timeout when 35s > 30s"
    
    # 测试未超时情况
    last_task_time = current_time - 25  # 25秒前
    is_timeout = (current_time - last_task_time) > timeout
    assert not is_timeout, "Should not detect timeout when 25s < 30s"
    
    print("✓ Timeout logic test passed")


def main():
    """主函数"""
    print("Celery Channel Job Mode Timeout Test")
    print("=" * 50)
    
    try:
        test_job_mode_timeout_configuration()
        test_eof_marker_creation()
        test_timeout_logic()
        
        print("\n✅ All job mode timeout tests passed!")
        print("\nNote: These are unit tests for the timeout logic.")
        print("To test the full functionality:")
        print("1. Start Redis server")
        print("2. Run: python examples/celery_job_mode_example.py")
        print("3. Send tasks: python examples/celery_job_mode_sender.py")
        print("4. Wait 15+ seconds to see automatic exit")
        
    except Exception as e:
        print(f"\n❌ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return 1
    
    return 0


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