#!/bin/bash

echo "Fetching publish dates for installed versions in package.json..."

# Check requirements
if [ ! -f "package.json" ]; then
    echo "Error: package.json not found"
    exit 1
fi

if ! command -v jq &> /dev/null; then
    echo "Error: jq not installed. Use: brew install jq (macOS) or apt-get install jq (Linux)"
    exit 1
fi

# Extract dependencies and devDependencies with versions
dependencies=$(jq -r '
  (.dependencies // {} | to_entries[] | {name: .key, version: .value, type: "dependency"}),
  (.devDependencies // {} | to_entries[] | {name: .key, version: .value, type: "devDependency"})
  | [ .name, .version, .type ]
  | @tsv
' package.json 2>/dev/null)

if [ -z "$dependencies" ]; then
    echo "No dependencies found in package.json"
    exit 0
fi

echo "Found $(echo "$dependencies" | wc -l | tr -d ' ') packages. Fetching version-specific publish dates..."
echo "------------------------------------------------------------------------"

echo "$dependencies" | while IFS=$'\t' read -r pkg version _; do
    # Normalize version: strip ^, ~, *, etc.
    clean_version=$(echo "$version" | sed -E 's/^[~^><=]+//; s/\s.*$//')

    # Get package metadata from npm
    json_output=$(npm view "$pkg" versions time --json 2>/dev/null)
    if [ -z "$json_output" ]; then
        echo "📦 $pkg@$version"
        echo "   Error: Unable to fetch data (check network or package name)"
        echo ""
        continue
    fi

    # Extract the exact version installed (best effort)
    # Try to find a version that matches the clean prefix
    exact_version=$(echo "$json_output" | jq -r --arg ver "$clean_version" '
      .versions[] | select(startswith($ver) and test("^[0-9]")) | . as $v
      | $v | split(".") | map(tonumber?) | . as $nums
      | select($nums | length == 3 and .[0] != null)
      | $v
    ' | head -1)

    if [ -n "$exact_version" ]; then
        publish_date=$(echo "$json_output" | jq -r --arg ver "$exact_version" '.time[$ver]')
        if [ "$publish_date" = "null" ] || [ -z "$publish_date" ]; then
            publish_date="Not found"
        fi
    else
        exact_version="matched_version_not_found"
        publish_date="Could not resolve exact version"
    fi

    # Output
    echo "📦 $pkg@$version"
    echo "   Resolved: $exact_version"
    echo "   Published: $publish_date"
    echo ""
done

echo "✅ Done!"

