"""Console entry point: dispatcher + plugin management subcommands.

Usage:
    statusline                         # dispatcher mode
    statusline list                    # show installed plugins
    statusline install <path> [--as NN-name]
    statusline uninstall <name>
    statusline install-builtins        # install/update built-in plugins
"""

import sys
from pathlib import Path

from .dispatcher import dispatch
from .plugin import ensure_plugin, install, install_builtins, list_plugins, uninstall


def cmd_list() -> None:
    """Show installed plugins."""
    plugins = list_plugins()
    if not plugins:
        print("No plugins installed.")
        return

    for path, name, enabled in plugins:
        stem = path.name.rsplit(".", 1)[0] if "." in path.name else path.name
        status = "enabled" if enabled else "disabled"
        print(f"  {stem:<20s} {status:<10s} {path}")


def cmd_install(args: list[str]) -> None:
    """Copy a plugin into statusline.d/."""
    src = Path(args[0])

    dest_name = None
    for i, a in enumerate(args[1:], 1):
        if a == "--as" and i + 1 <= len(args[1:]):
            dest_name = args[i + 1]
            break

    try:
        dest = install(src, dest_name)
        print(f"Installed {dest}")
    except (FileNotFoundError, ValueError) as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def cmd_uninstall(args: list[str]) -> None:
    """Remove a plugin from statusline.d/ by name match."""
    name = args[0]
    removed = uninstall(name)
    if removed:
        print(f"Removed {removed}")
    else:
        print(f"Plugin {name!r} not found", file=sys.stderr)
        sys.exit(1)


def cmd_install_builtins() -> None:
    """Install or update all built-in plugins."""
    installed = install_builtins()
    for p in installed:
        print(f"Installed {p}")


def main() -> None:
    if len(sys.argv) < 2:
        dispatch()
        return

    cmd = sys.argv[1]
    if cmd == "list":
        cmd_list()
    elif cmd == "install":
        if len(sys.argv) < 3:
            print("Usage: statusline install <path> [--as NN-name]", file=sys.stderr)
            sys.exit(1)
        cmd_install(sys.argv[2:])
    elif cmd == "uninstall":
        if len(sys.argv) < 3:
            print("Usage: statusline uninstall <name>", file=sys.stderr)
            sys.exit(1)
        cmd_uninstall(sys.argv[2:])
    elif cmd == "install-builtins":
        cmd_install_builtins()
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
