#!/usr/bin/env python3
import sys
import pkgutil
import importlib
import json
import urllib.request
from importlib.metadata import version, PackageNotFoundError
from packaging.version import Version
from babicli.colors import ok, warn, err, info
import babicli.plugins


# ---------------------------------------------------------
# Program name and dynamic version lookup
# ---------------------------------------------------------
PROGRAM_NAME = "babicli"

try:
    PROGRAM_VERSION = version(PROGRAM_NAME)
except PackageNotFoundError:
    PROGRAM_VERSION = "unknown"


# ---------------------------------------------------------
# Update check (fixed to avoid wrong warnings)
# ---------------------------------------------------------
def check_for_updates():
    try:
        with urllib.request.urlopen(
            "https://pypi.org/pypi/babicli/json",
            timeout=2
        ) as u:
            data = json.load(u)

        latest = data["info"]["version"]

        # Only warn when PyPI version is actually newer
        if Version(latest) > Version(PROGRAM_VERSION):
            warn(f"A new version of babicli is available: {PROGRAM_VERSION} → {latest}")
            print("Update with: pip install --upgrade babicli\n")

    except Exception:
        # Ignore offline/error
        return


# ---------------------------------------------------------
# Plugin loader (unchanged, simple, automatic)
# ---------------------------------------------------------
def load_plugins():
    plugins = {}

    for mod in pkgutil.iter_modules(babicli.plugins.__path__):
        name = mod.name.lower()

        try:
            module = importlib.import_module(f"babicli.plugins.{name}")
            plugins[name] = module
        except Exception as e:
            err(f"Failed to load plugin '{name}': {e}")

    return plugins


# ---------------------------------------------------------
# Help output (simple, clean)
# ---------------------------------------------------------
def cmd_help(plugins):
    print(f"{PROGRAM_NAME} {PROGRAM_VERSION}\n")
    print("Available commands:")

    for p in sorted(plugins):
        print(f"  {p}")

    print("\nUsage:")
    print(f"  {PROGRAM_NAME} <command>\n")

    print("Plugin system:")
    print("  Place new plugins in: babicli/plugins/")
    print("  Each plugin must define a function: run()")


# ---------------------------------------------------------
# Main entry point
# ---------------------------------------------------------
def main():
    check_for_updates()
    plugins = load_plugins()

    # No arguments → show help
    if len(sys.argv) < 2:
        cmd_help(plugins)
        return

    cmd = sys.argv[1].lower()

    # Built-in help
    if cmd in ("help", "-h", "--help"):
        cmd_help(plugins)
        return

    # Plugin execution
    if cmd in plugins:
        try:
            plugins[cmd].run()
        except Exception as e:
            err(f"Plugin error: {e}")
        return

    # Unknown command
    err(f"Unknown command: {cmd}")
    warn("Use 'babicli help' for available commands.")


if __name__ == "__main__":
    main()
