# Provisioning System - Standalone Infrastructure Automation
# Modern justfile for infrastructure provisioning and automation
# ============================================================

# Import provisioning module justfiles
import 'justfiles/build.just'
import 'justfiles/package.just'
import 'justfiles/release.just'
import 'justfiles/dev.just'
import 'justfiles/ci.just'
import 'justfiles/platform.just'
import 'justfiles/installer.just'
import 'justfiles/book.just'
import 'justfiles/auth.just'
import 'justfiles/kms.just'
import 'justfiles/orchestrator.just'

# ============================================================================
# Provisioning Configuration
# ============================================================================

# Project metadata
provisioning_name := "provisioning"
version := `git describe --tags --always --dirty 2>/dev/null || echo "dev-$(date +%Y%m%d)"`
build_time := `date -u +"%Y-%m-%dT%H:%M:%SZ"`
git_commit := `git rev-parse HEAD 2>/dev/null || echo "unknown"`

# Directories
provisioning_root := justfile_directory()
project_root := provisioning_root / ".."
tools_dir := provisioning_root / "tools"
build_dir := project_root / "target"
dist_dir := project_root / "dist"
packages_dir := project_root / "packages"

# Build configuration
rust_target := "x86_64-unknown-linux-gnu"
build_mode := "release"
platforms := "linux-amd64,macos-amd64,windows-amd64"
variants := "complete,minimal"

# Tools
nu := "nu"
cargo := "cargo"
docker := "docker"

# Flags
verbose := "false"
dry_run := "false"
parallel := "true"

# ============================================================================
# Default Recipe - Show Help
# ============================================================================

# Show concise provisioning overview
@default:
    echo "🏗️  PROVISIONING SYSTEM - INFRASTRUCTURE AUTOMATION"
    echo "==================================================="
    echo ""
    echo "🚀 QUICK START"
    echo "   just all           - Complete pipeline (build + package + test)"
    echo "   just quick         - Fast development build"
    echo "   just ci            - CI/CD pipeline (no cleanup)"
    echo "   just ci-clean      - CI/CD pipeline (with cleanup)"
    echo ""
    echo "📦 KEY MODULES"
    echo "   🏗️ build          - Platform binaries & core libraries    (just build-help)"
    echo "   📦 package        - Distribution packaging & containers    (just package-help)"
    echo "   🚀 release        - Release management & artifacts        (just release-help)"
    echo "   🔧 dev            - Development workflows & testing       (just dev-help)"
    echo "   ⚡ platform       - Platform services & orchestration     (just platform-help)"
    echo "   📦 installer      - Interactive installer & config mgmt   (just installer-help)"
    echo "   📖 book           - MDBook documentation system           (just book-help)"
    echo ""
    echo "🔐 PLUGIN MODULES"
    echo "   🔐 auth           - Authentication & MFA operations        (just auth-help)"
    echo "   🔒 kms            - Key management & encryption            (just kms-help)"
    echo "   🎯 orchestrator   - Workflow & task orchestration          (just orch-help)"
    echo ""
    echo "🔍 DETAILED HELP"
    echo "   just help          - Show this overview"
    echo "   just help-full     - Show comprehensive help"
    echo "   just --list        - List all available recipes"
    echo ""
    echo "💡 VERSION: {{version}} | Build: {{build_mode}} | Target: {{rust_target}}"

# ============================================================================
# Meta Recipes
# ============================================================================

# Show help - usage: just help [module]
help MODULE="":
    #!/usr/bin/env bash
    if [ "{{MODULE}}" = "" ]; then
        just --justfile {{justfile()}} default
    elif [ "{{MODULE}}" = "ci" ]; then
        echo "🔧 CI/CD PIPELINES"
        echo "==================="
        echo ""
        echo "Available CI commands:"
        echo "  just ci              - CI/CD pipeline WITHOUT cleanup (fast iteration)"
        echo "  just ci-clean        - CI/CD pipeline WITH cleanup (production)"
        echo "  just ci-full         - Run all CI checks (formatting, linting, tests, audit)"
        echo ""
        echo "CI Tasks:"
        echo "  just ci-fmt-check    - Check code formatting"
        echo "  just ci-fmt          - Code formatting"
        echo "  just ci-lint         - Run all linting checks"
        echo "  just ci-test         - Run all tests"
        echo "  just ci-audit        - Run security audits"
        echo "  just ci-docs         - Check documentation"
        echo ""
        echo "ℹ️  NOTE: nu_plugins (in plugins/nushell-plugins/) are excluded from CI checks"
        echo "    since they are maintained as a separate project with independent CI."
    else
        echo "❌ Unknown module: {{MODULE}}"
        echo ""
        echo "Available modules: ci, build, package, release, dev, platform, installer, book, auth, kms, orchestrator"
    fi

# Show comprehensive provisioning help
@help-full:
    echo "🏗️  PROVISIONING SYSTEM - COMPREHENSIVE HELP"
    echo "============================================="
    echo ""
    echo "STANDALONE INFRASTRUCTURE AUTOMATION TOOLKIT"
    echo "This system can be used independently or as part of a larger project ecosystem"
    echo "for cloud-native deployments across multiple providers (UpCloud, AWS, Local)."
    echo ""
    echo "📦 BUILD MODULE (build.just) - DETAILED"
    echo "   Complete build system for platform binaries and core libraries"
    echo "   • build-all        - Build all components (platform + core + KCL)"
    echo "   • build-platform   - Build platform binaries for all targets"
    echo "   • build-core       - Bundle core Nushell libraries"
    echo "   • validate-kcl     - Validate and compile KCL schemas"
    echo "   • build-cross      - Cross-compile for multiple platforms"
    echo "   • build-debug      - Debug build with symbols"
    echo "   • build-wasm       - WebAssembly target build"
    echo "   • build-libs       - Library components only"
    echo ""
    echo "📦 PACKAGE MODULE (package.just) - DETAILED"
    echo "   Distribution packaging and container management"
    echo "   • package-all      - Create all distribution packages"
    echo "   • package-binaries - Package binaries for distribution"
    echo "   • package-containers - Build container images"
    echo "   • create-archives  - Create distribution archives"
    echo "   • create-installers - Create installation packages"
    echo "   • package-minimal  - Minimal distribution package"
    echo "   • package-complete - Complete distribution with docs"
    echo ""
    echo "🚀 RELEASE MODULE (release.just) - DETAILED"
    echo "   Release management and artifact distribution"
    echo "   • release          - Create complete release (VERSION required)"
    echo "   • release-draft    - Create draft release"
    echo "   • upload-artifacts - Upload release artifacts"
    echo "   • notify-release   - Send release notifications"
    echo "   • publish-registry - Publish to package registries"
    echo "   • tag-release      - Git tag with version"
    echo ""
    echo "🔧 DEVELOPMENT MODULE (dev.just) - DETAILED"
    echo "   Development workflows and testing utilities"
    echo "   • dev-build        - Quick development build"
    echo "   • test-build       - Test build system"
    echo "   • test-dist        - Test generated distributions"
    echo "   • validate-all     - Validate all components"
    echo "   • benchmark        - Run build benchmarks"
    echo "   • watch-build      - Watch and rebuild on changes"
    echo "   • format-code      - Format all source code"
    echo "   • lint-check       - Run linting checks"
    echo ""
    echo "⚡ PLATFORM MODULE (platform.just) - DETAILED"
    echo "   Platform services and orchestration"
    echo "   • orchestrator     - Rust orchestrator management"
    echo "   • control-center   - Web control center"
    echo "   • mcp-server       - Model Context Protocol server"
    echo "   • api-gateway      - REST API gateway"
    echo "   • platform-status  - All platform services status"
    echo ""
    echo "📦 INSTALLER MODULE (installer.just) - DETAILED"
    echo "   Interactive installer and configuration management"
    echo "   • installer-build  - Build installer binary"
    echo "   • installer-run    - Run interactive TUI installer"
    echo "   • installer-headless - Run in headless mode"
    echo "   • installer-unattended - Run in unattended mode"
    echo "   • config-review    - Review installer configuration"
    echo "   • config-validate  - Validate config file"
    echo "   • install          - Install provisioning platform"
    echo "   • update           - Update existing installation"
    echo "   • installer-help   - Complete installer module help"
    echo ""
    echo "⚡ QUICK WORKFLOWS"
    echo "   just all           - Complete build, package, and test pipeline"
    echo "   just quick         - Fast development build"
    echo "   just ci            - CI/CD pipeline without cleanup (fast iteration)"
    echo "   just ci-clean      - CI/CD pipeline with cleanup (production)"
    echo "   just init          - Initialize provisioning environment"
    echo "   just status        - Show current provisioning status"
    echo ""
    echo "🔍 SYSTEM MANAGEMENT"
    echo "   just check-tools   - Validate required tools (nu, cargo, docker, git, kcl)"
    echo "   just clean         - Clean all build artifacts"
    echo "   just create-dirs   - Create necessary directories"
    echo "   just show-dirs     - Show directory structure"
    echo "   just info          - Show detailed system information"
    echo "   just validate-system - Complete system validation"
    echo ""
    echo "📊 CURRENT CONFIGURATION"
    echo "   System Name:  {{provisioning_name}}"
    echo "   Version:      {{version}}"
    echo "   Git Commit:   {{git_commit}}"
    echo "   Build Mode:   {{build_mode}}"
    echo "   Platforms:    {{platforms}}"
    echo "   Target:       {{rust_target}}"
    echo "   Variants:     {{variants}}"
    echo "   Root:         {{provisioning_root}}"
    echo ""
    echo "💡 PRACTICAL EXAMPLES"
    echo "   # Complete development workflow"
    echo "   just init && just all"
    echo ""
    echo "   # Quick development iteration"
    echo "   just dev-build && just test-dist"
    echo ""
    echo "   # Release workflow (with cleanup)"
    echo "   just ci-clean && just release VERSION=2.1.0"
    echo ""
    echo "   # Platform services"
    echo "   just orchestrator start && just api-gateway"
    echo ""
    echo "   # Module-specific operations"
    echo "   just build-platform && just package-containers"

# Complete build, package, and test pipeline
@all: clean build-all package-all test-dist
    echo "✅ Complete provisioning pipeline finished successfully"

# Quick development workflow
@quick: dev-build
    echo "⚡ Quick provisioning development build completed"

# CI/CD pipeline WITHOUT cleaning (for quick iteration)
@ci: build-all test-dist package-all
    echo "🚀 Provisioning CI/CD pipeline (without cleanup) completed successfully"

# Full CI/CD pipeline WITH cleaning (for production)
@ci-clean: clean build-all test-dist package-all
    echo "🚀 Provisioning CI/CD pipeline (with cleanup) completed successfully"

# Show current provisioning status
@status:
    echo "📊 PROVISIONING SYSTEM STATUS"
    echo "============================="
    echo "Name:        {{provisioning_name}}"
    echo "Version:     {{version}}"
    echo "Git Commit:  {{git_commit}}"
    echo "Build Time:  {{build_time}}"
    echo ""
    echo "Directories:"
    echo "  Provisioning: {{provisioning_root}}"
    echo "  Project Root: {{project_root}}"
    echo "  Tools:        {{tools_dir}}"
    echo "  Build:        {{build_dir}}"
    echo "  Distribution: {{dist_dir}}"
    echo "  Packages:     {{packages_dir}}"

# ============================================================================
# Environment Validation
# ============================================================================

# Validate that all required tools are available
@check-tools:
    #!/usr/bin/env bash
    echo "🔍 Checking required tools..."

    check_tool() {
        if command -v "$1" >/dev/null 2>&1; then
            echo "✅ $1: $(command -v "$1")"
        else
            echo "❌ $1: not found"
            exit 1
        fi
    }

    check_tool nu
    check_tool cargo
    check_tool docker
    check_tool git
    check_tool kcl

    echo "✅ All required tools are available"

# Initialize provisioning environment
@init: check-tools
    echo "🚀 Initializing provisioning environment..."
    mkdir -p "{{build_dir}}" "{{dist_dir}}" "{{packages_dir}}"
    echo "✅ Provisioning environment initialized"

# ============================================================================
# Directory Operations
# ============================================================================

# Create necessary directories
@create-dirs:
    mkdir -p "{{build_dir}}" "{{dist_dir}}" "{{packages_dir}}"
    mkdir -p "{{dist_dir}}/platform" "{{dist_dir}}/core" "{{dist_dir}}/kcl"

# Clean all build artifacts
@clean:
    echo "🧹 Cleaning provisioning build artifacts..."
    rm -rf {{dist_dir}} {{packages_dir}} {{build_dir}}
    mkdir -p {{dist_dir}} {{packages_dir}} {{build_dir}}
    echo "✅ All provisioning build artifacts cleaned"

# Show directory structure
@show-dirs:
    tree -d -L 3 "{{provisioning_root}}" || ls -la "{{provisioning_root}}"

# ============================================================================
# Integration Points
# ============================================================================

# Export provisioning configuration for external use
@export-config:
    echo "📤 Exporting provisioning configuration..."
    echo "PROVISIONING_VERSION={{version}}"
    echo "PROVISIONING_BUILD_MODE={{build_mode}}"
    echo "PROVISIONING_PLATFORMS={{platforms}}"
    echo "PROVISIONING_ROOT={{provisioning_root}}"
    echo "PROVISIONING_TOOLS={{tools_dir}}"

# Validate provisioning system integrity
@validate-system:
    echo "🔍 Validating provisioning system..."
    just check-tools
    just validate-all
    echo "✅ Provisioning system validation completed"

# Show system information
@info:
    #!/usr/bin/env bash
    echo "🔍 PROVISIONING SYSTEM INFORMATION"
    echo "=================================="
    echo "Operating System:"
    echo "  OS:           $(uname -s -r)"
    echo "  Architecture: $(uname -m)"
    echo "  User:         $(whoami)"
    echo "  Working Dir:  {{provisioning_root}}"
    echo ""
    echo "Tool Versions:"
    tools=("nu" "cargo" "rustc" "docker" "git" "kcl")
    for tool in "${tools[@]}"; do
        if command -v "$tool" >/dev/null 2>&1; then
            version=$($tool --version 2>/dev/null | head -1 | cut -d' ' -f2- || echo "unknown")
            echo "  $tool: $version"
        else
            echo "  $tool: not found"
        fi
    done
