#!/bin/bash
# Create Gitea release with build artifacts
# Usage: create-release.sh <version> [notes]
set -euo pipefail

VERSION=${1:-"v1.0.0"}
NOTES=${2:-"Release $VERSION"}
GITEA_URL="http://10.10.10.40:3000"
GITEA_TOKEN="admin:TaskTeam2026!"
REPO="admin/task-team"

cd /opt/task-team

echo "[$(date +%H:%M:%S)] Creating release $VERSION..."

# Create and push tag
if git rev-parse "$VERSION" >/dev/null 2>&1; then
    echo "Tag $VERSION already exists, skipping tag creation"
else
    git tag -a "$VERSION" -m "$NOTES"
    echo "Tag $VERSION created"
fi

# Push tag to Gitea
git push origin "$VERSION" 2>/dev/null || echo "Tag already pushed"

# Create release via Gitea API
RELEASE_RESP=$(curl -s -u "$GITEA_TOKEN" -X POST "$GITEA_URL/api/v1/repos/$REPO/releases"   -H "Content-Type: application/json"   -d "{\"tag_name\":\"$VERSION\",\"name\":\"Task Team $VERSION\",\"body\":\"$NOTES\",\"draft\":false,\"prerelease\":false}")

RELEASE_ID=$(echo "$RELEASE_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get(\"id\",\"\"))" 2>/dev/null || echo "")

if [ -z "$RELEASE_ID" ]; then
    echo "WARN: Could not create release (may already exist)"
    echo "Response: $RELEASE_RESP"
    # Try to get existing release
    RELEASE_ID=$(curl -s -u "$GITEA_TOKEN" "$GITEA_URL/api/v1/repos/$REPO/releases/tags/$VERSION" |         python3 -c "import sys,json; print(json.load(sys.stdin).get(\"id\",\"\"))" 2>/dev/null || echo "")
fi

echo "Release ID: $RELEASE_ID"

# Upload APK if exists
APK_DIR="/opt/task-team/mobile/dist/android"
APK=$(ls -t $APK_DIR/*.apk 2>/dev/null | head -1)
if [ -n "${APK:-}" ] && [ -f "$APK" ] && [ -n "$RELEASE_ID" ]; then
    echo "Uploading APK: $APK"
    curl -s -u "$GITEA_TOKEN" -X POST "$GITEA_URL/api/v1/repos/$REPO/releases/$RELEASE_ID/assets"       -F "attachment=@$APK"       -F "name=task-team-$VERSION.apk" >/dev/null
    echo "APK attached to release"
fi

# Upload web bundle if exists
WEB_BUNDLE="/opt/task-team/web/.next"
if [ -d "$WEB_BUNDLE" ] && [ -n "$RELEASE_ID" ]; then
    BUNDLE_FILE="/tmp/task-team-web-$VERSION.tar.gz"
    tar czf "$BUNDLE_FILE" -C /opt/task-team/web .next public package.json next.config.ts 2>/dev/null || true
    if [ -f "$BUNDLE_FILE" ]; then
        curl -s -u "$GITEA_TOKEN" -X POST "$GITEA_URL/api/v1/repos/$REPO/releases/$RELEASE_ID/assets"           -F "attachment=@$BUNDLE_FILE"           -F "name=task-team-web-$VERSION.tar.gz" >/dev/null
        rm -f "$BUNDLE_FILE"
        echo "Web bundle attached to release"
    fi
fi

echo "[$(date +%H:%M:%S)] Done: $GITEA_URL/$REPO/releases/tag/$VERSION"
