#!/bin/bash

# Gitea Wiki Cleanup Script
# Removes old flat structure pages while preserving new organized structure

set -e

# Configuration
GITEA_TOKEN=REDACTED_TOKEN
GITEA_URL="https://git.vish.gg"
REPO_OWNER="Vish"
REPO_NAME="homelab"
BASE_URL="$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/wiki"

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

echo -e "${BLUE}🧹 Cleaning up Gitea Wiki - removing old flat structure...${NC}"

# Pages to KEEP (our new organized structure)
declare -a KEEP_PAGES=(
    "Home"
    "Administration"
    "Infrastructure"
    "Services"
    "Getting-Started"
    "Troubleshooting"
    "Advanced"
    # Key organized pages
    "GitOps-Guide"
    "Deployment-Guide"
    "Operational-Status"
    "Development-Guide"
    "Agent-Memory"
    "Infrastructure-Overview"
    "Infrastructure-Health"
    "SSH-Guide"
    "User-Access-Guide"
    "Security-Guide"
    "Service-Index"
    "Dashboard-Setup"
    "Homarr-Setup"
    "ARR-Suite-Enhancements"
    "Beginner-Quickstart"
    "What-Is-Homelab"
    "Prerequisites"
    "Architecture-Overview"
    "Emergency-Guide"
    "Common-Issues"
    "Container-Diagnosis"
    "Disaster-Recovery"
    "Hardware-Inventory"
)

# Function to check if page should be kept
should_keep_page() {
    local page_title="$1"
    for keep_page in "${KEEP_PAGES[@]}"; do
        if [[ "$page_title" == "$keep_page" ]]; then
            return 0
        fi
    done
    return 1
}

# Get all wiki pages
echo -e "${BLUE}📋 Fetching all wiki pages...${NC}"
all_pages=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$BASE_URL/pages?limit=500")

if [[ -z "$all_pages" ]] || [[ "$all_pages" == "null" ]]; then
    echo -e "${RED}❌ Failed to fetch wiki pages${NC}"
    exit 1
fi

# Parse page titles
page_titles=$(echo "$all_pages" | jq -r '.[].title')
total_pages=$(echo "$page_titles" | wc -l)

echo -e "${BLUE}📊 Found $total_pages total wiki pages${NC}"

# Count pages to keep vs delete
keep_count=0
delete_count=0
declare -a pages_to_delete=()

while IFS= read -r page_title; do
    if should_keep_page "$page_title"; then
        ((keep_count++))
        echo -e "${GREEN}✅ KEEP: $page_title${NC}"
    else
        ((delete_count++))
        pages_to_delete+=("$page_title")
        echo -e "${YELLOW}🗑️  DELETE: $page_title${NC}"
    fi
done <<< "$page_titles"

echo ""
echo -e "${BLUE}📊 Cleanup Summary:${NC}"
echo -e "${GREEN}✅ Pages to keep: $keep_count${NC}"
echo -e "${YELLOW}🗑️  Pages to delete: $delete_count${NC}"
echo -e "${BLUE}📄 Total pages: $total_pages${NC}"

# Confirm deletion
echo ""
echo -e "${YELLOW}⚠️  This will DELETE $delete_count wiki pages!${NC}"
echo -e "${YELLOW}⚠️  Only the organized structure will remain.${NC}"
read -p "Continue with cleanup? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${BLUE}🚫 Cleanup cancelled${NC}"
    exit 0
fi

# Delete old pages
echo ""
echo -e "${BLUE}🗑️  Starting deletion of old pages...${NC}"

deleted_count=0
failed_count=0

for page_title in "${pages_to_delete[@]}"; do
    echo -e "${YELLOW}🗑️  Deleting: $page_title${NC}"

    response=$(curl -s -w "%{http_code}" -o /tmp/delete_response.json \
        -X DELETE \
        -H "Authorization: token $GITEA_TOKEN" \
        "$BASE_URL/$page_title")

    http_code="${response: -3}"

    if [[ "$http_code" == "204" ]] || [[ "$http_code" == "200" ]]; then
        echo -e "${GREEN}✅ Deleted: $page_title${NC}"
        ((deleted_count++))
    else
        echo -e "${RED}❌ Failed to delete: $page_title (HTTP $http_code)${NC}"
        ((failed_count++))
    fi

    # Small delay to avoid rate limiting
    sleep 0.1
done

echo ""
echo -e "${BLUE}🎯 Gitea Wiki Cleanup Complete!${NC}"
echo -e "${GREEN}✅ Successfully deleted: $deleted_count pages${NC}"
echo -e "${RED}❌ Failed to delete: $failed_count pages${NC}"
echo -e "${GREEN}📚 Organized pages remaining: $keep_count${NC}"

# Get final page count
final_page_count=$(curl -s -H "Authorization: token $GITEA_TOKEN" "$BASE_URL/pages?limit=500" | jq '. | length' 2>/dev/null || echo "unknown")
echo ""
echo -e "${GREEN}📊 Final Wiki Statistics:${NC}"
echo -e "${GREEN}   Total Pages: $final_page_count${NC}"
echo -e "${GREEN}   Structure: ✅ Clean organized hierarchy${NC}"
echo -e "${GREEN}   Old Pages Removed: $deleted_count${NC}"

echo ""
echo -e "${GREEN}🌐 Clean Gitea Wiki available at:${NC}"
echo -e "   ${BLUE}https://git.vish.gg/$REPO_OWNER/$REPO_NAME/wiki${NC}"

if [[ $failed_count -eq 0 ]]; then
    echo ""
    echo -e "${GREEN}✅ Gitea Wiki cleanup completed successfully!${NC}"
    echo -e "${GREEN}🎉 Wiki now has clean, organized structure only!${NC}"
    exit 0
else
    echo ""
    echo -e "${YELLOW}⚠️  Wiki cleanup completed with some issues.${NC}"
    echo -e "${YELLOW}📊 $deleted_count pages deleted, $failed_count failed.${NC}"
    exit 1
fi
