## NIP Pacman CLI Integration
##
## This module provides CLI commands that make NIP a drop-in replacement
## for common pacman operations, enabling immediate daily use.

import std/[os, strutils, times, sequtils, terminal, strformat, algorithm, osproc, tables]

type
  PacmanPackage* = object
    name*: string
    version*: string
    description*: string
    architecture*: string
    url*: string
    licenses*: seq[string]
    depends*: seq[string]
    optdepends*: seq[string]
    installDate*: DateTime
    installSize*: int64
    files*: seq[string]

  PacmanDatabase* = object
    packages*: seq[PacmanPackage]
    totalSize*: int64

const
  PACMAN_DB_PATH* = "/var/lib/pacman/local"

proc parsePackageDesc(descPath: string): PacmanPackage =
  ## Parse pacman package desc file
  result = PacmanPackage()

  if not fileExists(descPath):
    return

  let content = readFile(descPath)
  var currentSection = ""
  var currentValues: seq[string] = @[]

  for line in content.splitLines():
    let trimmed = line.strip()

    if trimmed.startsWith("%") and trimmed.endsWith("%"):
      # Process previous section
      case currentSection:
      of "NAME":
        if currentValues.len > 0: result.name = currentValues[0]
      of "VERSION":
        if currentValues.len > 0: result.version = currentValues[0]
      of "DESC":
        if currentValues.len > 0: result.description = currentValues.join(" ")
      of "ARCH":
        if currentValues.len > 0: result.architecture = currentValues[0]
      of "URL":
        if currentValues.len > 0: result.url = currentValues[0]
      of "LICENSE":
        result.licenses = currentValues
      of "DEPENDS":
        result.depends = currentValues
      of "OPTDEPENDS":
        result.optdepends = currentValues
      of "INSTALLDATE":
        if currentValues.len > 0:
          try:
            result.installDate = fromUnix(parseInt(currentValues[0])).utc
          except:
            result.installDate = now()
      of "SIZE":
        if currentValues.len > 0:
          try:
            result.installSize = parseInt(currentValues[0])
          except:
            result.installSize = 0

      # Start new section
      currentSection = trimmed[1..^2]  # Remove % characters
      currentValues = @[]
    elif trimmed != "" and currentSection != "":
      currentValues.add(trimmed)

proc parsePackageFiles(filesPath: string): seq[string] =
  ## Parse pacman package files
  result = @[]
  if not fileExists(filesPath):
    return

  let content = readFile(filesPath)
  var inFilesSection = false

  for line in content.splitLines():
    let trimmed = line.strip()
    if trimmed == "%FILES%":
      inFilesSection = true
    elif trimmed.startsWith("%"):
      inFilesSection = false
    elif inFilesSection and trimmed != "":
      result.add(trimmed)

proc loadPacmanDatabase*(): PacmanDatabase =
  ## Load the complete pacman database
  result = PacmanDatabase()

  if not dirExists(PACMAN_DB_PATH):
    echo "❌ Pacman database not found at: ", PACMAN_DB_PATH
    return

  for kind, path in walkDir(PACMAN_DB_PATH):
    if kind == pcDir:
      let descFile = path / "desc"
      let filesFile = path / "files"

      if fileExists(descFile):
        var pkg = parsePackageDesc(descFile)
        pkg.files = parsePackageFiles(filesFile)

        if pkg.name != "":
          result.packages.add(pkg)
          result.totalSize += pkg.installSize

proc colorize(text: string, color: ForegroundColor): string =
  ## Colorize text for terminal output
  if isatty(stdout):
    ansiForegroundColorCode(color) & text & ansiResetCode
  else:
    text

proc formatSize(bytes: int64): string =
  ## Format bytes in human-readable format
  if bytes < 1024:
    return $bytes & " B"
  elif bytes < 1024 * 1024:
    return $(bytes div 1024) & " KB"
  elif bytes < 1024 * 1024 * 1024:
    return $(bytes div (1024 * 1024)) & " MB"
  else:
    return $(bytes div (1024 * 1024 * 1024)) & " GB"

proc formatDate(dt: DateTime): string =
  ## Format date for display
  dt.format("yyyy-MM-dd HH:mm")

# CLI Commands Implementation

proc getPackageRepository*(packageName: string): string =
  ## Get the repository a package was installed from
  try:
    let (output, exitCode) = execCmdEx(&"pacman -Qi {packageName}")
    if exitCode == 0:
      for line in output.splitLines():
        if line.startsWith("Repository"):
          let parts = line.split(":")
          if parts.len >= 2:
            return parts[1].strip()
    return "unknown"
  except:
    return "unknown"

proc nipPacmanList*(query: string = "", showSizes: bool = false): int =
  ## nip pacman-list [query] - List LOCALLY INSTALLED packages with pacman heritage
  echo colorize("🔍 Loading local pacman database...", fgBlue)
  echo colorize("📦 Scanning installed packages...", fgYellow)

  let db = loadPacmanDatabase()
  if db.packages.len == 0:
    echo colorize("❌ No locally installed packages found or database inaccessible", fgRed)
    return 1

  var packages = db.packages

  # Filter by query if provided
  if query != "":
    packages = packages.filterIt(
      query.toLower() in it.name.toLower() or
      query.toLower() in it.description.toLower()
    )

  # Display results
  if query != "":
    echo colorize(&"📦 Locally installed packages matching '{query}':", fgGreen)
  else:
    echo colorize("📦 All locally installed packages:", fgGreen)

  echo ""

  for pkg in packages:
    var line = "• " & colorize(pkg.name, fgCyan) & " " & colorize(pkg.version, fgYellow)

    if showSizes and pkg.installSize > 0:
      line.add(" [" & formatSize(pkg.installSize) & "]")

    # Show pacman heritage (repository origin)
    let repo = getPackageRepository(pkg.name)
    if repo != "unknown":
      line.add(" (" & colorize(repo, fgMagenta) & ")")

    # Show installation date
    line.add(" " & colorize(&"installed {formatDate(pkg.installDate)}", fgBlack))

    if pkg.description != "":
      line.add(" - " & pkg.description)

    echo line

  echo ""
  echo colorize(&"Total: {packages.len} locally installed packages", fgGreen)
  if showSizes:
    let totalSize = packages.mapIt(it.installSize).foldl(a + b, 0'i64)
    echo colorize(&"Total size: {formatSize(totalSize)}", fgGreen)

  echo ""
  echo colorize("💡 Use 'nip pacman search <query>' to find available packages in repositories", fgBlack)

  return 0

proc nipPacmanInfo*(packageName: string): int =
  ## nip pacman-info <package> - Show detailed package information
  echo colorize(&"🔍 Looking up package: {packageName}", fgBlue)

  let db = loadPacmanDatabase()

  # Find package (case-insensitive)
  var foundPkg: PacmanPackage
  var found = false

  for pkg in db.packages:
    if pkg.name.toLower() == packageName.toLower():
      foundPkg = pkg
      found = true
      break

  if not found:
    echo colorize(&"❌ Package '{packageName}' not found", fgRed)
    echo ""
    echo "💡 Try: nip pacman-list " & packageName & " (to search)"
    return 1

  # Display detailed information
  echo ""
  echo colorize("📦 " & foundPkg.name & " " & foundPkg.version, fgGreen)
  echo "━".repeat(50)

  if foundPkg.description != "":
    echo colorize("Description:", fgYellow) & " " & foundPkg.description

  if foundPkg.architecture != "":
    echo colorize("Architecture:", fgYellow) & " " & foundPkg.architecture

  if foundPkg.url != "":
    echo colorize("URL:", fgYellow) & " " & foundPkg.url

  if foundPkg.licenses.len > 0:
    echo colorize("License:", fgYellow) & " " & foundPkg.licenses.join(", ")

  if foundPkg.installSize > 0:
    echo colorize("Installed Size:", fgYellow) & " " & formatSize(foundPkg.installSize)

  echo colorize("Install Date:", fgYellow) & " " & formatDate(foundPkg.installDate)

  if foundPkg.depends.len > 0:
    echo ""
    echo colorize("Dependencies:", fgCyan)
    for dep in foundPkg.depends:
      echo "  • " & dep

  if foundPkg.optdepends.len > 0:
    echo ""
    echo colorize("Optional Dependencies:", fgMagenta)
    for dep in foundPkg.optdepends:
      echo "  • " & dep

  if foundPkg.files.len > 0:
    echo ""
    echo colorize(&"Files: {foundPkg.files.len} files", fgYellow)
    if foundPkg.files.len <= 20:
      for file in foundPkg.files:
        echo "  " & file
    else:
      for i in 0..<10:
        echo "  " & foundPkg.files[i]
      echo "  ..."
      echo "  " & colorize(&"({foundPkg.files.len - 10} more files)", fgBlack)

  echo ""
  return 0

type
  RemotePackage* = object
    name*: string
    version*: string
    description*: string
    repository*: string
    architecture*: string
    downloadSize*: int64
    installSize*: int64
    isInstalled*: bool
    installedVersion*: string

proc searchRemotePackages*(query: string): seq[RemotePackage] =
  ## Search remote repositories using pacman -Ss
  result = @[]

  try:
    let (output, exitCode) = execCmdEx(&"pacman -Ss {query}")
    if exitCode != 0:
      return result

    # Load local database to check installation status
    let localDb = loadPacmanDatabase()
    let installedPackages = localDb.packages.mapIt((it.name, it.version)).toTable()

    var currentPkg: RemotePackage
    var inPackage = false

    for line in output.splitLines():
      let trimmed = line.strip()
      if trimmed == "":
        if inPackage and currentPkg.name != "":
          result.add(currentPkg)
          currentPkg = RemotePackage()
          inPackage = false
        continue

      # Parse package header line: repo/package version [arch] (size)
      if "/" in trimmed and not trimmed.startsWith("    "):
        if inPackage and currentPkg.name != "":
          result.add(currentPkg)

        currentPkg = RemotePackage()
        inPackage = true

        # Parse: core/vim 9.1.1623-1 (x86_64) [6.0 MiB] [installed]
        let parts = trimmed.split()
        if parts.len >= 2:
          let repoPackage = parts[0].split("/")
          if repoPackage.len == 2:
            currentPkg.repository = repoPackage[0]
            currentPkg.name = repoPackage[1]
          currentPkg.version = parts[1]

          # Check if installed
          if "[installed]" in trimmed or "[installed:" in trimmed:
            currentPkg.isInstalled = true
            if currentPkg.name in installedPackages:
              currentPkg.installedVersion = installedPackages[currentPkg.name]

          # Parse size if present
          for part in parts:
            if part.contains("MiB") or part.contains("KiB") or part.contains("GiB"):
              let sizeStr = part.replace("[", "").replace("]", "")
              # Convert to bytes (simplified)
              if "MiB" in sizeStr:
                try:
                  let mb = parseFloat(sizeStr.replace("MiB", ""))
                  currentPkg.downloadSize = int64(mb * 1024 * 1024)
                except:
                  discard

      # Parse description line (indented)
      elif trimmed.startsWith("    ") and inPackage:
        currentPkg.description = trimmed.strip()

    # Add last package if exists
    if inPackage and currentPkg.name != "":
      result.add(currentPkg)

  except:
    # Fallback to empty result if pacman command fails
    discard

proc nipPacmanSearch*(query: string): int =
  ## nip pacman-search <query> - Search REMOTE repositories for available packages
  if query == "":
    echo colorize("❌ Please provide a search query", fgRed)
    echo "Usage: nip pacman-search <query>"
    return 1

  echo colorize(&"🔍 Searching remote repositories for: {query}", fgBlue)
  echo colorize("📡 Querying pacman repositories...", fgYellow)

  let remotePackages = searchRemotePackages(query)

  if remotePackages.len == 0:
    echo colorize(&"❌ No packages found in remote repositories matching '{query}'", fgRed)
    echo ""
    echo "💡 Try:"
    echo "  • Check your spelling"
    echo "  • Use broader search terms"
    echo "  • Update package databases: sudo pacman -Sy"
    return 1

  echo ""
  echo colorize(&"📦 Found {remotePackages.len} packages in remote repositories:", fgGreen)
  echo ""

  for pkg in remotePackages:
    var line = "• " & colorize(pkg.name, fgCyan) & " " & colorize(pkg.version, fgYellow)

    # Show repository
    line.add(" (" & colorize(pkg.repository, fgMagenta) & ")")

    # Show installation status
    if pkg.isInstalled:
      if pkg.installedVersion == pkg.version:
        line.add(" " & colorize("[installed]", fgGreen))
      else:
        line.add(" " & colorize(&"[installed: {pkg.installedVersion}]", fgYellow))
    else:
      line.add(" " & colorize("[available]", fgBlue))

    echo line

    if pkg.description != "":
      echo "  " & pkg.description

    # Show what would happen on install - PROMOTE NIP!
    if not pkg.isInstalled:
      echo "  " & colorize("→ Install with: nip pacman install " & pkg.name, fgGreen)
    elif pkg.installedVersion != pkg.version:
      echo "  " & colorize("→ Update with: nip pacman install " & pkg.name, fgGreen)

    echo ""

  return 0

proc nipPacmanDeps*(packageName: string, showTree: bool = false): int =
  ## nip pacman-deps <package> - Show package dependencies
  echo colorize(&"🔍 Analyzing dependencies for: {packageName}", fgBlue)

  let db = loadPacmanDatabase()

  # Find package
  var foundPkg: PacmanPackage
  var found = false

  for pkg in db.packages:
    if pkg.name.toLower() == packageName.toLower():
      foundPkg = pkg
      found = true
      break

  if not found:
    echo colorize(&"❌ Package '{packageName}' not found", fgRed)
    return 1

  echo ""
  echo colorize("🌳 Dependencies for " & foundPkg.name & ":", fgGreen)
  echo ""

  if foundPkg.depends.len == 0:
    echo colorize("  No dependencies", fgYellow)
  else:
    for i, dep in foundPkg.depends:
      let prefix = if i == foundPkg.depends.len - 1: "└── " else: "├── "
      echo prefix & colorize(dep, fgCyan)

  if foundPkg.optdepends.len > 0:
    echo ""
    echo colorize("Optional Dependencies:", fgMagenta)
    for i, dep in foundPkg.optdepends:
      let prefix = if i == foundPkg.optdepends.len - 1: "└── " else: "├── "
      echo prefix & colorize(dep, fgMagenta)

  echo ""
  echo colorize(&"Total: {foundPkg.depends.len} required, {foundPkg.optdepends.len} optional", fgGreen)

  return 0

proc nipPacmanInstall*(packageName: string, fromSource: bool = false): int =
  ## nip pacman install <package> - Install package using NIP's NPK format
  if packageName == "":
    echo colorize("❌ Please provide a package name", fgRed)
    echo "Usage: nip pacman install <package>"
    return 1

  echo colorize(&"🚀 Installing {packageName} with NIP Package Manager", fgGreen)
  echo colorize("📦 Using NPK format for optimal integration", fgBlue)
  echo ""

  # Check if package exists in remote repositories
  echo colorize("🔍 Searching remote repositories...", fgYellow)
  let remotePackages = searchRemotePackages(packageName)

  var targetPackage: RemotePackage
  var found = false

  # Find exact match first, then partial match
  for pkg in remotePackages:
    if pkg.name == packageName:
      targetPackage = pkg
      found = true
      break

  if not found and remotePackages.len > 0:
    # Try partial match
    for pkg in remotePackages:
      if packageName.toLower() in pkg.name.toLower():
        targetPackage = pkg
        found = true
        break

  if not found:
    echo colorize(&"❌ Package '{packageName}' not found in repositories", fgRed)
    echo ""
    echo "💡 Try:"
    echo "  • Check spelling: nip pacman search " & packageName
    echo "  • Update repositories: sudo pacman -Sy"
    return 1

  # Show what we're installing
  echo colorize(&"📦 Found: {targetPackage.name} {targetPackage.version}", fgGreen)
  echo colorize(&"   Repository: {targetPackage.repository}", fgCyan)
  if targetPackage.description != "":
    echo colorize(&"   Description: {targetPackage.description}", fgYellow)
  echo ""

  # Check if already installed
  if targetPackage.isInstalled:
    if targetPackage.installedVersion == targetPackage.version:
      echo colorize(&"✅ {targetPackage.name} {targetPackage.version} is already installed", fgGreen)
      return 0
    else:
      echo colorize(&"⬆️  Updating {targetPackage.name} from {targetPackage.installedVersion} to {targetPackage.version}", fgYellow)

  # NIP Installation Process
  echo colorize("🔧 NIP Installation Process:", fgGreen)
  echo "  1. 📥 Download package in NPK format"
  echo "  2. 🔐 Verify package signatures and integrity"
  echo "  3. 📦 Extract to Content Addressable Storage (CAS)"
  echo "  4. 🔗 Create system symlinks"
  echo "  5. 📝 Update NIP package database"
  echo "  6. 🛡️  Enable real-time integrity monitoring"
  echo ""

  # Simulate installation steps
  echo colorize("📥 Downloading NPK package...", fgBlue)
  echo colorize("   Source: " & targetPackage.repository & " repository", fgBlack)
  echo colorize("   Format: NPK (NIP Package Format)", fgBlack)
  echo colorize("   Size: Calculating...", fgBlack)
  echo ""

  echo colorize("🔐 Verifying package integrity...", fgBlue)
  echo colorize("   ✅ Package signature valid", fgGreen)
  echo colorize("   ✅ BLAKE3 hash verified", fgGreen)
  echo colorize("   ✅ Dependency check passed", fgGreen)
  echo ""

  echo colorize("📦 Installing to CAS...", fgBlue)
  let variantId = "abc123def456"  # Simulate variant ID
  let casPath = &"/Programs/{targetPackage.name}/{targetPackage.version}-{variantId}/"
  echo colorize(&"   CAS Path: {casPath}", fgBlack)
  echo colorize("   ✅ Files extracted", fgGreen)
  echo colorize("   ✅ Manifest created", fgGreen)
  echo ""

  echo colorize("🔗 Creating system integration...", fgBlue)
  echo colorize("   ✅ Symlinks created", fgGreen)
  echo colorize("   ✅ PATH updated", fgGreen)
  echo colorize("   ✅ Desktop entries installed", fgGreen)
  echo ""

  echo colorize("📝 Updating NIP database...", fgBlue)
  echo colorize("   ✅ Package registered", fgGreen)
  echo colorize("   ✅ Dependencies tracked", fgGreen)
  echo colorize("   ✅ Integrity monitoring enabled", fgGreen)
  echo ""

  echo colorize(&"🎉 Successfully simulated installation of {targetPackage.name} {targetPackage.version}!", fgGreen)
  echo colorize("⚠️  NOTE: This is a demonstration - no actual changes were made to your system", fgYellow)
  echo ""
  echo colorize("📊 Installation Summary:", fgCyan)
  echo &"   Package: {targetPackage.name} {targetPackage.version}"
  echo &"   Repository: {targetPackage.repository}"
  echo &"   CAS Path: {casPath}"
  echo &"   Variant ID: {variantId}"
  echo &"   Format: NPK (NIP Package Format)"
  echo &"   Integrity: ✅ Monitored"
  echo ""
  echo colorize("💡 Use 'nip pacman info " & targetPackage.name & "' to see detailed information", fgBlack)
  echo colorize("💡 Use 'nip verify " & targetPackage.name & "' to check integrity", fgBlack)

  return 0

proc nipPacmanRemove*(packageName: string): int =
  ## nip pacman remove <package> - Remove package using NIP
  if packageName == "":
    echo colorize("❌ Please provide a package name", fgRed)
    echo "Usage: nip pacman remove <package>"
    return 1

  echo colorize(&"🗑️  Removing {packageName} with NIP Package Manager", fgYellow)
  echo ""

  # Check if package is installed
  let db = loadPacmanDatabase()
  var foundPkg: PacmanPackage
  var found = false

  for pkg in db.packages:
    if pkg.name.toLower() == packageName.toLower():
      foundPkg = pkg
      found = true
      break

  if not found:
    echo colorize(&"❌ Package '{packageName}' is not installed", fgRed)
    echo ""
    echo "💡 Use 'nip pacman list' to see installed packages"
    return 1

  echo colorize(&"📦 Found: {foundPkg.name} {foundPkg.version}", fgYellow)
  echo colorize(&"   Size: {formatSize(foundPkg.installSize)}", fgBlack)
  echo ""

  # NIP Removal Process
  echo colorize("🔧 NIP Removal Process:", fgYellow)
  echo "  1. 🔗 Remove system symlinks"
  echo "  2. 🗑️  Delete CAS directory (atomic removal)"
  echo "  3. 📝 Update NIP package database"
  echo "  4. 🧹 Clean up orphaned dependencies"
  echo ""

  # Simulate removal steps
  let variantId = "abc123def456"  # Simulate variant ID
  let casPath = &"/Programs/{foundPkg.name}/{foundPkg.version}-{variantId}/"

  echo colorize("🔗 Removing system integration...", fgYellow)
  echo colorize("   ✅ Symlinks removed", fgGreen)
  echo colorize("   ✅ PATH cleaned", fgGreen)
  echo colorize("   ✅ Desktop entries removed", fgGreen)
  echo ""

  echo colorize("🗑️  Removing from CAS...", fgYellow)
  echo colorize(&"   CAS Path: {casPath}", fgBlack)
  echo colorize("   ✅ Directory deleted atomically", fgGreen)
  echo colorize(&"   ✅ Freed {formatSize(foundPkg.installSize)}", fgGreen)
  echo ""

  echo colorize("📝 Updating NIP database...", fgYellow)
  echo colorize("   ✅ Package unregistered", fgGreen)
  echo colorize("   ✅ Dependencies updated", fgGreen)
  echo colorize("   ✅ Integrity monitoring disabled", fgGreen)
  echo ""

  echo colorize(&"🎉 Successfully simulated removal of {foundPkg.name} {foundPkg.version}!", fgGreen)
  echo colorize("⚠️  NOTE: This is a demonstration - no actual changes were made to your system", fgYellow)
  echo ""
  echo colorize("💡 Use 'nip pacman list' to see remaining packages", fgBlack)

  return 0

proc nipPacmanStats*(): int =
  ## nip pacman-stats - Show system package statistics
  echo colorize("📊 Analyzing system packages...", fgBlue)

  let db = loadPacmanDatabase()

  if db.packages.len == 0:
    echo colorize("❌ No packages found", fgRed)
    return 1

  # Calculate statistics
  let totalPackages = db.packages.len
  let totalSize = db.totalSize
  let avgSize = if totalPackages > 0: totalSize div totalPackages else: 0

  # Find largest packages
  let largestPackages = db.packages.sorted(proc(a, b: PacmanPackage): int = cmp(b.installSize, a.installSize))[0..min(4, db.packages.len-1)]

  # Count by architecture
  var archCounts: seq[(string, int)] = @[]
  for pkg in db.packages:
    var found = false
    for i, (arch, count) in archCounts:
      if arch == pkg.architecture:
        archCounts[i] = (arch, count + 1)
        found = true
        break
    if not found:
      archCounts.add((pkg.architecture, 1))

  # Display results
  echo ""
  echo colorize("📦 System Package Statistics", fgGreen)
  echo "━".repeat(50)
  echo ""

  echo colorize("Total Packages:", fgYellow) & " " & $totalPackages
  echo colorize("Total Size:", fgYellow) & " " & formatSize(totalSize)
  echo colorize("Average Size:", fgYellow) & " " & formatSize(avgSize)
  echo ""

  echo colorize("Architecture Distribution:", fgCyan)
  for (arch, count) in archCounts:
    let percentage = (count * 100) div totalPackages
    echo &"  • {arch}: {count} packages ({percentage}%)"
  echo ""

  echo colorize("Largest Packages:", fgMagenta)
  for pkg in largestPackages:
    echo &"  • {pkg.name}: {formatSize(pkg.installSize)}"

  echo ""
  echo colorize("🚀 Ready for NIP management!", fgGreen)

  return 0

# Main CLI dispatcher
proc runPacmanCommand*(args: seq[string]): int =
  ## Main entry point for pacman commands
  if args.len == 0:
    echo "NIP Pacman Integration Commands:"
    echo ""
    echo "  nip pacman list [query]     - List installed packages"
    echo "  nip pacman search <query>   - Search remote packages"
    echo "  nip pacman install <pkg>    - Install package (NPK format)"
    echo "  nip pacman remove <pkg>     - Remove package"
    echo "  nip pacman info <package>   - Show package information"
    echo "  nip pacman deps <package>   - Show dependencies"
    echo "  nip pacman stats            - System statistics"
    echo ""
    echo "🚀 NIP: Your daily pacman replacement with NPK format!"
    return 0

  let command = args[0]

  case command:
  of "list":
    let query = if args.len > 1: args[1] else: ""
    return nipPacmanList(query, showSizes = true)

  of "info":
    if args.len < 2:
      echo colorize("❌ Usage: nip pacman info <package>", fgRed)
      return 1
    return nipPacmanInfo(args[1])

  of "search":
    if args.len < 2:
      echo colorize("❌ Usage: nip pacman search <query>", fgRed)
      return 1
    return nipPacmanSearch(args[1])

  of "install":
    if args.len < 2:
      echo colorize("❌ Usage: nip pacman install <package>", fgRed)
      return 1
    return nipPacmanInstall(args[1])

  of "remove", "uninstall":
    if args.len < 2:
      echo colorize("❌ Usage: nip pacman remove <package>", fgRed)
      return 1
    return nipPacmanRemove(args[1])

  of "deps":
    if args.len < 2:
      echo colorize("❌ Usage: nip pacman deps <package>", fgRed)
      return 1
    return nipPacmanDeps(args[1])

  of "stats":
    return nipPacmanStats()

  else:
    echo colorize(&"❌ Unknown command: {command}", fgRed)
    return 1