#!/usr/bin/env python3
import sys
import pkgutil
import importlib
import json
import urllib.request
from babicli.colors import ok, warn, err, info
import babicli.plugins
import time
import random

PROGRAM_NAME = "babicli"
VERSION = "0.1.9"

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"]
    except Exception:
        return
    
    if latest != VERSION:
        warn(f"A new version of babicli is available: {VERSION} → {latest}")
        print("Update with: pip install --upgrade babicli\n")

def load_plugins():
    plugins = {}
    for mod in pkgutil.iter_modules(babicli.plugins.__path__):
        name = mod.name.lower()
        module = importlib.import_module(f"babicli.plugins.{name}")
        plugins[name] = module
    return plugins

def cmd_help(plugins):
    print(f"""{PROGRAM_NAME} {VERSION}

Available commands:
  modules      List loaded plugins
  bench        System benchmark
  doctor       Diagnose system issues
  netinfo      Show network information
  mgenerate    Make your own module
  sysinfo      Show system information
  ranum        Generate random number
  diskguard    looks for disk capacity issues
  updatecheck  Check for babicli updates
  Launcher     Launch from this doomsday PC
  cache
    -clear    Clear cache files
    -show     Show cache files
    -size     Show cache size

Plugin system:
  {PROGRAM_NAME} <pluginname>

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

def main():
    check_for_updates()
    plugins = load_plugins()

    if len(sys.argv) < 2:
        cmd_help(plugins)
        return

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

    if cmd in ["help", "--help", "-h"]:
        cmd_help(plugins)
        return

    if cmd in plugins:
        try:
            # FIX: Pass arguments to plugin
            args = sys.argv[2:]
            plugins[cmd].run(args)
        except Exception as e:
            err(f"Plugin error: {e}")
        return

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

if __name__ == "__main__":
    main()
