"""
Uninstall infra CLI
"""

import sys
import subprocess
import os
from pathlib import Path
from ..core.users import UserManager
from ..core.config import Config


def cmd_uninstall() -> None:
    """Uninstall infra CLI and clean up"""
    print("\n[bold red]⚠️  UNINSTALL INFRA CLI[/bold red]")
    print("=" * 60)

    # Discover managed services
    managed_services = Config.get_managed_services()

    print("\nThis will:")
    if managed_services:
        print(f"  1. Stop all managed Docker services ({', '.join(managed_services)})")
    else:
        print("  1. Stop all managed Docker services (none found)")
    print("  2. Remove the infra-users group")
    print("  3. Remove configuration files")
    print("  4. Uninstall the Python package")
    print()

    confirm = input("Type 'yes' to continue: ").strip().lower()

    if confirm != "yes":
        print("Cancelled")
        sys.exit(0)

    print("\n[1/4] Stopping Docker services...")
    services_stopped = 0
    for service in managed_services:
        service_dir = Config.SERVICES_DIR / service
        compose_files = Config.get_service_compose_files(service)

        if not compose_files:
            print(f"  {service}: Skipped (no docker-compose files)")
            continue

        print(f"  Stopping {service}...")
        # Stop all compose files for this service
        for compose_file in compose_files:
            result = subprocess.run(
                f"cd {service_dir} && COMPOSE_FILE={compose_file.name} docker-compose -f {compose_file.name} down",
                shell=True,
                capture_output=True,
                text=True
            )

            if result.returncode == 0:
                if len(compose_files) > 1:
                    print(f"    ✓ Stopped {compose_file.name}")
                services_stopped += 1
            else:
                if len(compose_files) > 1:
                    print(f"    Note: {compose_file.name}: {result.stdout or result.stderr or 'Already stopped'}")

        if len(compose_files) == 1:
            print(f"    ✓ Stopped")

    if services_stopped == 0:
        print("  No services were stopped")
    else:
        print(f"  Stopped {services_stopped} service(s)")

    print("\n[2/4] Removing infra-users group...")
    if UserManager.group_exists():
        members = UserManager.get_group_members()
        for member in members:
            print(f"  Removing {member} from group...")
            UserManager.remove_user_from_group(member)

        print(f"  Removing {UserManager.GROUP_NAME} group...")
        result = subprocess.run(
            f"sudo groupdel {UserManager.GROUP_NAME}",
            shell=True,
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            print(f"    ✓ Group removed")
        else:
            print(f"    {result.stderr or 'Failed to remove group'}")
    else:
        print("  Group does not exist, skipping...")

    print("\n[3/4] Removing configuration files...")
    if Config.CONFIG_DIR.exists():
        print(f"  Removing {Config.CONFIG_DIR}...")
        result = subprocess.run(
            f"sudo rm -rf {Config.CONFIG_DIR}",
            shell=True,
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            print(f"    ✓ Configuration removed")
        else:
            print(f"    {result.stderr or 'Failed to remove config'}")
    else:
        print("  No configuration files found, skipping...")

    # Also try to remove legacy config location
    legacy_config = Config.INSTALL_DIR / "config"
    if legacy_config.exists() and legacy_config != Config.CONFIG_DIR:
        print(f"  Removing legacy config {legacy_config}...")
        subprocess.run(
            f"sudo rm -rf {legacy_config}",
            shell=True,
            capture_output=True
        )

    print("\n[4/4] Uninstalling Python package...")
    result = subprocess.run(
        "pip3 uninstall -y infra-services",
        shell=True,
        capture_output=True,
        text=True
    )

    if result.returncode == 0:
        print("  ✓ Package uninstalled")
    else:
        print(f"  {result.stderr or 'Failed to uninstall'}")

    print("\n[green]✓ Uninstallation complete[/green]")
    print("\nNote: You may need to log out and log back in for group changes to take effect")
    print("\nDocker service files are still in:", Config.SERVICES_DIR)
    print("To completely remove, run: sudo rm -rf", Config.SERVICES_DIR)
