## container_commands.nim
## CLI commands for container operations

import std/[strutils, os, times]
import ../build/container_manager
import ../build/container_builder

proc containerInfoCommand*(): int =
  ## Show container runtime information
  let cm = newContainerManager()

  if not cm.isAvailable():
    echo "❌ No container runtime detected"
    echo ""
    echo "NIP supports the following container runtimes:"
    echo "  • Podman (recommended) - rootless, daemonless"
    echo "  • Docker - widely supported"
    echo "  • containerd (via nerdctl) - lightweight"
    echo ""
    echo "Install Podman:"
    echo "  Arch Linux: sudo pacman -S podman"
    echo "  Debian/Ubuntu: sudo apt install podman"
    echo "  Fedora: sudo dnf install podman"
    return 1

  echo cm.getContainerBuildInfo()
  return 0

proc containerListCommand*(): int =
  ## List available container images
  let cm = newContainerManager()

  if not cm.isAvailable():
    echo "❌ No container runtime available"
    return 1

  echo "Available Container Images:"
  echo "==========================="
  echo ""

  let images = cm.listBuildImages()

  if images.len == 0:
    echo "No build images found"
    echo ""
    echo "Pull a build image:"
    echo "  nip container pull gentoo"
    echo "  nip container pull nix"
    return 0

  for image in images:
    echo "  • ", image

  echo ""
  echo "Total: ", images.len, " images"
  return 0

proc containerPullCommand*(environment: string): int =
  ## Pull container image for build environment
  let cm = newContainerManager()

  if not cm.isAvailable():
    echo "❌ No container runtime available"
    return 1

  # Parse environment
  let env = case environment.toLower()
    of "gentoo": beGentoo
    of "nix": beNix
    of "pkgsrc": bePkgsrc
    of "alpine": beAlpine
    of "debian": beDebian
    else:
      echo "❌ Unknown environment: ", environment
      echo "Available: gentoo, nix, pkgsrc, alpine, debian"
      return 1

  let (success, message) = cm.ensureBuildImage(env)

  if success:
    echo "✅ ", message
    return 0
  else:
    echo "❌ ", message
    return 1

proc containerCleanCommand*(): int =
  ## Clean up stopped containers
  let cm = newContainerManager()

  if not cm.isAvailable():
    echo "❌ No container runtime available"
    return 1

  echo "Cleaning up stopped containers..."
  let removed = cm.cleanupBuildContainers()

  echo "✅ Cleanup complete"
  if removed > 0:
    echo "Removed ", removed, " containers"

  return 0

proc containerDetectCommand*(): int =
  ## Detect available container runtimes
  echo "Detecting Container Runtimes:"
  echo "============================="
  echo ""

  let runtimes = getAllRuntimes()

  if runtimes.len == 0:
    echo "❌ No container runtimes detected"
    echo ""
    echo "Install a container runtime:"
    echo "  • Podman (recommended): sudo pacman -S podman"
    echo "  • Docker: sudo pacman -S docker"
    return 1

  for runtime in runtimes:
    echo "✓ ", runtime.runtime
    echo "  Path: ", runtime.path
    echo "  Version: ", runtime.version
    echo "  Rootless: ", runtime.rootless
    echo ""

  echo "Preferred runtime: ", runtimes[0].runtime
  return 0

proc containerBuildCommand*(
  packageName: string,
  environment: string = "gentoo",
  useFlags: seq[string] = @[],
  outputDir: string = ""
): int =
  ## Build package in container
  let cm = newContainerManager()

  if not cm.isAvailable():
    echo "❌ No container runtime available"
    return 1

  # Parse environment
  let env = case environment.toLower()
    of "gentoo": beGentoo
    of "nix": beNix
    of "pkgsrc": bePkgsrc
    of "alpine": beAlpine
    of "debian": beDebian
    else:
      echo "❌ Unknown environment: ", environment
      return 1

  # Ensure image is available
  let (imageReady, imageMsg) = cm.ensureBuildImage(env)
  if not imageReady:
    echo "❌ Failed to prepare build image: ", imageMsg
    return 1

  # Prepare build configuration
  let output = if outputDir.len > 0: outputDir else: getTempDir() / "nip-build"

  var config = ContainerBuildConfig(
    environment: env,
    packageName: packageName,
    outputDir: output,
    useFlags: useFlags,
    keepContainer: false
  )

  echo "🐳 Building ", packageName, " in ", environment, " container..."
  echo ""

  # Build
  let buildResult = cm.buildInContainer(config)

  if buildResult.success:
    echo ""
    echo "✅ Build completed successfully!"
    echo "Build time: ", buildResult.buildTime.inSeconds, "s"

    if buildResult.artifacts.len > 0:
      echo ""
      echo "Artifacts:"
      for artifact in buildResult.artifacts:
        echo "  • ", artifact

    return 0
  else:
    echo ""
    echo "❌ Build failed: ", buildResult.message
    if buildResult.logs.len > 0:
      echo ""
      echo "Build logs:"
      echo buildResult.logs
    return 1

proc containerHelpCommand*(): int =
  ## Show container command help
  echo """
NIP Container Commands
======================

Container-based builds provide isolated, reproducible build environments.

Commands:
  nip container info              Show container runtime information
  nip container detect            Detect available container runtimes
  nip container list              List available build images
  nip container pull <env>        Pull build image (gentoo/nix/pkgsrc)
  nip container clean             Clean up stopped containers
  nip container build <pkg>       Build package in container
  nip container help              Show this help

Examples:
  # Check container support
  nip container info

  # Pull Gentoo build image
  nip container pull gentoo

  # Build package in container
  nip container build vim --env=gentoo --use=python,ruby

  # Clean up
  nip container clean

Container Runtimes:
  • Podman (recommended) - rootless, daemonless, secure
  • Docker - widely supported, requires daemon
  • containerd - lightweight, via nerdctl

Install Podman:
  Arch Linux:    sudo pacman -S podman
  Debian/Ubuntu: sudo apt install podman
  Fedora:        sudo dnf install podman

For more information:
  https://git.maiwald.work/Nexus/NexusToolKit/wiki/Container-Builds
"""
  return 0
