import subprocess
import platform
import webbrowser
from rich import print


# -------------------------------
# Check Docker Installed
# -------------------------------
def docker_exists():
    result = subprocess.run(
        "docker --version",
        shell=True,
        capture_output=True
    )
    return result.returncode == 0


# -------------------------------
# Check Docker Running
# -------------------------------
def docker_running():
    result = subprocess.run(
        "docker info",
        shell=True,
        capture_output=True
    )
    return result.returncode == 0


# -------------------------------
# Install Docker (Guided)
# -------------------------------
def install_docker():
    os_type = platform.system()

    confirm = input("\n[!] This will install Docker. Continue? (y/N): ").lower()
    if confirm != "y":
        print("[yellow][!] Installation cancelled[/yellow]")
        exit()

    if os_type == "Linux":
        print("[cyan][+] Installing Docker (Linux)...[/cyan]")
        subprocess.run("sudo apt update", shell=True)
        subprocess.run("sudo apt install -y docker.io", shell=True)

        print("\n[green][+] Docker installed![/green]")
        print("[yellow]Run the following and restart terminal:[/yellow]")
        print("sudo usermod -aG docker $USER")

    elif os_type == "Darwin":
        print("[cyan][+] Opening Docker Desktop download page...[/cyan]")
        webbrowser.open("https://www.docker.com/products/docker-desktop")

    elif os_type == "Windows":
        print("[cyan][+] Opening Docker Desktop download page...[/cyan]")
        webbrowser.open("https://www.docker.com/products/docker-desktop")

    else:
        print("[red][!] Unsupported OS[/red]")
        exit()


# -------------------------------
# Open Guide
# -------------------------------
def open_docker_guide():
    webbrowser.open("https://docs.docker.com/get-docker/")
    print("[cyan][+] Opened Docker installation guide[/cyan]")


# -------------------------------
# Onboarding Menu
# -------------------------------
def docker_onboarding():
    print("\n[bold red][!] Docker not found[/bold red]\n")
    print("Kytin requires Docker for local execution.\n")

    print("1. Install Docker (recommended)")
    print("2. Open installation guide")
    print("3. Exit")

    choice = input("\nEnter choice: ").strip()

    if choice == "1":
        install_docker()
    elif choice == "2":
        open_docker_guide()
    else:
        exit()