#!/bin/bash
# Diagnostic script to determine why package linking is failing
# This will help identify the correct package names and API format

set -e

if [ -z "$GITEA_TOKEN" ]; then
  echo "ERROR: GITEA_TOKEN environment variable is required"
  echo "Get your token from: https://git.mosaicstack.dev/user/settings/applications"
  echo "Then run: GITEA_TOKEN='your_token' ./diagnose-package-link.sh"
  exit 1
fi

BASE_URL="https://git.mosaicstack.dev"
OWNER="mosaic"
REPO="stack"

echo "=== Gitea Package Link Diagnostics ==="
echo "Gitea URL: $BASE_URL"
echo "Owner: $OWNER"
echo "Repository: $REPO"
echo ""

# Step 1: List all packages for the owner
echo "Step 1: Listing all container packages for owner '$OWNER'..."
PACKAGES_JSON=$(curl -s -X GET \
  -H "Authorization: token $GITEA_TOKEN" \
  "$BASE_URL/api/v1/packages/$OWNER?type=container&limit=20")

echo "$PACKAGES_JSON" | jq -r '.[] | "  - Name: \(.name), Type: \(.type), Version: \(.version)"' 2>/dev/null || {
  echo "  Response (raw):"
  echo "$PACKAGES_JSON" | head -20
}
echo ""

# Step 2: Extract package names and test linking for each
echo "Step 2: Testing package link API for each discovered package..."
PACKAGE_NAMES=$(echo "$PACKAGES_JSON" | jq -r '.[].name' 2>/dev/null)

if [ -z "$PACKAGE_NAMES" ]; then
  echo "  WARNING: No packages found or unable to parse response"
  echo "  Falling back to known package names..."
  PACKAGE_NAMES="stack-api stack-web stack-postgres stack-openbao stack-orchestrator"
fi

for package in $PACKAGE_NAMES; do
  echo ""
  echo "  Testing package: $package"

  # Test Format 1: Standard format
  echo "    Format 1: POST /api/v1/packages/$OWNER/container/$package/-/link/$REPO"
  STATUS=$(curl -s -o /tmp/link-response.txt -w "%{http_code}" -X POST \
    -H "Authorization: token $GITEA_TOKEN" \
    -H "Content-Type: application/json" \
    "$BASE_URL/api/v1/packages/$OWNER/container/$package/-/link/$REPO")
  echo "    Status: $STATUS"
  if [ "$STATUS" != "404" ]; then
    echo "    Response:"
    cat /tmp/link-response.txt | head -5
  fi

  # Test Format 2: Without /-/
  echo "    Format 2: POST /api/v1/packages/$OWNER/container/$package/link/$REPO"
  STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST \
    -H "Authorization: token $GITEA_TOKEN" \
    "$BASE_URL/api/v1/packages/$OWNER/container/$package/link/$REPO")
  echo "    Status: $STATUS"
done

echo ""
echo "=== Analysis ==="
echo "Expected successful status codes:"
echo "  - 200/201: Successfully linked"
echo "  - 204: No content (success)"
echo "  - 400: Already linked (also success)"
echo ""
echo "Error status codes:"
echo "  - 404: Endpoint or package doesn't exist"
echo "  - 401: Authentication failed"
echo "  - 403: Permission denied"
echo ""
echo "If all attempts return 404, possible causes:"
echo "  1. Gitea version < 1.24.0 (check with: curl $BASE_URL/api/v1/version)"
echo "  2. Package names are different than expected"
echo "  3. Package type is not 'container'"
echo "  4. API endpoint path has changed"
echo ""
echo "Next steps:"
echo "  1. Check package names on web UI: $BASE_URL/$OWNER/-/packages"
echo "  2. Check Gitea version in footer of: $BASE_URL"
echo "  3. Try linking manually via web UI to verify it works"
echo "  4. Check Gitea logs for API errors"
