#!/usr/bin/env python3
"""
Load Testing Script for Concurrent Bot Testing

Spawns multiple concurrent screenshare bots and monitors their performance.
Tracks spawn time, join success rate, and bot lifecycle management.

Usage:
    python load_test.py --bots 5 --duration 60
    python load_test.py --bots 2 --duration 30 --rooms room1.daily.co room2.daily.co
    python load_test.py --cleanup  # Kill all running bots
"""

import os
import sys
import asyncio
import argparse
import logging
import time
import signal
import subprocess
from typing import List, Dict, Optional
from dataclasses import dataclass, field
from pathlib import Path

logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)


@dataclass
class BotInstance:
    """Represents a single bot instance"""
    bot_id: int
    room_url: str
    deck_url: str
    process: Optional[subprocess.Popen] = None
    pid: Optional[int] = None
    spawn_time: float = 0.0
    join_success: bool = False
    error: Optional[str] = None
    start_time: float = field(default_factory=time.time)

    @property
    def uptime(self) -> float:
        """Calculate bot uptime in seconds"""
        return time.time() - self.start_time

    @property
    def is_running(self) -> bool:
        """Check if bot process is still running"""
        if self.process:
            return self.process.poll() is None
        return False


class LoadTestManager:
    """Manages concurrent bot load testing"""

    def __init__(
        self,
        bot_script_path: str,
        deck_url: str = "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/"
    ):
        self.bot_script_path = Path(bot_script_path)
        self.deck_url = deck_url
        self.bots: List[BotInstance] = []
        self.test_start_time: Optional[float] = None
        self.test_end_time: Optional[float] = None

        # Validate bot script exists
        if not self.bot_script_path.exists():
            raise FileNotFoundError(f"Bot script not found: {bot_script_path}")

    async def spawn_bot(
        self,
        bot_id: int,
        room_url: str,
        deck_url: Optional[str] = None
    ) -> BotInstance:
        """
        Spawn a single bot instance.

        Args:
            bot_id: Unique identifier for this bot
            room_url: Daily.co room URL to join
            deck_url: Optional deck URL (uses default if None)

        Returns:
            BotInstance with process information

        Raises:
            Exception if bot spawn fails
        """
        bot = BotInstance(
            bot_id=bot_id,
            room_url=room_url,
            deck_url=deck_url or self.deck_url
        )

        try:
            logger.info(f"🚀 Spawning bot {bot_id} for room: {room_url}")
            spawn_start = time.time()

            # Build command to run bot
            # Try to use venv python if available, otherwise use current interpreter
            venv_python = self.bot_script_path.parent / ".venv" / "bin" / "python"
            python_executable = str(venv_python) if venv_python.exists() else sys.executable

            cmd = [
                python_executable,
                str(self.bot_script_path),
                room_url
            ]

            # Spawn bot process
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                env=os.environ.copy(),
                start_new_session=True  # Create new process group for easier cleanup
            )

            bot.process = process
            bot.pid = process.pid
            bot.spawn_time = time.time() - spawn_start

            # Give bot a moment to initialize
            await asyncio.sleep(0.5)

            # Check if process started successfully
            if bot.is_running:
                bot.join_success = True
                logger.info(
                    f"✅ Bot {bot_id} spawned successfully "
                    f"(PID: {bot.pid}, spawn_time: {bot.spawn_time:.2f}s)"
                )
            else:
                bot.join_success = False
                bot.error = "Process terminated immediately after spawn"
                logger.error(f"❌ Bot {bot_id} failed to start")

        except Exception as e:
            bot.error = str(e)
            logger.error(f"❌ Failed to spawn bot {bot_id}: {e}")

        self.bots.append(bot)
        return bot

    async def spawn_concurrent_bots(
        self,
        room_urls: List[str],
        num_bots: Optional[int] = None
    ) -> List[BotInstance]:
        """
        Spawn multiple bots concurrently.

        Args:
            room_urls: List of Daily.co room URLs
            num_bots: Number of bots to spawn (defaults to len(room_urls))

        Returns:
            List of BotInstance objects
        """
        num_bots = num_bots or len(room_urls)

        # Ensure we have enough room URLs
        if len(room_urls) < num_bots:
            logger.warning(
                f"⚠️ Only {len(room_urls)} rooms provided for {num_bots} bots. "
                f"Some rooms will be reused."
            )

        logger.info(f"🚀 Spawning {num_bots} bots concurrently...")
        self.test_start_time = time.time()

        # Create spawn tasks
        tasks = []
        for i in range(num_bots):
            # Cycle through available rooms
            room_url = room_urls[i % len(room_urls)]
            tasks.append(self.spawn_bot(i + 1, room_url))

        # Spawn all bots concurrently
        bots = await asyncio.gather(*tasks, return_exceptions=True)

        # Filter out exceptions
        successful_bots = [b for b in bots if isinstance(b, BotInstance) and b.join_success]
        failed_bots = [b for b in bots if isinstance(b, BotInstance) and not b.join_success]

        spawn_duration = time.time() - self.test_start_time

        logger.info("\n" + "=" * 60)
        logger.info("BOT SPAWN SUMMARY")
        logger.info("=" * 60)
        logger.info(f"Total spawn time: {spawn_duration:.2f}s")
        logger.info(f"Bots spawned: {len(successful_bots)}/{num_bots}")
        logger.info(f"Success rate: {len(successful_bots)/num_bots*100:.1f}%")

        if successful_bots:
            avg_spawn_time = sum(b.spawn_time for b in successful_bots) / len(successful_bots)
            logger.info(f"Average spawn time: {avg_spawn_time:.2f}s")

        if failed_bots:
            logger.warning(f"❌ Failed bots: {len(failed_bots)}")
            for bot in failed_bots:
                logger.warning(f"  Bot {bot.bot_id}: {bot.error}")

        logger.info("=" * 60 + "\n")

        return successful_bots

    async def monitor_bots(self, duration_seconds: int):
        """
        Monitor running bots for specified duration.

        Args:
            duration_seconds: How long to monitor (in seconds)
        """
        logger.info(f"📊 Monitoring bots for {duration_seconds} seconds...")

        monitor_interval = 10  # Log status every 10 seconds
        elapsed = 0

        while elapsed < duration_seconds:
            await asyncio.sleep(min(monitor_interval, duration_seconds - elapsed))
            elapsed += monitor_interval

            # Check bot health
            running_bots = [b for b in self.bots if b.is_running]
            dead_bots = [b for b in self.bots if not b.is_running and b.join_success]

            logger.info(
                f"⏱️ [{elapsed}s/{duration_seconds}s] "
                f"Running: {len(running_bots)}, Dead: {len(dead_bots)}"
            )

            # Log any newly dead bots
            for bot in dead_bots:
                if not hasattr(bot, '_death_logged'):
                    logger.warning(
                        f"💀 Bot {bot.bot_id} died after {bot.uptime:.1f}s uptime"
                    )
                    bot._death_logged = True

        self.test_end_time = time.time()
        logger.info(f"✅ Monitoring complete ({duration_seconds}s elapsed)")

    def kill_bot(self, bot: BotInstance) -> bool:
        """
        Kill a single bot process.

        Args:
            bot: BotInstance to kill

        Returns:
            True if killed successfully, False otherwise
        """
        if not bot.process:
            return False

        try:
            # Try graceful termination first
            bot.process.terminate()

            # Wait up to 3 seconds for graceful shutdown
            try:
                bot.process.wait(timeout=3)
                logger.info(f"✅ Bot {bot.bot_id} (PID {bot.pid}) terminated gracefully")
                return True
            except subprocess.TimeoutExpired:
                # Force kill if still running
                bot.process.kill()
                bot.process.wait()
                logger.warning(f"⚠️ Bot {bot.bot_id} (PID {bot.pid}) force killed")
                return True

        except Exception as e:
            logger.error(f"❌ Error killing bot {bot.bot_id}: {e}")
            return False

    def cleanup_all_bots(self):
        """Kill all running bot processes"""
        logger.info(f"🧹 Cleaning up {len(self.bots)} bots...")

        killed_count = 0
        for bot in self.bots:
            if bot.is_running:
                if self.kill_bot(bot):
                    killed_count += 1

        logger.info(f"✅ Cleaned up {killed_count} bots")
        return killed_count

    def get_summary(self) -> Dict:
        """
        Get load test summary statistics.

        Returns:
            Dictionary with test metrics
        """
        total_bots = len(self.bots)
        successful_spawns = len([b for b in self.bots if b.join_success])
        running_bots = len([b for b in self.bots if b.is_running])
        failed_bots = len([b for b in self.bots if not b.join_success])
        dead_bots = len([b for b in self.bots if b.join_success and not b.is_running])

        spawn_times = [b.spawn_time for b in self.bots if b.join_success]
        avg_spawn_time = sum(spawn_times) / len(spawn_times) if spawn_times else 0

        test_duration = 0
        if self.test_start_time and self.test_end_time:
            test_duration = self.test_end_time - self.test_start_time

        return {
            'total_bots': total_bots,
            'successful_spawns': successful_spawns,
            'running_bots': running_bots,
            'failed_spawns': failed_bots,
            'dead_bots': dead_bots,
            'success_rate': (successful_spawns / total_bots * 100) if total_bots > 0 else 0,
            'avg_spawn_time': avg_spawn_time,
            'test_duration': test_duration,
            'bots': [
                {
                    'bot_id': b.bot_id,
                    'pid': b.pid,
                    'room_url': b.room_url,
                    'spawn_time': b.spawn_time,
                    'join_success': b.join_success,
                    'is_running': b.is_running,
                    'uptime': b.uptime if b.join_success else 0,
                    'error': b.error
                }
                for b in self.bots
            ]
        }

    def print_summary(self):
        """Print formatted load test summary"""
        summary = self.get_summary()

        logger.info("\n" + "=" * 60)
        logger.info("LOAD TEST SUMMARY")
        logger.info("=" * 60)
        logger.info(f"Test duration: {summary['test_duration']:.1f}s")
        logger.info(f"Total bots: {summary['total_bots']}")
        logger.info(f"Successful spawns: {summary['successful_spawns']}")
        logger.info(f"Currently running: {summary['running_bots']}")
        logger.info(f"Failed spawns: {summary['failed_spawns']}")
        logger.info(f"Died during test: {summary['dead_bots']}")
        logger.info(f"Success rate: {summary['success_rate']:.1f}%")
        logger.info(f"Avg spawn time: {summary['avg_spawn_time']:.2f}s")
        logger.info("=" * 60)

        logger.info("\nPER-BOT DETAILS:")
        for bot_info in summary['bots']:
            status = "✅ Running" if bot_info['is_running'] else (
                "❌ Failed" if not bot_info['join_success'] else "💀 Dead"
            )
            logger.info(
                f"  Bot {bot_info['bot_id']} (PID {bot_info['pid']}): {status} "
                f"[spawn: {bot_info['spawn_time']:.2f}s, uptime: {bot_info['uptime']:.1f}s]"
            )
            if bot_info['error']:
                logger.info(f"    Error: {bot_info['error']}")

        logger.info("=" * 60 + "\n")


async def main():
    """Main entry point for load testing CLI"""
    parser = argparse.ArgumentParser(
        description="Load testing for concurrent screenshare bots"
    )
    parser.add_argument(
        "--bots",
        type=int,
        default=5,
        help="Number of bots to spawn (default: 5)"
    )
    parser.add_argument(
        "--duration",
        type=int,
        default=60,
        help="Test duration in seconds (default: 60)"
    )
    parser.add_argument(
        "--rooms",
        nargs="+",
        help="Daily.co room URLs (reads from test_rooms.txt if not provided)"
    )
    parser.add_argument(
        "--deck-url",
        type=str,
        default="https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
        help="Deck URL for bots"
    )
    parser.add_argument(
        "--bot-script",
        type=str,
        help="Path to bot.py script (auto-detected if not provided)"
    )
    parser.add_argument(
        "--cleanup",
        action="store_true",
        help="Kill all running bots and exit"
    )

    args = parser.parse_args()

    # Auto-detect bot script path
    if not args.bot_script:
        # Assume load_test.py is in scripts/ and bot.py is in parent directory
        script_dir = Path(__file__).parent
        bot_script = script_dir.parent / "bot.py"
        if not bot_script.exists():
            logger.error(f"❌ Could not find bot.py at {bot_script}")
            logger.info("Specify path with --bot-script")
            sys.exit(1)
        args.bot_script = str(bot_script)

    # Initialize load test manager
    manager = LoadTestManager(args.bot_script, args.deck_url)

    # Handle cleanup mode
    if args.cleanup:
        logger.info("🧹 Cleanup mode: killing all bots...")
        manager.cleanup_all_bots()
        sys.exit(0)

    # Get room URLs
    room_urls = args.rooms
    if not room_urls:
        # Try to read from test_rooms.txt
        rooms_file = Path("test_rooms.txt")
        if rooms_file.exists():
            room_urls = [line.strip() for line in rooms_file.read_text().splitlines() if line.strip()]
            logger.info(f"📄 Loaded {len(room_urls)} rooms from test_rooms.txt")
        else:
            logger.error("❌ No room URLs provided and test_rooms.txt not found")
            logger.info("Create rooms first: python scripts/create_test_rooms.py --count 5")
            sys.exit(1)

    if not room_urls:
        logger.error("❌ No room URLs available")
        sys.exit(1)

    try:
        logger.info("=" * 60)
        logger.info("LOAD TEST STARTING")
        logger.info("=" * 60)
        logger.info(f"Bots: {args.bots}")
        logger.info(f"Duration: {args.duration}s")
        logger.info(f"Rooms: {len(room_urls)}")
        logger.info(f"Deck: {args.deck_url}")
        logger.info("=" * 60 + "\n")

        # Spawn bots
        await manager.spawn_concurrent_bots(room_urls, args.bots)

        # Monitor for duration
        if args.duration > 0:
            await manager.monitor_bots(args.duration)

        # Print summary
        manager.print_summary()

    except KeyboardInterrupt:
        logger.info("\n⚠️ Received interrupt signal")
    except Exception as e:
        logger.error(f"❌ Load test error: {e}", exc_info=True)
    finally:
        # Cleanup
        logger.info("\n🧹 Cleaning up bots...")
        manager.cleanup_all_bots()
        logger.info("✅ Load test complete")


if __name__ == "__main__":
    asyncio.run(main())
