#!/usr/bin/env sh
# Copyright (c) 2026 SnowdreamTech. All rights reserved.
# Licensed under the MIT License. See LICENSE file in the project root for full license information.

# scripts/gen-full-manifest.sh — Mise Manifest Aggregator
#
# Purpose:
#   Programmatically generates a comprehensive mise.toml containing all
#   Tier 1 (Core) and Tier 2 (On-demand) tools. This manifest is used by
#   'make sync-lock' to generate a unified mise.lock with 100% integrity.

set -eu

# 1. Boilerplate & Context Detection
SCRIPT_DIR=$(cd "$(dirname "${0:-}")" && pwd)

# 2. Load Tier 2 registry
. "${SCRIPT_DIR:-}/lib/versions.sh"

echo "# ------------------------------------------------------------"
echo "# AUTO-GENERATED FULL MANIFEST — DO NOT EDIT"
echo "# Generated by scripts/gen-full-manifest.sh"
echo "# ------------------------------------------------------------"
echo ""
echo "[tools]"

# 2. Extract Tier 1 tools from .mise.toml (excluding commented Tier 2 section)
# We assume Tier 1 tools are in the first [tools] block of .mise.toml.
perl -ne '
  if (/^\[tools\]/) { $in_tools = 1; next }
  if (/^\[/ || /^# ── TIER 2/) { $in_tools = 0 }
  if ($in_tools && /^\s*([^#\s][^=\s]*)\s*=\s*(.*)/) {
    print "$1 = $2\n";
  }
' "${SCRIPT_DIR:-}/../.mise.toml"

# 3. Add Tier 2 tools from versions.sh
# We parse versions.sh for VER_*_PROVIDER variables.
# If a _PROVIDER variable exists, we use it as the tool name.
# Otherwise, we use the name derived from VER_*.

# Get all VER_* variables from versions.sh
grep -E "^VER_[A-Z0-9_]+=" "${SCRIPT_DIR:-}/lib/versions.sh" | while IFS= read -r line; do
  var_name=$(echo "${line:-}" | cut -d= -f1)
  var_val=$(echo "${line:-}" | cut -d= -f2- | tr -d '"')

  # Skip _PROVIDER, _REF, and other metadata variables
  case "${var_name:-}" in
  *_PROVIDER | *_REF | *_URL | *_SHA*) continue ;;
  esac

  # Build the provider name
  provider_var="${var_name}_PROVIDER"
  # Use eval to get the value of the provider variable
  provider_val=$(eval "echo \${$provider_var:-}")

  if [ -n "${provider_val:-}" ]; then
    # Use the explicit provider (e.g., github:aquasecurity/trivy)
    echo "\"${provider_val:-}\" = \"${var_val:-}\""
  else
    # Fallback to simple name (e.g., go, rust) if it's a core tool not in .mise.toml
    # Usually these are already in Tier 1, so we avoid duplicates if they exist there.
    tool_name=$(echo "${var_name:-}" | sed 's/^VER_//' | tr '[:upper:]' '[:lower:]' | tr '_' '-')
    # Check if tool_name is one of the core runtimes
    case "${tool_name:-}" in
    go | node | python | ruby | java | rust | kotlin | dotnet | bun | deno | zig)
      # Only add if NOT already in .mise.toml Tier 1
      if ! grep -q "^\s*${tool_name:-}\s*=" "${SCRIPT_DIR:-}/../.mise.toml"; then
        echo "${tool_name:-} = \"${var_val:-}\""
      fi
      ;;
    *)
      # Other tools usually have a provider. If not, they might be missing.
      # We only add them if we are sure.
      ;;
    esac
  fi
done | sort -u
