#!/usr/bin/env nu

# KCL Packaging CLI
# Package and distribute KCL modules for provisioning system
# Author: JesusPerezLorenzo
# Date: 2025-09-29

use ../nulib/lib_provisioning/kcl_packaging.nu *

# Main pack command
def main [] {
    print_help
}

# Package core provisioning schemas
export def "main core" [
    --output: string = "",    # Output directory
    --version: string = ""    # Version override
] {
    print "📦 Packaging Core Provisioning Schemas"
    print ""

    let package_path = (pack-core --output $output --version $version)

    print ""
    print $"✅ Core package created: ($package_path)"
}

# Package a specific provider
export def "main provider" [
    provider: string,         # Provider name (e.g., upcloud, aws, local)
    --output: string = "",    # Output directory
    --version: string = ""    # Version override
] {
    print $"📦 Packaging Provider: ($provider)"
    print ""

    let package_path = (pack-provider $provider --output $output --version $version)

    print ""
    print $"✅ Provider package created: ($package_path)"
}

# Package all providers
export def "main providers" [
    --output: string = ""     # Output directory
] {
    print "📦 Packaging All Providers"
    print ""

    let results = (pack-all-providers --output $output)

    print ""
    print "📊 Packaging Summary:"
    $results | table

    let success_count = ($results | where status == "success" | length)
    let total_count = ($results | length)

    print ""
    if $success_count == $total_count {
        print $"✅ All ($total_count) providers packaged successfully"
    } else {
        print $"⚠️  ($success_count)/($total_count) providers packaged successfully"
    }
}

# Package everything (core + all providers)
export def "main all" [
    --output: string = ""     # Output directory
] {
    print "📦 Packaging Everything (Core + All Providers)"
    print ""

    # Package core
    print "▶️  Packaging core..."
    main core --output $output

    print ""

    # Package all providers
    print "▶️  Packaging providers..."
    main providers --output $output

    print ""
    print "✅ Complete packaging finished"
}

# List packaged modules
export def "main list" [
    --format: string = "table" # Output format: table, json, yaml
] {
    print "📦 Packaged Modules:"
    print ""

    list-packages --format $format
}

# Clean old packages
export def "main clean" [
    --keep-latest: int = 3,   # Number of latest versions to keep
    --dry-run,                # Show what would be deleted
    --all,                    # Clean ALL packages (ignores keep-latest)
    --force                   # Skip confirmation prompts
] {
    if $all {
        clean-all-packages --dry-run=$dry_run --force=$force
    } else {
        clean-packages --keep-latest $keep_latest --dry-run=$dry_run
    }
}

# Remove specific package and its metadata
export def "main remove" [
    package_name: string,     # Package name (e.g., "aws_prov", "upcloud_prov", "provisioning_core")
    --force                   # Skip confirmation prompt
] {
    remove-package $package_name --force=$force
}

# Show package information
export def "main info" [
    package_name: string      # Package name (without .tar.gz)
] {
    print $"📋 Package Information: ($package_name)"
    print ""

    # Look for package
    let pack_path = (get-config-value "distribution" "pack_path")
    let package_file = ($pack_path | path join $"($package_name).tar.gz")

    if not ($package_file | path exists) {
        print $"❌ Package not found: ($package_file)"
        return
    }

    let info = (ls $package_file | first)

    print $"  File: ($info.name)"
    print $"  Size: ($info.size)"
    print $"  Modified: ($info.modified)"

    # Check for metadata
    let registry_path = (get-config-value "distribution" "registry_path")
    let metadata_file = ($registry_path | path join $"($package_name).json")

    if ($metadata_file | path exists) {
        print ""
        print "  Metadata:"
        let metadata = (open $metadata_file)

        print $"    Name: ($metadata.name)"
        print $"    Version: ($metadata.version)"
        print $"    Created: ($metadata.created)"
        print $"    Maintainer: ($metadata.maintainer)"
        print $"    License: ($metadata.license)"
        print $"    Repository: ($metadata.repository)"
    }
}

# Initialize distribution directories
export def "main init" [] {
    print "🚀 Initializing Distribution System"
    print ""

    let pack_path = (get-config-value "distribution" "pack_path")
    let registry_path = (get-config-value "distribution" "registry_path")
    let cache_path = (get-config-value "distribution" "cache_path")

    mkdir $pack_path
    print $"  ✓ Created: ($pack_path)"

    mkdir $registry_path
    print $"  ✓ Created: ($registry_path)"

    mkdir $cache_path
    print $"  ✓ Created: ($cache_path)"

    print ""
    print "✅ Distribution system initialized"
}

# Helper: Print help
def print_help [] {
    print "KCL Packaging CLI - Package and distribute KCL modules"
    print ""
    print "Usage: pack <command> [options]"
    print ""
    print "COMMANDS:"
    print "  init                                        - Initialize distribution directories"
    print "  core [--output <dir>] [--version <v>]       - Package core provisioning schemas"
    print "  provider <name> [--output <dir>]            - Package specific provider"
    print "  providers [--output <dir>]                  - Package all providers"
    print "  all [--output <dir>]                        - Package everything (core + providers)"
    print "  list [--format <fmt>]                       - List packaged modules"
    print "  info <package_name>                         - Show package information"
    print "  remove <package_name> [--force]             - Remove specific package and metadata"
    print "  clean [--keep-latest <n>] [--all] [--dry-run] - Clean old packages"
    print ""
    print "OPTIONS:"
    print "  --output <dir>       Output directory (uses config default if not specified)"
    print "  --version <v>        Version override for package"
    print "  --format <fmt>       Output format: table, json, yaml"
    print "  --keep-latest <n>    Number of latest versions to keep (default: 3)"
    print "  --all                Clean ALL packages (use with clean command)"
    print "  --force              Skip confirmation prompts"
    print "  --dry-run            Show what would be done without executing"
    print ""
    print "EXAMPLES:"
    print "  pack init"
    print "  pack core"
    print "  pack provider upcloud"
    print "  pack providers"
    print "  pack all"
    print "  pack list"
    print "  pack info provisioning_core"
    print "  pack remove aws_prov"
    print "  pack remove upcloud_prov --force"
    print "  pack clean --keep-latest 5 --dry-run"
    print "  pack clean --all --dry-run"
    print "  pack clean --all"
    print ""
    print "Distribution configuration in: provisioning/config/config.defaults.toml [distribution]"
}
