#!/bin/bash

# Gitea Wiki Upload Script
# Uploads homelab documentation to Gitea wiki via API

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}🚀 Starting Gitea Wiki documentation upload...${NC}"
echo ""

# Function to create or update wiki page
create_wiki_page() {
    local title="$1"
    local file_path="$2"
    local message="$3"

    if [[ ! -f "$file_path" ]]; then
        echo -e "${RED}❌ File not found: $file_path${NC}"
        return 1
    fi

    echo -e "${YELLOW}📄 Creating/updating wiki page: $title${NC}"

    # Read file content and escape for JSON
    local content
    content=$(cat "$file_path" | jq -Rs .)

    # Create JSON payload
    local json_payload
    json_payload=$(jq -n \
        --arg title "$title" \
        --argjson content "$content" \
        --arg message "$message" \
        '{
            title: $title,
            content_base64: ($content | @base64),
            message: $message
        }')

    # Make API request
    local response
    response=$(curl -s -w "%{http_code}" -o /tmp/wiki_response.json \
        -X POST \
        -H "Authorization: token $GITEA_TOKEN" \
        -H "Content-Type: application/json" \
        -d "$json_payload" \
        "$BASE_URL/new")

    local http_code="${response: -3}"

    if [[ "$http_code" == "201" ]]; then
        echo -e "${GREEN}✅ Successfully created: $title${NC}"
        echo -e "${BLUE}🌐 View at: $GITEA_URL/$REPO_OWNER/$REPO_NAME/wiki/$title${NC}"
        return 0
    elif [[ "$http_code" == "409" ]]; then
        # Page exists, try to update it
        echo -e "${YELLOW}📝 Page exists, updating: $title${NC}"

        response=$(curl -s -w "%{http_code}" -o /tmp/wiki_response.json \
            -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$json_payload" \
            "$BASE_URL/$title")

        http_code="${response: -3}"

        if [[ "$http_code" == "200" ]]; then
            echo -e "${GREEN}✅ Successfully updated: $title${NC}"
            echo -e "${BLUE}🌐 View at: $GITEA_URL/$REPO_OWNER/$REPO_NAME/wiki/$title${NC}"
            return 0
        else
            echo -e "${RED}❌ Failed to update $title (HTTP $http_code)${NC}"
            cat /tmp/wiki_response.json 2>/dev/null || echo "No response body"
            return 1
        fi
    else
        echo -e "${RED}❌ Failed to create $title (HTTP $http_code)${NC}"
        cat /tmp/wiki_response.json 2>/dev/null || echo "No response body"
        return 1
    fi
}

# Function to sanitize title for wiki page names
sanitize_title() {
    echo "$1" | sed 's/[^a-zA-Z0-9_-]/_/g' | sed 's/__*/_/g' | sed 's/^_\|_$//g'
}

# Success and failure counters
success_count=0
total_count=0

echo -e "${BLUE}📋 Creating main homelab wiki index...${NC}"

# Create main wiki index page
cat > /tmp/wiki_index.md << 'EOF'
# Homelab Documentation Wiki

*This wiki is automatically synchronized from the homelab Git repository*

## 🎯 Quick Navigation

### 📖 Main Documentation
- [Repository README](README) - Complete repository overview
- [Documentation Index](Documentation-Index) - Master navigation guide
- [Operational Status](Operational-Status) - Current system status

### 🔧 Administration & Operations
- [GitOps Comprehensive Guide](GitOps-Comprehensive-Guide) - Complete deployment procedures ⭐
- [DokuWiki Integration](DokuWiki-Integration) - Documentation mirroring setup
- [Documentation Audit Report](Documentation-Audit-Report) - Recent improvements

### 🏗️ Infrastructure
- [Infrastructure Health Report](Infrastructure-Health-Report) - System health status
- [Monitoring Architecture](Monitoring-Architecture) - Monitoring setup
- [GitOps Deployment Guide](GitOps-Deployment-Guide) - Deployment procedures

### 📚 Runbooks & Procedures
- [Add New Service](Add-New-Service) - Service deployment runbook

## 🌐 Access Points

- **Git Repository**: https://git.vish.gg/Vish/homelab
- **DokuWiki Mirror**: http://atlantis.vish.local:8399/doku.php?id=homelab:start
- **Gitea Wiki**: https://git.vish.gg/Vish/homelab/wiki

## 📊 Repository Status

- **GitOps Status**: ✅ 18 active stacks, 50+ containers
- **Servers**: 5 active (Atlantis, Calypso, Gaming VPS, Homelab VM, Concord NUC)
- **Services**: 100+ containerized services
- **Documentation**: Comprehensive guides and runbooks

---

**Last Updated**: $(date)
**Source Repository**: https://git.vish.gg/Vish/homelab
**Maintainer**: Homelab Administrator
EOF

total_count=$((total_count + 1))
if create_wiki_page "Home" "/tmp/wiki_index.md" "Updated homelab wiki index with navigation"; then
    success_count=$((success_count + 1))
fi

# Upload key documentation files
declare -A wiki_files=(
    ["README"]="README.md"
    ["Documentation-Index"]="docs/INDEX.md"
    ["GitOps-Comprehensive-Guide"]="docs/admin/GITOPS_COMPREHENSIVE_GUIDE.md"
    ["DokuWiki-Integration"]="docs/admin/DOKUWIKI_INTEGRATION.md"
    ["Documentation-Audit-Report"]="DOCUMENTATION_AUDIT_REPORT.md"
    ["Operational-Status"]="OPERATIONAL_STATUS.md"
    ["Infrastructure-Health-Report"]="docs/infrastructure/INFRASTRUCTURE_HEALTH_REPORT.md"
    ["Monitoring-Architecture"]="MONITORING_ARCHITECTURE.md"
    ["GitOps-Deployment-Guide"]="GITOPS_DEPLOYMENT_GUIDE.md"
    ["Add-New-Service"]="docs/runbooks/add-new-service.md"
)

echo ""
echo -e "${BLUE}📚 Uploading documentation files...${NC}"

for wiki_title in "${!wiki_files[@]}"; do
    file_path="${wiki_files[$wiki_title]}"

    if [[ -f "$file_path" ]]; then
        echo ""
        echo -e "${YELLOW}📄 Processing: $file_path → $wiki_title${NC}"
        total_count=$((total_count + 1))

        if create_wiki_page "$wiki_title" "$file_path" "Updated $wiki_title from repository"; then
            success_count=$((success_count + 1))
        fi
    else
        echo -e "${RED}⚠️  File not found: $file_path${NC}"
        total_count=$((total_count + 1))
    fi
done

echo ""
echo -e "${BLUE}🎯 Upload Summary:${NC}"
echo -e "${GREEN}✅ Successful: $success_count/$total_count${NC}"
echo -e "${RED}❌ Failed: $((total_count - success_count))/$total_count${NC}"

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

if [[ $success_count -eq $total_count ]]; then
    echo ""
    echo -e "${GREEN}✅ Gitea Wiki upload completed successfully!${NC}"
    exit 0
else
    echo ""
    echo -e "${YELLOW}⚠️  Gitea Wiki upload completed with some failures.${NC}"
    exit 1
fi
