#!/usr/bin/env python3
"""
Railway Configuration Validator for Screenshare Bot
Task #119 Stream A - Production Deployment & Monitoring

Validates that the Railway environment is properly configured to run
the screenshare bot. Checks environment variables, dependencies,
API connectivity, and Playwright initialization.

Usage:
    python scripts/validate_railway_config.py

Exit codes:
    0 - All checks passed
    1 - One or more checks failed
"""

import asyncio
import os
import sys
import logging
from typing import Dict, List, Tuple

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


class RailwayConfigValidator:
    """Validates Railway environment configuration for screenshare bot."""

    # Required environment variables
    REQUIRED_ENV_VARS = {
        'PIPECAT_API_KEY': 'Pipecat API key for bot authentication',
        'DAILY_PIPECAT_API_KEY': 'Daily.co API key for Pipecat integration',
        'DAILY_API_KEY': 'Daily.co API key for creating rooms and authentication',
        'SUPABASE_URL': 'Supabase project URL for database access',
        'SUPABASE_SERVICE_KEY': 'Supabase service role key for admin operations',
    }

    # Optional environment variables with defaults
    OPTIONAL_ENV_VARS = {
        'BOT_TIMEOUT_MINUTES': ('30', 'Maximum bot session duration in minutes'),
        'MAX_CONCURRENT_BOTS': ('5', 'Maximum number of concurrent bot instances'),
        'FRAME_RATE': ('10', 'Video frame rate (FPS)'),
        'DEBUG_MODE': ('false', 'Enable debug logging'),
        'LOG_LEVEL': ('INFO', 'Logging level (DEBUG, INFO, WARNING, ERROR)'),
        'MOTIA_API_URL': ('http://localhost:3000', 'Motia API base URL for spawning'),
    }

    # Required Python packages
    REQUIRED_PACKAGES = [
        'pipecat',
        'daily',
        'playwright',
        'PIL',
        'aiohttp',
        'psutil',
        'dotenv',
    ]

    def __init__(self):
        self.checks_passed = []
        self.checks_failed = []
        self.warnings = []

    def _check_pass(self, message: str):
        """Record a passed check."""
        self.checks_passed.append(message)
        logger.info(f"✅ {message}")

    def _check_fail(self, message: str):
        """Record a failed check."""
        self.checks_failed.append(message)
        logger.error(f"❌ {message}")

    def _check_warn(self, message: str):
        """Record a warning."""
        self.warnings.append(message)
        logger.warning(f"⚠️  {message}")

    def check_environment_variables(self) -> bool:
        """
        Check that all required environment variables are set.

        Returns:
            True if all required vars are present, False otherwise
        """
        logger.info("=" * 70)
        logger.info("CHECKING ENVIRONMENT VARIABLES")
        logger.info("=" * 70)

        all_present = True

        # Check required variables
        for var_name, description in self.REQUIRED_ENV_VARS.items():
            value = os.getenv(var_name)
            if value:
                # Mask sensitive values in logs
                masked_value = f"{value[:8]}..." if len(value) > 8 else "***"
                self._check_pass(f"{var_name} is set ({masked_value}) - {description}")
            else:
                self._check_fail(f"{var_name} is NOT set - {description}")
                all_present = False

        # Check optional variables
        logger.info("")
        logger.info("Optional variables (with defaults):")
        for var_name, (default, description) in self.OPTIONAL_ENV_VARS.items():
            value = os.getenv(var_name, default)
            logger.info(f"  {var_name} = {value} - {description}")

        return all_present

    def check_python_dependencies(self) -> bool:
        """
        Check that all required Python packages can be imported.

        Returns:
            True if all packages are available, False otherwise
        """
        logger.info("")
        logger.info("=" * 70)
        logger.info("CHECKING PYTHON DEPENDENCIES")
        logger.info("=" * 70)

        all_available = True

        for package in self.REQUIRED_PACKAGES:
            try:
                if package == 'pipecat':
                    import pipecat
                    version = getattr(pipecat, '__version__', 'unknown')
                    self._check_pass(f"{package} is installed (version: {version})")
                elif package == 'daily':
                    import daily
                    self._check_pass(f"{package} (daily-python) is installed")
                elif package == 'playwright':
                    import playwright
                    self._check_pass(f"{package} is installed")
                elif package == 'PIL':
                    from PIL import Image
                    self._check_pass(f"Pillow (PIL) is installed")
                elif package == 'aiohttp':
                    import aiohttp
                    version = aiohttp.__version__
                    self._check_pass(f"{package} is installed (version: {version})")
                elif package == 'psutil':
                    import psutil
                    version = psutil.__version__
                    self._check_pass(f"{package} is installed (version: {version})")
                elif package == 'dotenv':
                    import dotenv
                    self._check_pass(f"python-dotenv is installed")
                else:
                    __import__(package)
                    self._check_pass(f"{package} is installed")
            except ImportError as e:
                self._check_fail(f"{package} is NOT installed - {e}")
                all_available = False

        return all_available

    async def check_daily_api_key(self) -> bool:
        """
        Validate Daily.co API key by making a test request.

        Returns:
            True if API key is valid, False otherwise
        """
        logger.info("")
        logger.info("=" * 70)
        logger.info("CHECKING DAILY.CO API KEY")
        logger.info("=" * 70)

        api_key = os.getenv('DAILY_API_KEY')
        if not api_key:
            self._check_fail("DAILY_API_KEY not set - cannot validate")
            return False

        try:
            import aiohttp

            url = "https://api.daily.co/v1/rooms"
            headers = {
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            }

            timeout = aiohttp.ClientTimeout(total=10)
            async with aiohttp.ClientSession(timeout=timeout) as session:
                async with session.get(url, headers=headers) as response:
                    if response.status == 200:
                        data = await response.json()
                        room_count = len(data.get('data', []))
                        self._check_pass(
                            f"DAILY_API_KEY is valid (found {room_count} rooms)"
                        )
                        return True
                    else:
                        error_text = await response.text()
                        self._check_fail(
                            f"DAILY_API_KEY validation failed: "
                            f"HTTP {response.status} - {error_text}"
                        )
                        return False

        except Exception as e:
            self._check_fail(f"DAILY_API_KEY validation error: {e}")
            return False

    async def check_pipecat_api_keys(self) -> bool:
        """
        Validate Pipecat API keys are set (format check only).
        Note: Actual API validation would require Pipecat service endpoint.

        Returns:
            True if keys appear valid, False otherwise
        """
        logger.info("")
        logger.info("=" * 70)
        logger.info("CHECKING PIPECAT API KEYS")
        logger.info("=" * 70)

        all_valid = True

        # Check PIPECAT_API_KEY
        pipecat_key = os.getenv('PIPECAT_API_KEY')
        if pipecat_key:
            if len(pipecat_key) >= 16:
                masked = f"{pipecat_key[:8]}..."
                self._check_pass(f"PIPECAT_API_KEY is set and has valid format ({masked})")
            else:
                self._check_fail(f"PIPECAT_API_KEY is too short (expected >= 16 chars)")
                all_valid = False
        else:
            self._check_fail("PIPECAT_API_KEY is not set")
            all_valid = False

        # Check DAILY_PIPECAT_API_KEY
        daily_pipecat_key = os.getenv('DAILY_PIPECAT_API_KEY')
        if daily_pipecat_key:
            if len(daily_pipecat_key) >= 16:
                masked = f"{daily_pipecat_key[:8]}..."
                self._check_pass(f"DAILY_PIPECAT_API_KEY is set and has valid format ({masked})")
            else:
                self._check_fail(f"DAILY_PIPECAT_API_KEY is too short (expected >= 16 chars)")
                all_valid = False
        else:
            self._check_fail("DAILY_PIPECAT_API_KEY is not set")
            all_valid = False

        return all_valid

    async def check_supabase_connection(self) -> bool:
        """
        Test Supabase connection.

        Returns:
            True if connection works, False otherwise
        """
        logger.info("")
        logger.info("=" * 70)
        logger.info("CHECKING SUPABASE CONNECTION")
        logger.info("=" * 70)

        supabase_url = os.getenv('SUPABASE_URL')
        supabase_key = os.getenv('SUPABASE_SERVICE_KEY')

        if not supabase_url or not supabase_key:
            self._check_fail("SUPABASE_URL or SUPABASE_SERVICE_KEY not set")
            return False

        try:
            import aiohttp

            # Test connection with a simple health check
            url = f"{supabase_url}/rest/v1/"
            headers = {
                "apikey": supabase_key,
                "Authorization": f"Bearer {supabase_key}"
            }

            timeout = aiohttp.ClientTimeout(total=10)
            async with aiohttp.ClientSession(timeout=timeout) as session:
                async with session.get(url, headers=headers) as response:
                    if response.status in [200, 404]:
                        # 404 is OK - means API is responding
                        self._check_pass(
                            f"Supabase connection successful ({supabase_url})"
                        )
                        return True
                    else:
                        error_text = await response.text()
                        self._check_fail(
                            f"Supabase connection failed: "
                            f"HTTP {response.status} - {error_text}"
                        )
                        return False

        except Exception as e:
            self._check_fail(f"Supabase connection error: {e}")
            return False

    async def check_playwright_availability(self) -> bool:
        """
        Check if Playwright can be initialized.

        Note: This is a basic check. Full browser initialization
        requires `playwright install` to have been run.

        Returns:
            True if Playwright is available, False otherwise
        """
        logger.info("")
        logger.info("=" * 70)
        logger.info("CHECKING PLAYWRIGHT AVAILABILITY")
        logger.info("=" * 70)

        try:
            from playwright.async_api import async_playwright

            self._check_pass("Playwright module can be imported")

            # Try to initialize (this will fail if browsers aren't installed,
            # but that's expected in Railway - we just check the module works)
            try:
                async with async_playwright() as p:
                    self._check_pass("Playwright context manager works")

                    # Check if chromium is available
                    try:
                        browser = await p.chromium.launch(headless=True)
                        await browser.close()
                        self._check_pass("Playwright Chromium browser can be launched")
                        return True
                    except Exception as browser_error:
                        self._check_warn(
                            f"Playwright browser launch failed: {browser_error}"
                        )
                        self._check_warn(
                            "This is expected if 'playwright install' hasn't been run"
                        )
                        self._check_warn(
                            "Make sure Dockerfile includes: RUN playwright install --with-deps chromium"
                        )
                        # Return True anyway - the module works, just needs browser install
                        return True

            except Exception as e:
                self._check_warn(f"Playwright initialization check: {e}")
                return True  # Module is importable, which is what matters

        except ImportError as e:
            self._check_fail(f"Playwright is NOT available: {e}")
            return False

    def check_bot_modules(self) -> bool:
        """
        Check that bot-specific modules can be imported.

        Returns:
            True if all bot modules are available, False otherwise
        """
        logger.info("")
        logger.info("=" * 70)
        logger.info("CHECKING BOT MODULES")
        logger.info("=" * 70)

        all_available = True

        # Import bot.py to check dependencies
        try:
            # Get the bot directory
            import sys
            from pathlib import Path
            bot_dir = Path(__file__).parent.parent
            if str(bot_dir) not in sys.path:
                sys.path.insert(0, str(bot_dir))

            # Try importing the bot
            import bot
            self._check_pass("bot.py can be imported")

            # Check for required classes
            if hasattr(bot, 'ScreenshareBot'):
                self._check_pass("ScreenshareBot class is available")
            else:
                self._check_fail("ScreenshareBot class not found in bot.py")
                all_available = False

        except Exception as e:
            self._check_fail(f"Failed to import bot.py: {e}")
            all_available = False

        # Check deck_url_validator
        try:
            import deck_url_validator
            self._check_pass("deck_url_validator.py can be imported")
        except Exception as e:
            self._check_fail(f"Failed to import deck_url_validator.py: {e}")
            all_available = False

        # Check performance_monitor
        try:
            import performance_monitor
            self._check_pass("performance_monitor.py can be imported")
        except Exception as e:
            self._check_fail(f"Failed to import performance_monitor.py: {e}")
            all_available = False

        return all_available

    async def run_all_checks(self) -> bool:
        """
        Run all validation checks.

        Returns:
            True if all critical checks passed, False otherwise
        """
        logger.info("=" * 70)
        logger.info("RAILWAY CONFIGURATION VALIDATOR FOR SCREENSHARE BOT")
        logger.info("=" * 70)
        logger.info("")

        # Run all checks
        env_check = self.check_environment_variables()
        deps_check = self.check_python_dependencies()
        pipecat_keys_check = await self.check_pipecat_api_keys()
        daily_check = await self.check_daily_api_key()
        supabase_check = await self.check_supabase_connection()
        playwright_check = await self.check_playwright_availability()
        modules_check = self.check_bot_modules()

        # Print summary
        logger.info("")
        logger.info("=" * 70)
        logger.info("VALIDATION SUMMARY")
        logger.info("=" * 70)

        logger.info(f"\n✅ Checks Passed: {len(self.checks_passed)}")
        for check in self.checks_passed:
            logger.info(f"   - {check}")

        if self.warnings:
            logger.info(f"\n⚠️  Warnings: {len(self.warnings)}")
            for warning in self.warnings:
                logger.info(f"   - {warning}")

        if self.checks_failed:
            logger.info(f"\n❌ Checks Failed: {len(self.checks_failed)}")
            for check in self.checks_failed:
                logger.info(f"   - {check}")

        logger.info("")
        all_passed = (
            env_check and
            deps_check and
            pipecat_keys_check and
            daily_check and
            supabase_check and
            playwright_check and
            modules_check
        )

        if all_passed:
            logger.info("🎉 ALL CRITICAL CHECKS PASSED - Railway is ready for deployment!")
        else:
            logger.error("❌ SOME CHECKS FAILED - Please fix the issues above before deploying")

        logger.info("=" * 70)

        return all_passed


async def main():
    """Main entry point."""
    validator = RailwayConfigValidator()
    success = await validator.run_all_checks()

    # Exit with appropriate code
    sys.exit(0 if success else 1)


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