#!/usr/bin/env bash
# generate-registry.sh — Build a registry.json from a directory of .pkg files.
#
# Usage:
#   ./scripts/generate-registry.sh [PKG_DIR] [BASE_URL]
#
# Arguments:
#   PKG_DIR   Directory containing .pkg files (default: dist/)
#   BASE_URL  HTTPS base URL for download links (default: https://example.com/packages)
#
# Output:
#   Writes registry.json to stdout. Redirect to a file:
#     ./scripts/generate-registry.sh dist/ https://cdn.example.com/pkg > registry.json

set -euo pipefail

PKG_DIR="${1:-dist}"
BASE_URL="${2:-https://example.com/packages}"

# Strip trailing slash
BASE_URL="${BASE_URL%/}"

if [ ! -d "$PKG_DIR" ]; then
    echo "Error: directory '$PKG_DIR' not found" >&2
    exit 1
fi

# Collect entries
entries=()

for pkg in "$PKG_DIR"/*.pkg; do
    [ -f "$pkg" ] || continue

    # Extract manifest.json from the ZIP archive
    manifest=$(unzip -p "$pkg" manifest.json 2>/dev/null) || {
        echo "Warning: skipping $pkg (no manifest.json)" >&2
        continue
    }

    # Read fields from manifest
    id=$(echo "$manifest"          | jq -r '.id // empty')
    title=$(echo "$manifest"       | jq -r '.title // .id')
    version=$(echo "$manifest"     | jq -r '.version // "0.0.0"')
    description=$(echo "$manifest" | jq -r '.description // ""')
    author=$(echo "$manifest"      | jq -r '.author // ""')
    type=$(echo "$manifest"        | jq -r '.type // "extension"')
    tier=$(echo "$manifest"        | jq -r '.tier // "community"')

    if [ -z "$id" ]; then
        echo "Warning: skipping $pkg (no id in manifest)" >&2
        continue
    fi

    filename=$(basename "$pkg")
    size=$(stat -c%s "$pkg" 2>/dev/null || stat -f%z "$pkg" 2>/dev/null || echo 0)
    updated_at=$(date -r "$pkg" -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || date -u +"%Y-%m-%dT%H:%M:%SZ")

    entry=$(jq -n \
        --arg id "$id" \
        --arg title "$title" \
        --arg version "$version" \
        --arg description "$description" \
        --arg author "$author" \
        --arg type "$type" \
        --arg tier "$tier" \
        --arg download_url "$BASE_URL/$filename" \
        --argjson size "$size" \
        --arg updated_at "$updated_at" \
        '{id: $id, title: $title, version: $version, description: $description,
          author: $author, type: $type, tier: $tier, download_url: $download_url,
          size: $size, updated_at: $updated_at}')

    entries+=("$entry")
done

# Build final JSON
if [ ${#entries[@]} -eq 0 ]; then
    echo '{"packages": []}' | jq .
else
    printf '%s\n' "${entries[@]}" | jq -s '{packages: .}'
fi
