import os
import sys
import signal
import subprocess
import multiprocessing
from pathlib import Path
from rich.console import Console

from bot.cli.section import Sections
from bot.auth.authentication import Authentication
from bot.auth.auth_page import show_license_notice, authentication_page

console = Console()

# Handle Ctrl+C gracefully
def handle_signit(sig, frame) -> None:
    console.print("\n[bold cyan]Detected Ctrl+C. Ending session safely...[/bold cyan]")
    sys.exit(0)

signal.signal(signal.SIGINT, handle_signit)

# Configure Playwright to use correct browser path
def set_browser_path():
    
    if getattr(sys, "frozen", False):
        # Running as standalone binary
        base_dir = Path(sys.argv[0]).resolve().parent
        os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(base_dir / "ms-playwright")
    else:
        # Running from development environment
        os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(Path.home() / ".cache/ms-playwright")

set_browser_path()

# Ensure Chromium is installed for PyPI users
def ensure_browser():
    """
    Automatically install Chromium if missing.
    Works for PyPI installs and fresh machines.
    """
    browser_path = Path(os.environ["PLAYWRIGHT_BROWSERS_PATH"])
    chromium_dir = browser_path / "chromium-*"  # any version

    # Check if directory exists and contains at least one folder
    if not any(browser_path.glob("chromium-*")):
        console.print("[bold cyan]Playwright browser not found. Installing Chromium...[/bold cyan]")
        try:
            # Use sys.executable to call Python module
            subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
            console.print("[bold green]Chromium installed successfully![/bold green]")
        except Exception as e:
            console.print(f"[bold red]Failed to install Chromium: {e}[/bold red]")
            sys.exit(1)

authenticated = Authentication()
app = Sections(console)

def main() -> None:
    ensure_browser()
    authentication_page()

    if authenticated.validate_license_key():
        app.home_pagesection()
    else:
        show_license_notice()

if __name__ == "__main__":
    multiprocessing.freeze_support()
    main()