#!/bin/bash

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🗑️  GitHub Release Deletion Tool${NC}"

# Check if version is provided
if [ -z "$1" ]; then
    echo -e "${RED}❌ Please provide a version to delete${NC}"
    echo -e "${YELLOW}Usage: $0 <version>${NC}"
    echo -e "${YELLOW}Example: $0 1.3.5${NC}"
    exit 1
fi

VERSION=$1
echo -e "${YELLOW}Version to delete: ${VERSION}${NC}"

# Check if we're in a git repository
if [ ! -d ".git" ]; then
    echo -e "${RED}❌ Not in a git repository${NC}"
    exit 1
fi

# Get repository info
REPO_URL=$(git remote get-url origin)
if [[ $REPO_URL == *"github.com"* ]]; then
    # Extract owner/repo from git URL
    if [[ $REPO_URL == *"git@github.com:"* ]]; then
        REPO_PATH=$(echo $REPO_URL | sed 's/git@github.com://' | sed 's/\.git$//')
    elif [[ $REPO_URL == *"https://github.com/"* ]]; then
        REPO_PATH=$(echo $REPO_URL | sed 's/https:\/\/github.com\///' | sed 's/\.git$//')
    else
        echo -e "${RED}❌ Could not parse GitHub repository URL${NC}"
        exit 1
    fi
    
    echo -e "${YELLOW}Repository: ${REPO_PATH}${NC}"
    
    # Check if release exists
    echo -e "${YELLOW}🔍 Checking if release v${VERSION} exists...${NC}"
    RELEASE_INFO=$(curl -s "https://api.github.com/repos/${REPO_PATH}/releases/tags/v${VERSION}")
    RELEASE_ID=$(echo "$RELEASE_INFO" | jq -r '.id')
    
    if [ "$RELEASE_ID" = "null" ] || [ -z "$RELEASE_ID" ]; then
        echo -e "${YELLOW}ℹ️ Release v${VERSION} does not exist${NC}"
        exit 0
    fi
    
    echo -e "${GREEN}✅ Release v${VERSION} found (ID: ${RELEASE_ID})${NC}"
    
    # Confirm deletion
    echo -e "${RED}⚠️  WARNING: This will permanently delete the release v${VERSION}${NC}"
    read -p "Are you sure you want to continue? (y/N): " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}🗑️  Deleting release v${VERSION}...${NC}"
        
        # Delete the release
        RESPONSE=$(curl -s -w "%{http_code}" -X DELETE \
            -H "Authorization: token $GITHUB_TOKEN" \
            "https://api.github.com/repos/${REPO_PATH}/releases/${RELEASE_ID}")
        
        HTTP_CODE="${RESPONSE: -3}"
        
        if [ "$HTTP_CODE" = "204" ]; then
            echo -e "${GREEN}✅ Release v${VERSION} deleted successfully!${NC}"
        else
            echo -e "${RED}❌ Failed to delete release (HTTP ${HTTP_CODE})${NC}"
            echo -e "${YELLOW}Make sure you have GITHUB_TOKEN set with appropriate permissions${NC}"
            exit 1
        fi
    else
        echo -e "${YELLOW}❌ Deletion cancelled${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  Not a GitHub repository, cannot delete release${NC}"
fi 