#!/usr/bin/env python3
"""
Bot Lifecycle Manager

Manages bot lifecycle including:
- Inactivity timeout monitoring (30 minutes configurable)
- Signal handling (SIGTERM, SIGINT) for graceful shutdown
- Termination notifications
- Resource cleanup coordination

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

import asyncio
import logging
import signal
import time
from typing import Callable, Optional, Any, TypeVar, Coroutine

logger = logging.getLogger(__name__)

T = TypeVar('T')


async def retry_with_backoff(
    func: Callable[[], Coroutine[Any, Any, T]],
    max_attempts: int = 3,
    operation_name: str = "operation"
) -> T:
    """
    Retry an async function with exponential backoff.

    Args:
        func: Async function to retry (no arguments)
        max_attempts: Maximum number of attempts (default: 3)
        operation_name: Name for logging purposes

    Returns:
        Result of the function call

    Raises:
        Exception: Re-raises the last exception if all attempts fail

    Example:
        >>> result = await retry_with_backoff(some_async_func, max_attempts=3)
    """
    last_exception: Optional[Exception] = None

    for attempt in range(1, max_attempts + 1):
        try:
            logger.info(f"Attempting {operation_name} (attempt {attempt}/{max_attempts})")
            result = await func()
            logger.info(f"{operation_name} succeeded on attempt {attempt}")
            return result

        except Exception as e:
            last_exception = e
            wait_time = 2 ** (attempt - 1)  # 1s, 2s, 4s

            if attempt < max_attempts:
                logger.warning(
                    f"{operation_name} failed on attempt {attempt}/{max_attempts}: {e}. "
                    f"Retrying in {wait_time}s..."
                )
                await asyncio.sleep(wait_time)
            else:
                logger.error(
                    f"{operation_name} failed after {max_attempts} attempts: {e}",
                    exc_info=True
                )

    # If we got here, all attempts failed
    assert last_exception is not None
    raise last_exception


class BotLifecycleManager:
    """
    Manages bot lifecycle with inactivity monitoring and signal handling.

    Features:
    - Inactivity timeout monitoring (configurable, default 30 minutes)
    - Graceful shutdown on SIGTERM/SIGINT
    - Termination notifications
    - Coordinates resource cleanup via bot.stop()

    Example:
        >>> bot = ScreenshareBot(room_url, deck_url, session_id)
        >>> lifecycle_manager = BotLifecycleManager(bot, timeout_minutes=30)
        >>> await lifecycle_manager.start()
    """

    def __init__(
        self,
        bot: Any,  # ScreenshareBot instance
        timeout_minutes: int = 30,
        check_interval_seconds: int = 60
    ) -> None:
        """
        Initialize lifecycle manager.

        Args:
            bot: Bot instance (must have start() and stop() methods)
            timeout_minutes: Inactivity timeout in minutes (default: 30)
            check_interval_seconds: How often to check for inactivity (default: 60)
        """
        self.bot: Any = bot
        self.timeout_minutes: int = timeout_minutes
        self.check_interval_seconds: int = check_interval_seconds

        # State tracking
        self.last_activity: float = time.time()
        self.is_running: bool = False
        self._inactivity_task: Optional[asyncio.Task[None]] = None
        self._original_sigterm_handler: Any = None
        self._original_sigint_handler: Any = None
        self._termination_reason: Optional[str] = None

        logger.info(
            f"BotLifecycleManager initialized: "
            f"timeout={timeout_minutes}min, "
            f"check_interval={check_interval_seconds}s"
        )

    def update_activity(self) -> None:
        """
        Update last activity timestamp.

        Call this whenever the bot performs meaningful activity
        (e.g., receives slide command, streams frame, etc.)
        """
        self.last_activity = time.time()

    def get_inactive_time_seconds(self) -> float:
        """Get how long the bot has been inactive (in seconds)"""
        return time.time() - self.last_activity

    async def start(self) -> None:
        """
        Start the bot with lifecycle management.

        - Starts the bot (calls bot.start())
        - Begins inactivity monitoring
        - Registers signal handlers for graceful shutdown
        """
        try:
            logger.info("=" * 70)
            logger.info("STARTING BOT WITH LIFECYCLE MANAGEMENT")
            logger.info("=" * 70)
            logger.info(f"Inactivity timeout: {self.timeout_minutes} minutes")
            logger.info(f"Check interval: {self.check_interval_seconds} seconds")
            logger.info("=" * 70)

            self.is_running = True
            self.last_activity = time.time()

            # Register signal handlers
            self._register_signal_handlers()

            # Start inactivity monitor in background
            self._inactivity_task = asyncio.create_task(self._monitor_inactivity())
            logger.info("Inactivity monitor started")

            # Start the bot
            logger.info("Starting bot...")
            await self.bot.start()

        except Exception as e:
            logger.error(f"Failed to start bot with lifecycle management: {e}", exc_info=True)
            await self.terminate("startup_error")
            raise

    async def _monitor_inactivity(self) -> None:
        """
        Background task that monitors for inactivity timeout.

        Checks every check_interval_seconds and terminates bot if
        inactive for more than timeout_minutes.
        """
        try:
            logger.info(
                f"Inactivity monitor running: "
                f"will terminate after {self.timeout_minutes} minutes of inactivity"
            )

            while self.is_running:
                await asyncio.sleep(self.check_interval_seconds)

                inactive_seconds = self.get_inactive_time_seconds()
                inactive_minutes = inactive_seconds / 60

                # Log status periodically
                if int(inactive_seconds) % (5 * 60) == 0:  # Every 5 minutes
                    logger.info(
                        f"Inactivity check: {inactive_minutes:.1f} minutes "
                        f"(timeout: {self.timeout_minutes} minutes)"
                    )

                # Check if timeout reached
                if inactive_minutes >= self.timeout_minutes:
                    logger.warning(
                        f"Inactivity timeout reached: {inactive_minutes:.1f} minutes "
                        f"(threshold: {self.timeout_minutes} minutes)"
                    )
                    await self.terminate("inactivity_timeout")
                    break

        except asyncio.CancelledError:
            logger.info("Inactivity monitor cancelled")
        except Exception as e:
            logger.error(f"Inactivity monitor error: {e}", exc_info=True)
            await self.terminate("monitor_error")

    def _register_signal_handlers(self) -> None:
        """Register signal handlers for graceful shutdown"""
        try:
            # Store original handlers so we can restore them if needed
            self._original_sigterm_handler = signal.signal(
                signal.SIGTERM,
                self._handle_signal
            )
            self._original_sigint_handler = signal.signal(
                signal.SIGINT,
                self._handle_signal
            )
            logger.info("Signal handlers registered (SIGTERM, SIGINT)")

        except Exception as e:
            logger.warning(f"Failed to register signal handlers: {e}")

    def _handle_signal(self, signum: int, frame: Any) -> None:
        """
        Signal handler for SIGTERM and SIGINT.

        Creates an asyncio task to perform graceful shutdown.
        """
        signal_name = signal.Signals(signum).name
        logger.info(f"Received signal: {signal_name} ({signum})")

        # Create task for graceful shutdown
        # We can't await in a signal handler, so we create a task
        if self.is_running:
            reason = f"signal_{signal_name.lower()}"
            asyncio.create_task(self.terminate(reason))
        else:
            logger.info("Already terminating, ignoring signal")

    async def terminate(self, reason: str) -> None:
        """
        Terminate the bot gracefully.

        Args:
            reason: Reason for termination (e.g., "inactivity_timeout", "signal_sigterm")
        """
        if not self.is_running:
            logger.info(f"Terminate called but bot already stopped (reason: {reason})")
            return

        try:
            logger.info("=" * 70)
            logger.info(f"TERMINATING BOT: {reason}")
            logger.info("=" * 70)

            self.is_running = False
            self._termination_reason = reason

            # Cancel inactivity monitor
            if self._inactivity_task and not self._inactivity_task.done():
                logger.info("Cancelling inactivity monitor...")
                self._inactivity_task.cancel()
                try:
                    await self._inactivity_task
                except asyncio.CancelledError:
                    pass

            # Send termination notification
            await self._send_termination_notification(reason)

            # Stop the bot (cleanup resources)
            logger.info("Stopping bot and cleaning up resources...")
            await self.bot.stop()

            logger.info("=" * 70)
            logger.info(f"BOT TERMINATED SUCCESSFULLY: {reason}")
            logger.info("=" * 70)

        except Exception as e:
            logger.error(f"Error during termination: {e}", exc_info=True)
        finally:
            # Restore original signal handlers
            self._restore_signal_handlers()

    def _restore_signal_handlers(self) -> None:
        """Restore original signal handlers"""
        try:
            if self._original_sigterm_handler:
                signal.signal(signal.SIGTERM, self._original_sigterm_handler)
            if self._original_sigint_handler:
                signal.signal(signal.SIGINT, self._original_sigint_handler)
            logger.info("Signal handlers restored")
        except Exception as e:
            logger.warning(f"Failed to restore signal handlers: {e}")

    async def _send_termination_notification(self, reason: str) -> None:
        """
        Send termination notification.

        Currently logs to Railway logs. Can be extended to POST to backend API.

        Args:
            reason: Termination reason
        """
        try:
            # Log to Railway logs (always available)
            logger.info("=" * 70)
            logger.info("BOT TERMINATION NOTIFICATION")
            logger.info("=" * 70)
            logger.info(f"Reason: {reason}")
            logger.info(f"Runtime: {self.get_runtime_seconds():.1f} seconds")
            logger.info(f"Last activity: {self.get_inactive_time_seconds():.1f} seconds ago")
            logger.info("=" * 70)

            # Optional: POST to backend API
            # This can be implemented when backend endpoint is available
            # Example:
            # await self._post_termination_to_api({
            #     'bot_id': self.bot.bot_id,
            #     'reason': reason,
            #     'runtime_seconds': self.get_runtime_seconds(),
            #     'timestamp': time.time()
            # })

        except Exception as e:
            logger.warning(f"Failed to send termination notification: {e}")

    def get_runtime_seconds(self) -> float:
        """Get total runtime in seconds (from initialization)"""
        # Note: This approximates runtime from when lifecycle manager was created
        # For more accurate tracking, we could store a start_time in start()
        return time.time() - self.last_activity + self.get_inactive_time_seconds()

    @property
    def termination_reason(self) -> Optional[str]:
        """Get termination reason (None if not terminated)"""
        return self._termination_reason
