# ankur_scraper/core/playwright_checker.py
"""
Playwright browser availability checker with auto-installation.
"""

import subprocess
import sys
from pathlib import Path
from ankur_scraper.logging_config import get_logger

info_logger = get_logger("info")
error_logger = get_logger("error")


def get_playwright_browsers_path():
    """Get the default Playwright browsers installation path."""
    import os
    
    if sys.platform == "win32":
        # Windows: %USERPROFILE%\AppData\Local\ms-playwright
        return Path(os.environ.get("USERPROFILE", "")) / "AppData" / "Local" / "ms-playwright"
    elif sys.platform == "darwin":
        # macOS: ~/Library/Caches/ms-playwright
        return Path.home() / "Library" / "Caches" / "ms-playwright"
    else:
        # Linux: ~/.cache/ms-playwright
        return Path.home() / ".cache" / "ms-playwright"


def is_chromium_installed():
    """
    Check if Playwright Chromium browser is installed.
    
    Returns:
        bool: True if Chromium is installed, False otherwise
    """
    try:
        # Check if browsers directory exists
        browsers_path = get_playwright_browsers_path()
        
        if not browsers_path.exists():
            return False
        
        # Check for chromium directory
        chromium_dirs = list(browsers_path.glob("chromium-*"))
        
        return len(chromium_dirs) > 0
        
    except Exception as e:
        error_logger.debug(f"Error checking Chromium installation: {e}")
        return False


def install_chromium():
    """
    Attempt to install Playwright Chromium browser.
    
    Returns:
        bool: True if installation succeeded, False otherwise
    """
    info_logger.info("[yellow]Playwright Chromium not found. Attempting auto-install...[/]")
    
    try:
        # Run playwright install chromium
        result = subprocess.run(
            [sys.executable, "-m", "playwright", "install", "chromium"],
            capture_output=True,
            text=True,
            timeout=300  # 5 minute timeout
        )
        
        if result.returncode == 0:
            info_logger.info("[green]✅ Chromium browser installed successfully![/]")
            return True
        else:
            error_logger.error(f"[red]Failed to install Chromium:[/] {result.stderr}")
            return False
            
    except subprocess.TimeoutExpired:
        error_logger.error("[red]Chromium installation timed out (5 minutes)[/]")
        return False
    except Exception as e:
        error_logger.error(f"[red]Error installing Chromium:[/] {e}")
        return False


def check_playwright_available():
    """
    Check if Playwright is available and browsers are installed.
    Auto-installs browsers if missing.
    
    Returns:
        bool: True if Playwright is ready to use, False otherwise
    
    Raises:
        RuntimeError: If Playwright cannot be made available
    """
    # Check if playwright module is installed
    try:
        import playwright
    except ImportError:
        raise RuntimeError(
            "Playwright is not installed. Install it with: pip install playwright"
        )
    
    # Check if Chromium browser is installed
    if is_chromium_installed():
        info_logger.debug("Chromium browser is already installed")
        return True
    
    # Try to auto-install
    info_logger.info("[yellow]Chromium browser not found. Installing...[/]")
    
    if install_chromium():
        # Verify installation
        if is_chromium_installed():
            return True
        else:
            raise RuntimeError(
                "Chromium installation reported success but browser not found. "
                "Try manually: playwright install chromium"
            )
    else:
        # Auto-install failed
        raise RuntimeError(
            "Failed to auto-install Playwright browsers.\n"
            "Please install manually:\n"
            "    playwright install chromium\n"
            "Or disable dynamic mode and use static scraping only."
        )


def get_browser_info():
    """
    Get information about installed Playwright browsers.
    
    Returns:
        dict: Information about installed browsers
    """
    info = {
        "browsers_path": str(get_playwright_browsers_path()),
        "chromium_installed": is_chromium_installed(),
        "browsers_found": []
    }
    
    try:
        browsers_path = get_playwright_browsers_path()
        if browsers_path.exists():
            # List all browser directories
            for browser_dir in browsers_path.iterdir():
                if browser_dir.is_dir():
                    info["browsers_found"].append(browser_dir.name)
    except Exception as e:
        info["error"] = str(e)
    
    return info