#!/usr/bin/env nu
# Info: Script to run Provisioning Package Management
# Author: JesusPerezLorenzo
# Release: 1.0.0
# Date: 29-09-2025

use std log

use lib_provisioning *
use env.nu *

# - > Help on Pack
export def "main help" [
  --src: string = ""
  --notitles       # not titles
  --out: string    # Print Output format: json, yaml, text (default)
]: nothing -> nothing {
  if $notitles == null or not $notitles { show_titles }
  ^$"($env.PROVISIONING_NAME)" -mod pack --help
  if ($out | is-not-empty) { $env.PROVISIONING_NO_TERMINAL = false }
  print (provisioning_options $src)
  if not $env.PROVISIONING_DEBUG { end_run "" }
}

# > Package Management (Advanced/Maintainer)
# WARNING: This is an advanced tool for packaging and distributing KCL modules
def main [
  ...args: string  # Other options, use help to get info
  -v               # Show version
  -i               # Show Info
  --version (-V)   # Show version with title
  --info (-I)      # Show Info with title
  --about (-a)     # Show About
  --output: string = ""     # Output directory for packages
  --format: string = ""     # Output format: table, json, yaml
  --keep-latest: int = 3    # Number of latest versions to keep (clean command)
  --all            # Clean ALL packages (clean command)
  --force (-f)     # Skip confirmation prompts
  --dry-run        # Show what would be done without doing it
  --check (-c)     # Only check mode, no actual changes
  --yes (-y)       # Confirm task
  --debug (-x)     # Use Debug mode
  --xm             # Debug with PROVISIONING_METADATA
  --xld            # Log level with DEBUG PROVISIONING_LOG_LEVEL=debug
  --metadata       # Error with metadata (-xm)
  --notitles       # Do not show banner titles
  --helpinfo (-h)  # For more details use options "help" (no dashes)
  --out: string    # Print Output format: json, yaml, text (default)
]: nothing -> nothing {
  if ($out | is-not-empty) {
    $env.PROVISIONING_OUT = $out
    $env.PROVISIONING_NO_TERMINAL = true
  }
  provisioning_init $helpinfo "pack" $args
  if $version or $v { ^$env.PROVISIONING_NAME -v ; exit }
  if $info or $i { ^$env.PROVISIONING_NAME -i ; exit }
  if $about {
    _print (get_about_info)
    exit
  }
  if $debug { $env.PROVISIONING_DEBUG = true }
  if $metadata { $env.PROVISIONING_METADATA = true }

  let task = if ($args | length) > 0 { ($args | get 0) } else { "" }
  let ops = if ($args | length) > 1 { ($args | skip 1 | str join " ") } else { "" }
  let package_name = if ($ops | is-not-empty) and not ($ops | str starts-with "-") {
    ($ops | split row " " | get 0)
  } else {
    ""
  }

  $env.PROVISIONING_MODULE = "pack"

  let pack_cli = ($env.PROVISIONING | path join "core" "cli" "pack")

  if not ($pack_cli | path exists) {
    print "❌ Pack CLI not found at: ($pack_cli)"
    exit 1
  }

  match $task {
    "h" => {
      exec $"($env.PROVISIONING_NAME)" -mod pack help --notitles
    },
    "init" => {
      print "⚠️  WARNING: Initializing distribution system (Maintainer operation)"
      ^nu $pack_cli init
    },
    "core" => {
      print "📦 WARNING: Packaging core schemas (Maintainer operation)"
      let output_flag = if ($output | is-not-empty) { ["--output" $output] } else { [] }
      ^nu $pack_cli core ...$output_flag
    },
    "provider" => {
      if ($package_name | is-empty) {
        print "❌ Provider name required"
        print "Usage: provisioning pack provider <name>"
        exit 1
      }
      print $"📦 WARNING: Packaging provider: ($package_name) (Maintainer operation)"
      let output_flag = if ($output | is-not-empty) { ["--output" $output] } else { [] }
      ^nu $pack_cli provider $package_name ...$output_flag
    },
    "providers" => {
      print "📦 WARNING: Packaging all providers (Maintainer operation)"
      let output_flag = if ($output | is-not-empty) { ["--output" $output] } else { [] }
      ^nu $pack_cli providers ...$output_flag
    },
    "all" => {
      print "📦 WARNING: Packaging everything - core + all providers (Maintainer operation)"
      let output_flag = if ($output | is-not-empty) { ["--output" $output] } else { [] }
      ^nu $pack_cli all ...$output_flag
    },
    "list" | "ls" => {
      let fmt = if ($format | is-not-empty) { $format } else if ($out | is-not-empty) { $out } else { "table" }
      ^nu $pack_cli list --format $fmt
    },
    "info" => {
      if ($package_name | is-empty) {
        print "❌ Package name required"
        print "Usage: provisioning pack info <package_name>"
        exit 1
      }
      ^nu $pack_cli info $package_name
    },
    "remove" | "rm" => {
      if ($package_name | is-empty) {
        print "❌ Package name required"
        print "Usage: provisioning pack remove <package_name> [--force]"
        exit 1
      }
      print $"⚠️  WARNING: Removing package: ($package_name) (Maintainer operation)"
      let force_flag = if $force { ["--force"] } else { [] }
      ^nu $pack_cli remove $package_name ...$force_flag
    },
    "clean" => {
      print "⚠️  WARNING: Cleaning packages (Maintainer operation)"
      let dry_run_flag = if $dry_run { ["--dry-run"] } else { [] }
      let all_flag = if $all { ["--all"] } else { [] }
      let force_flag = if $force { ["--force"] } else { [] }
      let keep_flag = if ($keep_latest | is-not-empty) and not $all {
        ["--keep-latest" ($keep_latest | into string)]
      } else {
        []
      }
      ^nu $pack_cli clean ...$keep_flag ...$all_flag ...$dry_run_flag ...$force_flag
    },
    "clean-all" => {
      # Convenience alias for clean --all
      print "⚠️  WARNING: Cleaning ALL packages (Maintainer operation)"
      let dry_run_flag = if $dry_run { ["--dry-run"] } else { [] }
      let force_flag = if $force { ["--force"] } else { [] }
      ^nu $pack_cli clean --all ...$dry_run_flag ...$force_flag
    },
    _ => {
      print $"❌ Unknown task: ($task)"
      print ""
      print "Available commands:"
      print "  init              - Initialize distribution directories"
      print "  core              - Package core schemas"
      print "  provider <name>   - Package specific provider"
      print "  providers         - Package all providers"
      print "  all               - Package everything"
      print "  list              - List packaged modules"
      print "  info <name>       - Show package information"
      print "  remove <name>     - Remove package"
      print "  clean             - Clean old packages (keeps latest 3 by default)"
      print "  clean-all         - Clean ALL packages (convenience for clean --all)"
      print ""
      print "Flags:"
      print "  --all             - Clean all packages (use with clean)"
      print "  --keep-latest N   - Keep N latest versions (use with clean, default: 3)"
      print "  --dry-run         - Show what would be done without doing it"
      print "  --force           - Skip confirmation prompts"
      print ""
      print "Use 'provisioning pack help' for detailed information"
      exit 1
    }
  }
}
