#!/usr/bin/env python3
"""
Unit Tests for BotLifecycleManager

Tests lifecycle management features:
- Inactivity timeout monitoring
- Signal handling (SIGTERM, SIGINT)
- Retry logic with exponential backoff
- Termination notifications
- Resource cleanup coordination

Task #116 - Stream B: Bot Lifecycle Manager
"""

import asyncio
import signal
import time
import pytest
from unittest.mock import AsyncMock, Mock, patch, call
from pathlib import Path
import sys

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))
from lifecycle_manager import BotLifecycleManager, retry_with_backoff


class MockBot:
    """Mock bot for testing lifecycle manager"""

    def __init__(self):
        self.start_called = False
        self.stop_called = False
        self.start_count = 0
        self.stop_count = 0
        self.start_side_effect = None
        self.stop_side_effect = None

    async def start(self):
        """Mock start method"""
        self.start_called = True
        self.start_count += 1
        if self.start_side_effect:
            raise self.start_side_effect

    async def stop(self):
        """Mock stop method"""
        self.stop_called = True
        self.stop_count += 1
        if self.stop_side_effect:
            raise self.stop_side_effect


class TestRetryWithBackoff:
    """Test suite for retry_with_backoff utility function"""

    @pytest.mark.asyncio
    async def test_success_on_first_attempt(self):
        """Test that function succeeds on first attempt"""
        call_count = 0

        async def successful_func():
            nonlocal call_count
            call_count += 1
            return "success"

        result = await retry_with_backoff(successful_func, max_attempts=3)

        assert result == "success"
        assert call_count == 1

    @pytest.mark.asyncio
    async def test_success_on_second_attempt(self):
        """Test that function succeeds on second attempt after one failure"""
        call_count = 0

        async def flaky_func():
            nonlocal call_count
            call_count += 1
            if call_count == 1:
                raise Exception("First attempt fails")
            return "success"

        start_time = time.time()
        result = await retry_with_backoff(flaky_func, max_attempts=3)
        elapsed = time.time() - start_time

        assert result == "success"
        assert call_count == 2
        # Should have waited ~1 second between attempts
        assert 0.9 < elapsed < 1.5

    @pytest.mark.asyncio
    async def test_success_on_third_attempt(self):
        """Test that function succeeds on third attempt after two failures"""
        call_count = 0

        async def very_flaky_func():
            nonlocal call_count
            call_count += 1
            if call_count < 3:
                raise Exception(f"Attempt {call_count} fails")
            return "success"

        start_time = time.time()
        result = await retry_with_backoff(very_flaky_func, max_attempts=3)
        elapsed = time.time() - start_time

        assert result == "success"
        assert call_count == 3
        # Should have waited 1s + 2s = 3 seconds total
        assert 2.8 < elapsed < 3.5

    @pytest.mark.asyncio
    async def test_all_attempts_fail(self):
        """Test that exception is raised after all attempts fail"""
        call_count = 0

        async def always_fails():
            nonlocal call_count
            call_count += 1
            raise ValueError(f"Attempt {call_count} failed")

        with pytest.raises(ValueError, match="Attempt 3 failed"):
            await retry_with_backoff(always_fails, max_attempts=3)

        assert call_count == 3

    @pytest.mark.asyncio
    async def test_exponential_backoff_timing(self):
        """Test that backoff timing follows exponential pattern (1s, 2s, 4s)"""
        call_times = []

        async def failing_func():
            call_times.append(time.time())
            raise Exception("Always fails")

        try:
            await retry_with_backoff(failing_func, max_attempts=3)
        except Exception:
            pass

        # Check that we have 3 call times
        assert len(call_times) == 3

        # Check delay between attempts
        delay1 = call_times[1] - call_times[0]  # Should be ~1s
        delay2 = call_times[2] - call_times[1]  # Should be ~2s

        assert 0.9 < delay1 < 1.5, f"First delay was {delay1}s, expected ~1s"
        assert 1.8 < delay2 < 2.5, f"Second delay was {delay2}s, expected ~2s"

    @pytest.mark.asyncio
    async def test_custom_operation_name_in_logs(self, caplog):
        """Test that custom operation name appears in logs"""
        import logging
        caplog.set_level(logging.INFO)

        async def test_func():
            return "ok"

        await retry_with_backoff(
            test_func,
            max_attempts=1,
            operation_name="custom_operation"
        )

        assert "custom_operation" in caplog.text


class TestBotLifecycleManager:
    """Test suite for BotLifecycleManager class"""

    @pytest.mark.asyncio
    async def test_initialization(self):
        """Test that lifecycle manager initializes correctly"""
        bot = MockBot()
        manager = BotLifecycleManager(bot, timeout_minutes=30)

        assert manager.bot == bot
        assert manager.timeout_minutes == 30
        assert manager.is_running is False
        assert manager.termination_reason is None

    @pytest.mark.asyncio
    async def test_start_calls_bot_start(self):
        """Test that start() calls bot.start()"""
        bot = MockBot()
        manager = BotLifecycleManager(bot, timeout_minutes=30)

        # Start in background and stop immediately for testing
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)  # Let start() begin
        await manager.terminate("test")
        await start_task

        assert bot.start_called is True
        assert manager.is_running is False

    @pytest.mark.asyncio
    async def test_inactivity_timeout_short(self):
        """Test that inactivity timeout triggers termination (short timeout for testing)"""
        bot = MockBot()
        # Set very short timeout (1 second) and check interval (0.5 seconds) for testing
        manager = BotLifecycleManager(
            bot,
            timeout_minutes=1/60,  # 1 second as fraction of minute
            check_interval_seconds=1
        )

        # Start manager (don't await - it will run until timeout)
        start_task = asyncio.create_task(manager.start())

        # Wait for timeout (1 second) + check interval (1 second) + buffer
        await asyncio.sleep(2.5)

        # Should have terminated due to inactivity
        assert manager.is_running is False
        assert manager.termination_reason == "inactivity_timeout"
        assert bot.stop_called is True

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_update_activity_prevents_timeout(self):
        """Test that updating activity prevents timeout"""
        bot = MockBot()
        manager = BotLifecycleManager(
            bot,
            timeout_minutes=2/60,  # 2 seconds
            check_interval_seconds=1
        )

        # Start manager
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)

        # Update activity every second to prevent timeout
        for i in range(3):
            await asyncio.sleep(1)
            manager.update_activity()

        # Should still be running after 3 seconds (timeout is 2 seconds but we updated activity)
        assert manager.is_running is True

        # Cleanup
        await manager.terminate("test")
        await start_task

    @pytest.mark.asyncio
    async def test_get_inactive_time(self):
        """Test get_inactive_time_seconds returns correct value"""
        bot = MockBot()
        manager = BotLifecycleManager(bot)

        # Set last activity to 2 seconds ago
        manager.last_activity = time.time() - 2.0

        inactive_time = manager.get_inactive_time_seconds()

        # Should be approximately 2 seconds
        assert 1.9 < inactive_time < 2.2

    @pytest.mark.asyncio
    async def test_signal_handler_sigterm(self):
        """Test that SIGTERM signal triggers graceful termination"""
        bot = MockBot()
        manager = BotLifecycleManager(bot, timeout_minutes=30)

        # Start manager
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.2)  # Let it start

        # Simulate SIGTERM signal
        manager._handle_signal(signal.SIGTERM, None)

        # Give it time to process signal
        await asyncio.sleep(0.2)

        # Should have terminated
        assert manager.is_running is False
        assert bot.stop_called is True
        assert "sigterm" in manager.termination_reason.lower()

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_signal_handler_sigint(self):
        """Test that SIGINT signal triggers graceful termination"""
        bot = MockBot()
        manager = BotLifecycleManager(bot, timeout_minutes=30)

        # Start manager
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.2)

        # Simulate SIGINT signal
        manager._handle_signal(signal.SIGINT, None)
        await asyncio.sleep(0.2)

        # Should have terminated
        assert manager.is_running is False
        assert bot.stop_called is True
        assert "sigint" in manager.termination_reason.lower()

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_terminate_called_multiple_times(self):
        """Test that calling terminate() multiple times is safe"""
        bot = MockBot()
        manager = BotLifecycleManager(bot)

        # Start manager
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)

        # Call terminate multiple times
        await manager.terminate("first")
        await manager.terminate("second")
        await manager.terminate("third")

        # Bot stop should only be called once
        assert bot.stop_count == 1
        assert manager.termination_reason == "first"  # First reason wins

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_termination_notification_logged(self, caplog):
        """Test that termination notification is logged"""
        import logging
        caplog.set_level(logging.INFO)

        bot = MockBot()
        manager = BotLifecycleManager(bot)

        # Start and terminate
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)
        await manager.terminate("test_reason")

        # Check logs
        assert "TERMINATING BOT" in caplog.text
        assert "test_reason" in caplog.text
        assert "TERMINATION NOTIFICATION" in caplog.text

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_bot_stop_error_handled_gracefully(self, caplog):
        """Test that errors in bot.stop() are handled gracefully"""
        bot = MockBot()
        bot.stop_side_effect = Exception("Stop failed")
        manager = BotLifecycleManager(bot)

        # Start and terminate
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)

        # This should not raise even though bot.stop() fails
        await manager.terminate("test")

        # Should have logged the error
        assert "Error during termination" in caplog.text or "Stop failed" in caplog.text

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_inactivity_monitor_cancellation(self):
        """Test that inactivity monitor task is cancelled on termination"""
        bot = MockBot()
        manager = BotLifecycleManager(bot)

        # Start manager
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)

        # Monitor should be running
        assert manager._inactivity_task is not None
        assert not manager._inactivity_task.done()

        # Terminate
        await manager.terminate("test")

        # Monitor should be cancelled
        assert manager._inactivity_task.done()

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_get_runtime_seconds(self):
        """Test get_runtime_seconds returns reasonable value"""
        bot = MockBot()
        manager = BotLifecycleManager(bot)

        # Start manager
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)

        # Wait a bit
        await asyncio.sleep(1)

        runtime = manager.get_runtime_seconds()

        # Should be approximately 1 second (but implementation uses time since initialization)
        # The actual value will be larger since last_activity is set before sleeping
        # Let's just check it's positive and reasonable
        assert runtime > 1.0, f"Runtime should be > 1s, got {runtime}"
        assert runtime < 5.0, f"Runtime should be < 5s, got {runtime}"

        # Cleanup
        await manager.terminate("test")
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_signal_handlers_restored(self):
        """Test that original signal handlers are restored after termination"""
        bot = MockBot()
        manager = BotLifecycleManager(bot)

        # Store original handlers
        original_sigterm = signal.signal(signal.SIGTERM, signal.SIG_DFL)
        original_sigint = signal.signal(signal.SIGINT, signal.SIG_DFL)

        # Restore them
        signal.signal(signal.SIGTERM, original_sigterm)
        signal.signal(signal.SIGINT, original_sigint)

        # Start manager (registers handlers)
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)

        # Handlers should be changed
        current_sigterm = signal.getsignal(signal.SIGTERM)
        assert current_sigterm != original_sigterm

        # Terminate (should restore handlers)
        await manager.terminate("test")

        # Handlers should be restored
        restored_sigterm = signal.getsignal(signal.SIGTERM)
        assert restored_sigterm == original_sigterm

        # Cleanup
        try:
            await start_task
        except:
            pass


class TestBotLifecycleIntegration:
    """Integration tests for lifecycle manager"""

    @pytest.mark.asyncio
    async def test_complete_lifecycle(self):
        """Test complete lifecycle: start -> run -> terminate"""
        bot = MockBot()
        manager = BotLifecycleManager(bot, timeout_minutes=30)

        # Start
        start_task = asyncio.create_task(manager.start())
        await asyncio.sleep(0.1)

        # Should be running
        assert manager.is_running is True
        assert bot.start_called is True

        # Update activity
        manager.update_activity()
        await asyncio.sleep(0.1)

        # Terminate
        await manager.terminate("normal_shutdown")

        # Should be stopped
        assert manager.is_running is False
        assert bot.stop_called is True
        assert manager.termination_reason == "normal_shutdown"

        # Cleanup
        try:
            await start_task
        except:
            pass

    @pytest.mark.asyncio
    async def test_startup_error_handling(self):
        """Test that startup errors are handled properly"""
        bot = MockBot()
        bot.start_side_effect = Exception("Startup failed")
        manager = BotLifecycleManager(bot)

        # Start should fail
        with pytest.raises(Exception, match="Startup failed"):
            await manager.start()

        # Should have attempted cleanup
        assert bot.stop_called is True
        assert manager.termination_reason == "startup_error"


if __name__ == "__main__":
    # Allow running tests directly
    pytest.main([__file__, "-v", "-s"])
