#!/usr/bin/env bash
# Publish a release to Gitea (git.lazypugs.com).
#
# Auth: needs a Gitea token with 'write:repository'. Never hardcode it.
#   export GITEA_TOKEN=...        # from your shell / password manager
#   ./tools/publish.sh            # or: GAME=GundamBreaker4 TAG=v1.0.1 ./tools/publish.sh
#
# Steps: build the game's zip -> push branch+tag -> create release -> upload asset.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"; cd "$HERE"

HOST="${GITEA_HOST:-https://git.lazypugs.com}"
OWNER="${GITEA_OWNER:-ckoch}"
REPO="${GITEA_REPO:-UltraWidePatches}"
GAME="${GAME:-GundamBreaker4}"
TAG="${TAG:-v1.0.0}"
NOTES="${NOTES:-games/$GAME/README.md}"
[ -f "$NOTES" ] || NOTES="RELEASE_NOTES.md"
API="$HOST/api/v1"

[ -n "${GITEA_TOKEN:-}" ] || { echo "[!] GITEA_TOKEN is not set. Create one at $HOST/user/settings/applications (scope: write:repository)"; exit 1; }
AUTH=(-H "Authorization: token $GITEA_TOKEN")
ZIPNAME="${GAME}_UltraWide_Fix.zip"

# 1. build the artifact -- do NOT swallow output; a failure here used to exit
# the whole script silently because stdout went to /dev/null under `set -e`.
if ! bash tools/build_release.sh "$GAME"; then
  echo "[!] build_release.sh failed for game '$GAME' (see above)"; exit 1
fi
ZIP="dist/$ZIPNAME"
[ -f "$ZIP" ] || { echo "[!] build produced no $ZIP"; exit 1; }
echo "[+] Built $ZIP"

# 2. push code + tag
git push origin main
if ! git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
  git tag -a "$TAG" -m "$TAG"
  echo "[+] Created tag $TAG at $(git rev-parse --short HEAD)"
fi
git push origin "$TAG" 2>&1 | tail -1

# 3. create the release (or reuse if it already exists)
REL_ID=$(curl -sf "${AUTH[@]}" "$API/repos/$OWNER/$REPO/releases/tags/$TAG" 2>/dev/null \
         | python3 -c "import sys,json;print(json.load(sys.stdin)['id'])" 2>/dev/null || true)

if [ -z "$REL_ID" ]; then
  BODY=$(python3 -c "import json,sys;print(json.dumps(open(sys.argv[1]).read()))" "$NOTES")
  REL_ID=$(curl -sf "${AUTH[@]}" -H "Content-Type: application/json" \
      -d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":$BODY}" \
      "$API/repos/$OWNER/$REPO/releases" \
    | python3 -c "import sys,json;print(json.load(sys.stdin)['id'])")
  echo "[+] Created release $TAG (id=$REL_ID)"
else
  echo "[i] Release $TAG exists (id=$REL_ID); replacing asset"
  OLD=$(curl -sf "${AUTH[@]}" "$API/repos/$OWNER/$REPO/releases/$REL_ID" \
        | ZIPNAME="$ZIPNAME" python3 -c "
import sys, json, os
d = json.load(sys.stdin)
want = os.environ['ZIPNAME']
print(next((str(a['id']) for a in d.get('assets', []) if a['name'] == want), ''))" 2>/dev/null || true)
  if [ -n "$OLD" ]; then
    curl -sf -X DELETE "${AUTH[@]}" "$API/repos/$OWNER/$REPO/releases/$REL_ID/assets/$OLD" >/dev/null \
      && echo "[i] removed previous asset"
  fi
fi

# 4. upload the zip
curl -sf "${AUTH[@]}" -F "attachment=@$ZIP" \
  "$API/repos/$OWNER/$REPO/releases/$REL_ID/assets?name=$ZIPNAME" >/dev/null
echo "[+] Uploaded $ZIPNAME"

echo
echo "[+] Done: $HOST/$OWNER/$REPO/releases/tag/$TAG"
