# ╔══════════════════════════════════════════════════════════════════════╗
# ║                   DISTRIBUTION & PACKAGING RECIPES                   ║
# ║                  Build, package, and distribute binaries             ║
# ╚══════════════════════════════════════════════════════════════════════╝

# Help for distro module
help:
    @echo "DISTRIBUTION MODULE"
    @echo ""
    @echo "Build:"
    @echo "  just distro::build-all          Build all targets (debug)"
    @echo "  just distro::build-release      Build all targets (release)"
    @echo ""
    @echo "Cross-Compilation:"
    @echo "  just distro::cross              Cross-compile all platforms"
    @echo "  just distro::cross-docker       Cross-compile using Docker"
    @echo "  just distro::cross-target TGT   Cross-compile specific target"
    @echo ""
    @echo "Distribution Package:"
    @echo "  just distro::create-package     Create distribution package"
    @echo "  just distro::create-checksums   Generate checksums"
    @echo "  just distro::package-all        Build + package + checksums"
    @echo ""
    @echo "Release:"
    @echo "  just distro::package-release    Package for release (with notes)"
    @echo "  just distro::package-release-version V  With specific version"
    @echo ""
    @echo "Installation:"
    @echo "  just distro::install            Install binaries to ~/.local/bin"
    @echo "  just distro::install DIR=/path  Install to custom directory"
    @echo ""
    @echo "Manifest:"
    @echo "  just distro::generate-manifest  Create manifest file"
    @echo ""
    @echo "Compliance:"
    @echo "  just distro::generate-sbom      Regenerate SBOMs (LICENSE.md, SBOM.*)"
    @echo ""
    @echo "Utilities:"
    @echo "  just distro::list-packages      List distribution packages"
    @echo "  just distro::clean-distro       Clean distribution directory"

# Workspace root directory
# Note: In modules, justfile_directory() returns the workspace root already
WORKSPACE_ROOT := justfile_directory()

# === BUILD TARGETS ===

# Build all workspace targets (debug)
[doc("Build all targets (debug)")]
build-all:
    @echo "=== Building all targets (debug) ==="
    "{{ WORKSPACE_ROOT }}/scripts/build_all.sh" debug

# Build all workspace targets (release)
[doc("Build all targets (release)")]
build-release:
    @echo "=== Building all targets (release) ==="
    "{{ WORKSPACE_ROOT }}/scripts/build_all.sh" release

# === CROSS-COMPILATION ===

# Cross-compile for all platforms
[doc("Cross-compile for all platforms")]
cross:
    @echo "=== Cross-compiling for all platforms ==="
    "{{ WORKSPACE_ROOT }}/scripts/build_cross.sh"

# Cross-compile for specific target
[doc("Cross-compile for target")]
cross-target TARGET:
    @echo "=== Cross-compiling for {{TARGET}} ==="
    "{{ WORKSPACE_ROOT }}/scripts/build_cross.sh" "{{TARGET}}"

# Cross-compile using Docker
[doc("Cross-compile using Docker")]
cross-docker TARGET="x86_64-unknown-linux-gnu":
    @echo "=== Docker cross-compilation: {{TARGET}} ==="
    docker build \
        -f .woodpecker/Dockerfile.cross \
        --build-arg TARGET="{{TARGET}}" \
        -t typedialog-builder:{{TARGET}} \
        .
    docker run --rm \
        -v "$(pwd)/distribution:/output" \
        typedialog-builder:{{TARGET}}

# === DISTRIBUTION ===

# Create distribution package
[doc("Create distribution package")]
create-package:
    @echo "=== Creating distribution package ==="
    "{{ WORKSPACE_ROOT }}/scripts/create_distro.sh"

# Create distribution package with version
[doc("Create distribution with version")]
create-package-version VERSION:
    @echo "=== Creating distribution ({{VERSION}}) ==="
    "{{ WORKSPACE_ROOT }}/scripts/create_distro.sh" "{{VERSION}}"

# Generate checksums for distribution
[doc("Generate checksums")]
create-checksums:
    @echo "=== Generating checksums ==="
    @cd "{{ WORKSPACE_ROOT }}/distribution" && \
        find . -type f \( -name "*.tar.gz" -o -name "*.zip" \) | \
        while read -r file; do \
            sha256sum "$$file" > "$${file}.sha256"; \
        done
    @echo "✓ Checksums generated"

# === PACKAGING ===

# Create all distribution packages (debug + release + cross)
[doc("Create all packages")]
package-all:
    @echo "=== Building all packages ==="
    @just distro::build-release
    @just distro::create-package
    @just distro::create-checksums
    @echo "✓ All packages complete"

# Package release (create release directory with checksums and notes)
[doc("Package for release")]
package-release:
    @echo "=== Packaging release ==="
    "{{ WORKSPACE_ROOT }}/scripts/package_release.sh"

# Package release with version
[doc("Package release with version")]
package-release-version VERSION:
    @echo "=== Packaging release ({{VERSION}}) ==="
    "{{ WORKSPACE_ROOT }}/scripts/package_release.sh" "{{VERSION}}"

# === INSTALLATION ===

# Install release binaries to location (default: ~/.local/bin)
[doc("Install binaries (default: ~/.local/bin or DIR=<path>)")]
install DIR="":
    #!/bin/bash
    set -e

    WORKSPACE="{{ WORKSPACE_ROOT }}"

    # Resolve install directory
    if [ -z "{{ DIR }}" ]; then
        INSTALL_DIR="$HOME/.local/bin"
    else
        INSTALL_DIR="{{ DIR }}"
    fi

    echo "=== Installing binaries to $INSTALL_DIR ==="
    mkdir -p "$INSTALL_DIR" || { echo "✗ Failed to create directory"; exit 1; }
    echo ""
    echo "Installing release binaries..."

    for binary in typedialog typedialog-tui typedialog-web typedialog-ai typedialog-ag typedialog-prov-gen; do
        SRC="$WORKSPACE/target/release/$binary"
        if [ -f "$SRC" ]; then
            cp "$SRC" "$INSTALL_DIR/$binary"
            chmod +x "$INSTALL_DIR/$binary"
            echo "  ✓ $binary"
        else
            echo "  ✗ $binary (not found at $SRC)"
        fi
    done

    # Copy prov-gen templates if they don't exist
    echo ""
    echo "Installing data files..."
    TEMPLATES_DIR="$HOME/.config/typedialog/prov-gen/templates"
    if [ ! -d "$TEMPLATES_DIR" ]; then
        mkdir -p "$TEMPLATES_DIR"
        cp -r "$WORKSPACE/crates/typedialog-prov-gen/templates"/* "$TEMPLATES_DIR/"
        echo "  ✓ prov-gen templates"
    else
        echo "  ⊘ prov-gen templates (already exist)"
    fi

    echo ""
    echo "Installation summary:"
    echo "  Install dir: $INSTALL_DIR"
    echo "  Templates dir: $TEMPLATES_DIR"

    if echo "$INSTALL_DIR" | grep -q "\.local/bin"; then
        echo "  Shell setup: Run 'export PATH=\"\$PATH:$INSTALL_DIR\"' or add to ~/.bashrc/.zshrc"
    fi

    echo ""
    echo "Verify installation:"
    echo "  $INSTALL_DIR/typedialog --version  # Verify TypeDialog installation"
    echo ""

# === MANIFEST ===

# Generate distribution manifest
[doc("Generate distribution manifest")]
generate-manifest:
    @echo "=== Generating manifest ==="
    @cd "{{ WORKSPACE_ROOT }}/distribution" && \
        ls -1 typedialog-*.tar.gz 2>/dev/null | \
        jq -R -s -c 'split("\n") | map(select(length > 0)) | {"packages": .}' > manifest.json
    @echo "✓ Manifest generated"

# === UTILITIES ===

# List distribution contents
[doc("List distribution packages")]
list-packages:
    @echo "=== Distribution Packages ==="
    @ls -lh "{{ WORKSPACE_ROOT }}/distribution/" 2>/dev/null || echo "No packages found"

# Clean distribution directory
[doc("Clean distribution directory")]
clean-distro:
    @echo "=== Cleaning distribution ==="
    @rm -rf "{{ WORKSPACE_ROOT }}/distribution"
    @mkdir -p "{{ WORKSPACE_ROOT }}/distribution"
    @echo "✓ Distribution cleaned"

# === COMPLIANCE ===

# Regenerate SBOMs (SBOM.spdx.json + SBOM.cyclonedx.json)
[doc("Regenerate SBOMs (SPDX 2.3 and CycloneDX 1.4)")]
generate-sbom:
    @echo "=== Regenerating SBOMs ==="
    cd "{{ WORKSPACE_ROOT }}" && \
        cargo sbom --output-format spdx_json_2_3 > SBOM.spdx.json && \
        cargo sbom --output-format cyclone_dx_json_1_4 > SBOM.cyclonedx.json
    @echo "✓ SBOMs regenerated"
    @echo "  - SBOM.spdx.json (SPDX 2.3 format)"
    @echo "  - SBOM.cyclonedx.json (CycloneDX 1.4 format)"
