## bootstrap_commands.nim
## CLI commands for managing build tool bootstrap

import std/[strformat, strutils, options]
import ../build/[bootstrap, recipe_manager, recipe_parser]

proc bootstrapListCommand*(): int =
  ## List installed build tools
  listInstalledTools()
  return 0

proc bootstrapInstallCommand*(toolName: string): int =
  ## Install a specific build tool
  let toolType = case toolName.toLower()
    of "nix": bttNix
    of "pkgsrc": bttPkgsrc
    of "gentoo": bttGentoo
    else:
      echo fmt"❌ Unknown tool: {toolName}"
      echo "   Available: nix, pkgsrc, gentoo"
      return 1

  if isSystemToolAvailable(toolType):
    echo fmt"✅ {toolType} is already available on the system"
    return 0

  if isToolInstalled(toolType):
    echo fmt"✅ {toolType} is already installed via NIP"
    return 0

  if handleMissingTool(toolType, autoBootstrap = false):
    return 0
  else:
    return 1

proc bootstrapRemoveCommand*(toolName: string): int =
  ## Remove an installed build tool
  let toolType = case toolName.toLower()
    of "nix": bttNix
    of "pkgsrc": bttPkgsrc
    of "gentoo": bttGentoo
    else:
      echo fmt"❌ Unknown tool: {toolName}"
      echo "   Available: nix, pkgsrc, gentoo"
      return 1

  if removeInstalledTool(toolType):
    return 0
  else:
    return 1

proc bootstrapUpdateRecipesCommand*(): int =
  ## Update recipes from repository
  echo "📥 Updating bootstrap recipes..."

  let recipeManager = newRecipeManager()
  let fetchResult = recipeManager.fetchRecipes()

  if fetchResult.success:
    echo fmt"✅ {fetchResult.message}"
    if fetchResult.recipesUpdated > 0:
      echo fmt"   Updated {fetchResult.recipesUpdated} recipe(s)"
    return 0
  else:
    echo fmt"❌ {fetchResult.message}"
    return 1

proc bootstrapValidateRecipeCommand*(toolName: string): int =
  ## Validate a recipe file
  echo fmt"🔍 Validating {toolName} recipe..."

  let recipeManager = newRecipeManager()

  # Check if recipe exists
  if not recipeManager.hasRecipe(toolName):
    echo fmt"❌ Recipe not found: {toolName}"
    echo "   Try: nip bootstrap update-recipes"
    return 1

  # Load and validate recipe
  let recipeOpt = recipeManager.loadRecipe(toolName)
  if recipeOpt.isNone():
    echo fmt"❌ Failed to load recipe: {toolName}"
    return 1

  let recipe = recipeOpt.get()
  echo fmt"✅ Recipe loaded: {recipe.name} v{recipe.version}"

  # Validate recipe
  let (valid, errors) = validateRecipe(recipe)
  if not valid:
    echo "❌ Validation failed:"
    for error in errors:
      echo fmt"   • {error}"
    return 1

  echo "✅ Recipe is valid"
  echo ""
  echo "Recipe details:"
  echo fmt"  Name:        {recipe.name}"
  echo fmt"  Version:     {recipe.version}"
  echo fmt"  Tool Type:   {recipe.toolType}"
  echo fmt"  Description: {recipe.description}"
  echo fmt"  Platforms:   {recipe.platforms.len}"

  for platform in recipe.platforms:
    echo fmt"    • {platform.arch}/{platform.os}"
    echo fmt"      Binaries: {platform.binaries.len}"
    echo fmt"      Archives: {platform.archives.len}"

  if recipe.dependencies.len > 0:
    echo "  Dependencies:"
    for dep in recipe.dependencies:
      let req = if dep.required: "required" else: "optional"
      echo fmt"    • {dep.name} ({req})"

  return 0

proc bootstrapListRecipesCommand*(): int =
  ## List available recipes
  echo "📋 Available bootstrap recipes:"
  echo ""

  let recipeManager = newRecipeManager()
  let recipes = recipeManager.listAvailableRecipes()

  if recipes.len == 0:
    echo "No recipes found. Try: nip bootstrap update-recipes"
    return 1

  for toolType in recipes:
    let recipeOpt = recipeManager.loadRecipe(toolType)
    if recipeOpt.isSome():
      let recipe = recipeOpt.get()
      echo fmt"  {toolType:8} - {recipe.description}"
      echo fmt"           Version: {recipe.version}"
      echo fmt"           Platforms: {recipe.platforms.len}"
    else:
      echo fmt"  {toolType:8} - (failed to load)"

  echo ""
  return 0

proc bootstrapInfoCommand*(toolName: string): int =
  ## Show detailed information about a tool
  let recipeManager = newRecipeManager()

  if not recipeManager.hasRecipe(toolName):
    echo fmt"❌ Recipe not found: {toolName}"
    echo "   Try: nip bootstrap update-recipes"
    return 1

  let recipeOpt = recipeManager.loadRecipe(toolName)
  if recipeOpt.isNone():
    echo fmt"❌ Failed to load recipe: {toolName}"
    return 1

  let recipe = recipeOpt.get()

  echo ""
  echo fmt"📦 {recipe.name} v{recipe.version}"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo ""
  echo fmt"Description: {recipe.description}"
  echo fmt"Tool Type:   {recipe.toolType}"
  echo ""

  if recipe.metadata.author.len > 0:
    echo "Metadata:"
    echo fmt"  Author:   {recipe.metadata.author}"
    echo fmt"  License:  {recipe.metadata.license}"
    echo fmt"  Updated:  {recipe.metadata.updated}"
    if recipe.metadata.homepage.len > 0:
      echo fmt"  Homepage: {recipe.metadata.homepage}"
    echo ""

  echo "Platforms:"
  for platform in recipe.platforms:
    echo fmt"  • {platform.arch}/{platform.os}"

    if platform.binaries.len > 0:
      echo "    Binaries:"
      for binary in platform.binaries:
        let sizeKB = binary.size div 1024
        echo fmt"      - {binary.name} ({sizeKB} KB)"

    if platform.archives.len > 0:
      echo "    Archives:"
      for archive in platform.archives:
        let sizeMB = archive.size div (1024 * 1024)
        echo fmt"      - {archive.name} ({sizeMB} MB) → {archive.extractTo}"

  echo ""

  if recipe.dependencies.len > 0:
    echo "Dependencies:"
    for dep in recipe.dependencies:
      let req = if dep.required: "required" else: "optional"
      let ver = if dep.version.len > 0: fmt" {dep.version}" else: ""
      echo fmt"  • {dep.name}{ver} ({req})"
    echo ""

  echo "Installation:"
  echo fmt"  Script:       {recipe.install.script}"
  echo fmt"  Verification: {recipe.install.verifyScript}"
  if recipe.install.postInstall.len > 0:
    echo fmt"  Post-install: {recipe.install.postInstall}"
  echo ""

  # Check if tool is installed
  let toolType = case toolName.toLower()
    of "nix": bttNix
    of "pkgsrc": bttPkgsrc
    of "gentoo": bttGentoo
    else:
      echo "Status: Unknown tool type"
      return 0

  if isSystemToolAvailable(toolType):
    echo "Status: ✅ Available on system"
  elif isToolInstalled(toolType):
    echo "Status: ✅ Installed via NIP"
    let toolDir = getToolDir(toolType)
    echo fmt"        {toolDir}"
  else:
    echo "Status: ⚠️  Not installed"
    echo fmt"        Install with: nip bootstrap install {toolName}"

  echo ""
  return 0

proc bootstrapHelpCommand*() =
  ## Show bootstrap help
  echo ""
  echo "NIP Bootstrap - Build Tool Management"
  echo ""
  echo "Commands:"
  echo "  nip bootstrap list              List installed build tools"
  echo "  nip bootstrap install <tool>    Install a build tool"
  echo "  nip bootstrap remove <tool>     Remove a build tool"
  echo "  nip bootstrap info <tool>       Show detailed tool information"
  echo "  nip bootstrap recipes           List available recipes"
  echo "  nip bootstrap update-recipes    Update recipes from repository"
  echo "  nip bootstrap validate <tool>   Validate a recipe file"
  echo "  nip bootstrap help              Show this help"
  echo ""
  echo "Available tools:"
  echo "  nix      - Nix package manager (100,000+ packages)"
  echo "  pkgsrc   - PKGSRC (27,000+ packages, portable)"
  echo "  gentoo   - Gentoo Portage (20,000+ packages)"
  echo ""
  echo "Examples:"
  echo "  nip bootstrap list"
  echo "  nip bootstrap install nix"
  echo "  nip bootstrap info nix"
  echo "  nip bootstrap recipes"
  echo "  nip bootstrap update-recipes"
  echo "  nip bootstrap validate nix"
  echo "  nip bootstrap remove gentoo"
  echo ""
