"""CLI commands for managing the composable registry"""

import sys
from ..core.registry import RegistryManager


def handle_registry_command(args):
    """Handle registry subcommands"""
    if not args:
        print("Usage: infra registry <subcommand>")
        sys.exit(1)

    subcommand = args[0]

    if subcommand == "list":
        registry_list(args[1:])

    elif subcommand == "install":
        if len(args) < 2:
            print("Usage: infra registry install <name> [-e KEY=VALUE ...]")
            sys.exit(1)
        registry_install(args[1:])

    elif subcommand == "uninstall":
        if len(args) < 2:
            print("Usage: infra registry uninstall <name>")
            sys.exit(1)
        registry_uninstall(args[1])

    elif subcommand == "enable":
        if len(args) < 2:
            print("Usage: infra registry enable <name>")
            sys.exit(1)
        registry_enable(args[1])

    elif subcommand == "disable":
        if len(args) < 2:
            print("Usage: infra registry disable <name>")
            sys.exit(1)
        registry_disable(args[1])

    elif subcommand == "start":
        if len(args) < 2:
            print("Usage: infra registry start <name>")
            sys.exit(1)
        registry_start(args[1])

    elif subcommand == "stop":
        if len(args) < 2:
            print("Usage: infra registry stop <name>")
            sys.exit(1)
        registry_stop(args[1])

    elif subcommand == "logs":
        if len(args) < 2:
            print("Usage: infra registry logs <name> [-f]")
            sys.exit(1)
        follow = "-f" in args or "--follow" in args
        registry_logs(args[1], follow)

    elif subcommand == "info":
        if len(args) < 2:
            print("Usage: infra registry info <name>")
            sys.exit(1)
        registry_info(args[1])

    else:
        print(f"Unknown registry subcommand: {subcommand}")
        sys.exit(1)


def registry_list(args):
    """List available stacks"""
    category = None
    refresh = "--refresh" in args or "-r" in args

    if "--infrastructure" in args or "-i" in args:
        category = "infrastructure"
    elif "--services" in args or "-s" in args:
        category = "services"

    try:
        if refresh:
            RegistryManager.fetch_registry(force=True)

        stacks = RegistryManager.list_stacks(category=category)

        if not stacks:
            print("No stacks found")
            return

        # Group by category
        by_category = {}
        for stack in stacks:
            cat = stack.category
            if cat not in by_category:
                by_category[cat] = []
            by_category[cat].append(stack)

        for cat, cat_stacks in by_category.items():
            print(f"\n\033[1;36m{cat.upper()}\033[0m")
            print("-" * 60)

            for stack in cat_stacks:
                # Status indicator with colors
                if not stack.installed:
                    status = "\033[90m○ not installed\033[0m"
                elif not stack.enabled:
                    status = "\033[33m○ disabled\033[0m"
                elif stack.running:
                    status = "\033[32m● running\033[0m"
                else:
                    status = "\033[31m○ stopped\033[0m"

                print(f"  \033[1m{stack.name}\033[0m")
                print(f"    Status: {status}")
                if stack.description:
                    print(f"    {stack.description}")
                if stack.ports:
                    ports_str = ", ".join(str(p) for p in stack.ports)
                    print(f"    Ports: {ports_str}")
                if stack.requires:
                    deps = ", ".join(stack.requires)
                    print(f"    Requires: {deps}")

    except Exception as e:
        print(f"\033[31mError: {e}\033[0m")
        sys.exit(1)


def registry_install(args):
    """Install a stack"""
    name = args[0]

    # Parse env vars
    env_vars = {}
    i = 1
    while i < len(args):
        if args[i] == "-e" and i + 1 < len(args):
            kv = args[i + 1]
            if "=" in kv:
                key, value = kv.split("=", 1)
                env_vars[key] = value
            i += 2
        else:
            i += 1

    print(f"Installing {name}...")
    result = RegistryManager.install(name, env_vars if env_vars else None)

    if result["success"]:
        print(f"\033[32m✓ {result['message']}\033[0m")

        # Check if there are env vars that need to be set
        stack = RegistryManager.get_stack(name)
        if stack and stack.env_vars:
            missing = [v for v in stack.env_vars if v not in env_vars]
            if missing:
                print(f"\n\033[33mRequired environment variables:\033[0m")
                for var in missing:
                    print(f"  {var}=<value>")
                print(f"\nEdit the .env file in {RegistryManager.get_install_path(name)}")
    else:
        print(f"\033[31m✗ {result['message']}\033[0m")
        sys.exit(1)


def registry_uninstall(name):
    """Uninstall a stack"""
    confirm = input(f"Uninstall {name}? This will stop and remove all files. [y/N]: ")
    if confirm.lower() != 'y':
        print("Cancelled")
        return

    print(f"Uninstalling {name}...")
    result = RegistryManager.uninstall(name)

    if result["success"]:
        print(f"\033[32m✓ {result['message']}\033[0m")
    else:
        print(f"\033[31m✗ {result['message']}\033[0m")
        sys.exit(1)


def registry_enable(name):
    """Enable a disabled stack"""
    result = RegistryManager.enable(name)

    if result["success"]:
        print(f"\033[32m✓ {result['message']}\033[0m")
    else:
        print(f"\033[31m✗ {result['message']}\033[0m")
        sys.exit(1)


def registry_disable(name):
    """Disable a stack"""
    print(f"Disabling {name}...")
    result = RegistryManager.disable(name)

    if result["success"]:
        print(f"\033[32m✓ {result['message']}\033[0m")
    else:
        print(f"\033[31m✗ {result['message']}\033[0m")
        sys.exit(1)


def registry_start(name):
    """Start a stack"""
    print(f"Starting {name}...")
    result = RegistryManager.start(name)

    if result["success"]:
        print(f"\033[32m✓ {result['message']}\033[0m")
    else:
        print(f"\033[31m✗ {result['message']}\033[0m")
        sys.exit(1)


def registry_stop(name):
    """Stop a stack"""
    print(f"Stopping {name}...")
    result = RegistryManager.stop(name)

    if result["success"]:
        print(f"\033[32m✓ {result['message']}\033[0m")
    else:
        print(f"\033[31m✗ {result['message']}\033[0m")
        sys.exit(1)


def registry_logs(name, follow=False):
    """Show logs for a stack"""
    result = RegistryManager.get_logs(name, lines=100, follow=follow)

    if not result["success"]:
        print(f"\033[31m✗ {result['message']}\033[0m")
        sys.exit(1)

    if follow:
        # Execute command interactively
        import subprocess
        subprocess.run(result["command"])
    else:
        print(result.get("logs", ""))


def registry_info(name):
    """Show detailed information about a stack"""
    stack = RegistryManager.get_stack(name)

    if not stack:
        print(f"\033[31mStack '{name}' not found in registry\033[0m")
        sys.exit(1)

    print(f"\n\033[1;36m{stack.name}\033[0m")
    print("=" * 50)

    print(f"\nCategory:    {stack.category}")
    print(f"Path:        {stack.path}")

    if stack.description:
        print(f"Description: {stack.description}")

    # Status
    if not stack.installed:
        status = "Not installed"
    elif not stack.enabled:
        status = "Disabled"
    elif stack.running:
        status = "\033[32mRunning\033[0m"
    else:
        status = "\033[31mStopped\033[0m"
    print(f"Status:      {status}")

    if stack.installed:
        print(f"Install dir: {RegistryManager.get_install_path(name)}")

    if stack.ports:
        print(f"\nPorts: {', '.join(str(p) for p in stack.ports)}")

    if stack.requires:
        print(f"\nDependencies:")
        for req in stack.requires:
            req_stack = RegistryManager.get_stack(req)
            if req_stack and req_stack.installed:
                print(f"  \033[32m✓ {req}\033[0m")
            else:
                print(f"  \033[31m✗ {req} (not installed)\033[0m")

    if stack.env_vars:
        print(f"\nEnvironment variables:")
        for var in stack.env_vars:
            print(f"  {var}")
