#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VERSION="$1"
ZIP_PATH="$2"
DMG_PATH="$3"

: "${GITEA_TOKEN:?Set GITEA_TOKEN in .signing.env}"
: "${GITEA_OWNER:?Set GITEA_OWNER in .signing.env}"
: "${GITEA_REPO:?Set GITEA_REPO in .signing.env}"

TARGET_COMMIT="${GITEA_TARGET_COMMIT:-$(git -C "$ROOT_DIR" rev-parse HEAD)}"
API_BASE="${GITEA_API_BASE:-https://git.24unix.net/api/v1}"
API_BASE="${API_BASE%/}"
RELEASE_TAG="v${VERSION}"
API_URL="${API_BASE}/repos/${GITEA_OWNER}/${GITEA_REPO}"
CHANGELOG_FILE="$ROOT_DIR/CHANGELOG.md"

if ! command -v jq >/dev/null 2>&1; then
  echo "❌ jq is required to parse Gitea responses." >&2
  exit 1
fi

# Extract changelog for this version
extract_changelog() {
  local version="$1"
  local changelog_file="$2"

  if [[ ! -f "$changelog_file" ]]; then
    echo ""
    return
  fi

  awk -v ver="## $version" '
    /^## / {
      if (found) exit
      if ($0 ~ ver) {
        found=1
        next
      }
    }
    found { print }
  ' "$changelog_file"
}

CHANGELOG_BODY="$(extract_changelog "$VERSION" "$CHANGELOG_FILE")"
if [[ -z "$CHANGELOG_BODY" ]]; then
  CHANGELOG_BODY="See commit history for details."
fi

PRERELEASE_FLAG="${GITEA_PRERELEASE:-false}"

create_payload="$(jq -n \
  --arg tag "$RELEASE_TAG" \
  --arg name "iKeyMon ${VERSION}" \
  --arg target "$TARGET_COMMIT" \
  --arg body "$CHANGELOG_BODY" \
  --argjson prerelease "$PRERELEASE_FLAG" \
  '{ tag_name: $tag, name: $name, target_commitish: $target, body: $body, draft: false, prerelease: $prerelease }')"

response_file="$(mktemp)"
http_code=$(curl -sS -w "%{http_code}" -o "$response_file" \
  -H "Authorization: token ${GITEA_TOKEN}" \
  -H "Content-Type: application/json" \
  -X POST \
  -d "$create_payload" \
  "${API_URL}/releases")

if [[ "$http_code" == "201" ]]; then
  echo "✅ Created release ${RELEASE_TAG}"
elif [[ "$http_code" == "409" ]]; then
  echo "ℹ️ Release ${RELEASE_TAG} already exists, fetching existing ID."
else
  echo "❌ Failed to create release (HTTP ${http_code}):"
  cat "$response_file"
  rm -f "$response_file"
  exit 1
fi

if [[ "$http_code" == "409" ]]; then
  curl -sS \
    -H "Authorization: token ${GITEA_TOKEN}" \
    "${API_URL}/releases/tags/${RELEASE_TAG}" >"$response_file"
fi

release_id=$(jq -r '.id' "$response_file")
rm -f "$response_file"

if [[ -z "$release_id" || "$release_id" == "null" ]]; then
  echo "❌ Could not determine release ID for ${RELEASE_TAG}"
  exit 1
fi

delete_existing_asset() {
  local filename="$1"
  local asset_id
  asset_id="$(curl -sS \
    -H "Authorization: token ${GITEA_TOKEN}" \
    "${API_URL}/releases/${release_id}/assets" | jq -r --arg name "$filename" '.[] | select(.name == $name) | .id' | head -n 1)"
  if [[ -n "$asset_id" && "$asset_id" != "null" ]]; then
    echo "🗑️  Removing existing asset ${filename}"
    curl -sS \
      -H "Authorization: token ${GITEA_TOKEN}" \
      -X DELETE \
      "${API_URL}/releases/${release_id}/assets/${asset_id}" >/dev/null
  fi
}

upload_asset() {
  local file="$1"
  local filename
  filename="$(basename "$file")"

  delete_existing_asset "$filename"

  echo "⬆️  Uploading ${filename}"
  curl -sS \
    -H "Authorization: token ${GITEA_TOKEN}" \
    -F "attachment=@${file}" \
    "${API_URL}/releases/${release_id}/assets" >/dev/null
}

upload_asset "$ZIP_PATH"
upload_asset "$DMG_PATH"

echo "🎉 Release ${RELEASE_TAG} assets uploaded."
