#!/usr/bin/env python3
"""
AIVA Demo Recording - Setup Validation
Tests all dependencies and configurations before running the main script.

Usage:
    python test_setup.py

Author: Genesis AI
Created: 2026-02-15
"""

import sys
import subprocess
from pathlib import Path

# ANSI color codes for terminal output
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RESET = '\033[0m'
BOLD = '\033[1m'


def print_header(text):
    """Print a formatted header."""
    print(f"\n{BOLD}{BLUE}{'='*70}{RESET}")
    print(f"{BOLD}{BLUE}{text.center(70)}{RESET}")
    print(f"{BOLD}{BLUE}{'='*70}{RESET}\n")


def print_success(text):
    """Print success message."""
    print(f"{GREEN}✅ {text}{RESET}")


def print_error(text):
    """Print error message."""
    print(f"{RED}❌ {text}{RESET}")


def print_warning(text):
    """Print warning message."""
    print(f"{YELLOW}⚠️  {text}{RESET}")


def print_info(text):
    """Print info message."""
    print(f"   {text}")


def check_python_version():
    """Check Python version is 3.8+."""
    print_header("CHECKING PYTHON VERSION")

    version = sys.version_info
    version_str = f"{version.major}.{version.minor}.{version.micro}"

    if version.major >= 3 and version.minor >= 8:
        print_success(f"Python {version_str} (compatible)")
        return True
    else:
        print_error(f"Python {version_str} (requires 3.8+)")
        return False


def check_python_dependencies():
    """Check required Python packages are installed."""
    print_header("CHECKING PYTHON DEPENDENCIES")

    dependencies = {
        'requests': 'HTTP library for API calls',
        'docx': 'Word document reader (python-docx)',
    }

    all_good = True
    missing = []

    for module, description in dependencies.items():
        try:
            __import__(module)
            print_success(f"{module:15} - {description}")
        except ImportError:
            print_error(f"{module:15} - {description} (MISSING)")
            all_good = False
            missing.append(module if module != 'docx' else 'python-docx')

    if not all_good:
        print_warning("\nMissing dependencies detected")
        print_info("To install:")
        print_info(f"  pip install {' '.join(missing)}")

    return all_good


def check_ffmpeg():
    """Check ffmpeg is installed and accessible."""
    print_header("CHECKING FFMPEG")

    try:
        result = subprocess.run(
            ['ffmpeg', '-version'],
            capture_output=True,
            timeout=5,
            text=True
        )

        if result.returncode == 0:
            # Extract version from first line
            version_line = result.stdout.split('\n')[0]
            version = version_line.split('version')[1].split()[0] if 'version' in version_line else 'unknown'
            print_success(f"ffmpeg version {version} (installed)")

            # Check for required encoders
            print_info("Checking required encoders...")

            encoders = {
                'libopus': 'Opus encoder for WebM',
                'libmp3lame': 'MP3 encoder for fallback',
            }

            for encoder, description in encoders.items():
                encoder_check = subprocess.run(
                    ['ffmpeg', '-encoders'],
                    capture_output=True,
                    text=True
                )

                if encoder in encoder_check.stdout:
                    print_success(f"  {encoder:15} - {description}")
                else:
                    print_warning(f"  {encoder:15} - {description} (may be missing)")

            return True
        else:
            print_error("ffmpeg not working properly")
            return False

    except FileNotFoundError:
        print_error("ffmpeg not found in PATH")
        print_info("To install:")
        print_info("  Ubuntu/WSL: sudo apt-get install ffmpeg")
        print_info("  macOS: brew install ffmpeg")
        return False
    except Exception as e:
        print_error(f"ffmpeg check failed: {e}")
        return False


def check_working_directory():
    """Verify we're running on E: drive (Windows WSL protection)."""
    print_header("CHECKING WORKING DIRECTORY")

    cwd = Path.cwd()

    # Check if we're on E: drive (for WSL)
    if str(cwd).startswith('/mnt/e'):
        print_success(f"On E: drive: {cwd}")
        return True
    else:
        print_warning(f"Not on E: drive: {cwd}")
        print_info("This may be fine, but be aware of C: drive space constraints")
        return True  # Not a hard failure


def check_script_file():
    """Check that the demo script .docx file exists."""
    print_header("CHECKING DEMO SCRIPT FILE")

    script_path = Path("/mnt/e/genesis-system/RECEPTIONISTAI/Receptionist AI Pre-Recording Demo Script.docx")

    if script_path.exists():
        size_kb = script_path.stat().st_size / 1024
        print_success(f"Script file found: {script_path.name}")
        print_info(f"  Size: {size_kb:.1f} KB")
        return True
    else:
        print_warning(f"Script file not found: {script_path}")
        print_info("Fallback script text will be used instead")
        return True  # Not a hard failure - we have fallback


def check_output_directory():
    """Check that output directory exists or can be created."""
    print_header("CHECKING OUTPUT DIRECTORY")

    output_dir = Path("/mnt/e/genesis-system/RECEPTIONISTAI/assets/audio")

    try:
        output_dir.mkdir(parents=True, exist_ok=True)
        print_success(f"Output directory ready: {output_dir}")

        # Check write permissions
        test_file = output_dir / ".test_write"
        try:
            test_file.write_text("test")
            test_file.unlink()
            print_success("  Write permissions confirmed")
            return True
        except Exception as e:
            print_error(f"  Cannot write to directory: {e}")
            return False

    except Exception as e:
        print_error(f"Cannot create output directory: {e}")
        return False


def check_telnyx_api():
    """Verify Telnyx API key is configured (without actually calling the API)."""
    print_header("CHECKING TELNYX API CONFIGURATION")

    # Import from main script
    try:
        sys.path.insert(0, str(Path(__file__).parent))
        from record_demo import TELNYX_API_KEY, TELNYX_TTS_URL, VOICE_NAME

        if TELNYX_API_KEY and len(TELNYX_API_KEY) > 20:
            print_success(f"API key configured: {TELNYX_API_KEY[:20]}...")
            print_info(f"  Endpoint: {TELNYX_TTS_URL}")
            print_info(f"  Voice: {VOICE_NAME}")
            return True
        else:
            print_error("API key missing or invalid")
            return False

    except Exception as e:
        print_error(f"Cannot import configuration: {e}")
        return False


def check_disk_space():
    """Check available disk space on output directory."""
    print_header("CHECKING DISK SPACE")

    output_dir = Path("/mnt/e/genesis-system/RECEPTIONISTAI/assets/audio")

    try:
        stat = subprocess.run(
            ['df', '-h', str(output_dir.parent)],
            capture_output=True,
            text=True
        )

        if stat.returncode == 0:
            lines = stat.stdout.strip().split('\n')
            if len(lines) >= 2:
                # Parse df output
                parts = lines[1].split()
                if len(parts) >= 4:
                    available = parts[3]
                    use_percent = parts[4]

                    print_success(f"Available: {available} ({use_percent} used)")

                    # Check if we have at least 100MB
                    if 'M' in available or 'G' in available or 'T' in available:
                        return True
                    else:
                        print_warning("Low disk space detected")
                        return True  # Not a hard failure

        print_info("Could not determine disk space (non-critical)")
        return True

    except Exception as e:
        print_info(f"Disk space check skipped: {e}")
        return True  # Not a hard failure


def print_summary(results):
    """Print summary of all checks."""
    print_header("VALIDATION SUMMARY")

    passed = sum(1 for r in results.values() if r)
    total = len(results)

    for check, result in results.items():
        if result:
            print_success(f"{check:30} PASS")
        else:
            print_error(f"{check:30} FAIL")

    print(f"\n{BOLD}Results: {passed}/{total} checks passed{RESET}\n")

    if passed == total:
        print_success("All checks passed! Ready to run record_demo.py")
        return True
    else:
        print_warning("Some checks failed. Fix issues before proceeding.")
        print_info("\nTo fix most issues:")
        print_info("  1. Install ffmpeg: sudo apt-get install ffmpeg")
        print_info("  2. Install Python deps: pip install requests python-docx")
        print_info("  3. Re-run this test: python test_setup.py")
        return False


def main():
    """Run all validation checks."""
    print(f"\n{BOLD}{'='*70}{RESET}")
    print(f"{BOLD}AIVA DEMO RECORDING - SETUP VALIDATION{RESET}".center(70))
    print(f"{BOLD}{'='*70}{RESET}")

    # Run all checks
    results = {
        'Python Version': check_python_version(),
        'Python Dependencies': check_python_dependencies(),
        'ffmpeg': check_ffmpeg(),
        'Working Directory': check_working_directory(),
        'Demo Script File': check_script_file(),
        'Output Directory': check_output_directory(),
        'Telnyx API Config': check_telnyx_api(),
        'Disk Space': check_disk_space(),
    }

    # Print summary
    success = print_summary(results)

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


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print(f"\n\n{YELLOW}⚠️  Interrupted by user. Exiting.{RESET}")
        sys.exit(0)
    except Exception as e:
        print(f"\n{RED}❌ Unexpected error: {e}{RESET}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
