#!/bin/bash

# Organized Hierarchical Gitea Wiki Upload Script
# Creates a properly structured wiki with categories and navigation

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'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

echo -e "${BLUE}🚀 Starting ORGANIZED Gitea Wiki upload with hierarchical structure...${NC}"

# 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: $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
        }')

    # Try to create new page first
    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}✅ Created: $title${NC}"
        return 0
    elif [[ "$http_code" == "409" ]] || [[ "$http_code" == "400" ]]; then
        # Page exists, try to update it
        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}✅ Updated: $title${NC}"
            return 0
        else
            echo -e "${RED}❌ Failed to update $title (HTTP $http_code)${NC}"
            return 1
        fi
    else
        echo -e "${RED}❌ Failed to create $title (HTTP $http_code)${NC}"
        return 1
    fi
}

# Success counter
success_count=0
total_count=0

echo -e "${BLUE}📋 Creating main navigation hub...${NC}"

# Create REDACTED_APP_PASSWORD with organized navigation
cat > /tmp/organized_wiki_home.md << 'EOF'
# 🏠 Homelab Documentation Wiki

*Complete organized documentation for Vish's homelab infrastructure*
*Last Updated: $(date)*

## 🎯 Quick Navigation

### 📖 **Core Documentation**
- [📋 Repository README](README) - Complete repository overview
- [📚 Documentation Index](Documentation-Index) - Master navigation guide
- [📊 Operational Status](Admin-Operational-Status) - Current system status
- [📝 Changelog](Changelog) - Version history and updates

---

## 🔧 **Administration & Operations**

### 🚀 Deployment & GitOps
- [🎯 GitOps Comprehensive Guide](Admin-Gitops-Comprehensive-Guide) - Complete deployment procedures ⭐
- [📋 Deployment Documentation](Admin-Deployment-Documentation) - Deployment procedures
- [🔄 Deployment Workflow](Admin-Deployment-Workflow) - Step-by-step workflows
- [📊 Documentation Audit Report](Admin-Documentation-Audit-Report) - Audit results

### 🔧 System Administration
- [🛠️ Development Guide](Admin-Development) - Development procedures
- [🤖 Agent Memory](Admin-Agents) - AI agent context and memory
- [🔐 Security Hardening](Security-Server-Hardening) - Security procedures
- [📈 Monitoring Setup](Admin-Monitoring-Setup) - Monitoring configuration
- [💾 Backup Strategies](Admin-Backup-Strategies) - Backup procedures
- [🔧 Maintenance](Admin-Maintenance) - Maintenance procedures

### 📚 Integration Documentation
- [📖 DokuWiki Integration](Admin-Dokuwiki-Integration) - External wiki setup
- [📖 Gitea Wiki Integration](Admin-Gitea-Wiki-Integration) - Native wiki setup

---

## 🏗️ **Infrastructure**

### 🌐 Core Infrastructure
- [🏗️ Infrastructure Overview](Infrastructure-Infrastructure-Overview) - Complete infrastructure guide
- [📊 Infrastructure Health](Infrastructure-Infrastructure-Health-Report) - System health status
- [🌐 Networking](Infrastructure-Networking) - Network configuration
- [💾 Storage](Infrastructure-Storage) - Storage configuration
- [🖥️ Hosts](Infrastructure-Hosts) - Host management

### 🔐 Access & Security
- [🔑 SSH Access Guide](Infrastructure-Ssh-Access-Guide) - SSH access procedures
- [👥 User Access Guide](Infrastructure-User-Access-Guide) - User access management
- [🔐 Authentik SSO](Infrastructure-Authentik-Sso) - Single sign-on setup

### 🌐 Network Services
- [🚇 Tailscale Setup](Infrastructure-Tailscale-Setup-Guide) - VPN configuration
- [☁️ Cloudflare Tunnels](Infrastructure-Cloudflare-Tunnels) - Tunnel configuration
- [☁️ Cloudflare DNS](Infrastructure-Cloudflare-Dns) - DNS configuration
- [🌐 Network Performance](Infrastructure-Network-Performance-Tuning) - Performance optimization

### 🏠 Host Management
- [📊 Hardware Inventory](Infrastructure-Hardware-Inventory) - Hardware catalog
- [🔄 Atlantis Migration](Infrastructure-Atlantis-Migration) - Migration procedures
- [📱 Mobile Setup](Infrastructure-Mobile-Device-Setup) - Mobile device configuration
- [💻 Laptop Setup](Infrastructure-Laptop-Travel-Setup) - Laptop configuration

---

## 🎯 **Services**

### 📊 Service Management
- [📋 Service Index](Services-Index) - All available services
- [✅ Verified Service Inventory](Services-Verified-Service-Inventory) - Service catalog
- [📊 Dashboard Setup](Services-Dashboard-Setup) - Dashboard configuration
- [🎨 Homarr Setup](Services-Homarr-Setup) - Homarr dashboard setup
- [🎨 Theme Park](Services-Theme-Park) - UI theming

### 🎬 Media Services
- [🎬 ARR Suite Enhancements](Services-Arr-Suite-Enhancements-Feb2025) - Media stack improvements
- [🎬 ARR Suite Language Config](Arr-Suite-Language-Configuration) - Language configuration

### 💬 Communication Services
- [💬 Stoatchat Setup](Services-Stoatchat-Setup) - Chat platform setup
- [💬 Stoatchat Next Steps](Services-Stoatchat-Next-Steps) - Future improvements
- [🗨️ Matrix Setup](Services-Matrix-Setup) - Matrix server configuration
- [💬 Mastodon Setup](Services-Mastodon-Setup) - Social media platform
- [💬 Mattermost Setup](Services-Mattermost-Setup) - Team communication

### 🔧 Development Services
- [🤖 OpenHands](Services-Openhands) - AI development assistant
- [📄 Paperless](Services-Paperless) - Document management
- [📝 Reactive Resume](Services-Reactive-Resume) - Resume builder

### 📋 Individual Services
- [📋 Individual Service Docs](Services-Individual-Index) - Complete service documentation

---

## 🚀 **Getting Started**

### 🎯 Quick Start
- [⚡ Beginner Quickstart](Getting-Started-Beginner-Quickstart) - Quick start guide
- [❓ What Is Homelab](Getting-Started-What-Is-Homelab) - Introduction to homelabs
- [📋 Prerequisites](Getting-Started-Prerequisites) - Requirements and setup
- [🏗️ Architecture](Getting-Started-Architecture) - System architecture overview

### 📚 Comprehensive Guides
- [📖 Beginner Homelab Guide](Getting-Started-Beginner-Homelab-Guide) - Complete beginner guide
- [🛒 Shopping Guide](Getting-Started-Shopping-Guide) - Hardware recommendations
- [🔄 Complete Rebuild Guide](Getting-Started-Complete-Rebuild-Guide) - Full rebuild procedures
- [⚡ Quick Start](Getting-Started-Quick-Start) - Quick deployment guide

---

## 🛠️ **Troubleshooting**

### 🚨 Emergency Procedures
- [🚨 Emergency Access Guide](Troubleshooting-Emergency-Access-Guide) - Emergency procedures
- [🔄 Disaster Recovery](Troubleshooting-Disaster-Recovery) - Recovery procedures
- [📋 Recovery Guide](Troubleshooting-Recovery-Guide) - System recovery
- [🔧 Emergency](Troubleshooting-Emergency) - Emergency troubleshooting

### 🔍 Diagnostics
- [❓ Common Issues](Troubleshooting-Common-Issues) - Frequently encountered problems
- [🔍 Diagnostics](Troubleshooting-Diagnostics) - Diagnostic procedures
- [📊 Container Diagnosis](Troubleshooting-Container-Diagnosis-Report) - Container troubleshooting
- [⚡ Performance](Troubleshooting-Performance) - Performance troubleshooting

### 🔧 Specific Issues
- [🔄 Watchtower Emergency](Troubleshooting-Watchtower-Emergency-Procedures) - Watchtower issues
- [🔐 Authentik SSO Rebuild](Troubleshooting-Authentik-Sso-Rebuild) - SSO troubleshooting
- [🆘 Beginner Troubleshooting](Troubleshooting-Beginner-Troubleshooting) - Beginner help

---

## 🔬 **Advanced Topics**

### 🚀 Growth & Optimization
- [📈 Homelab Maturity Roadmap](Advanced-Homelab-Maturity-Roadmap) - Growth planning
- [⚡ Repository Optimization](Advanced-Repository-Optimization-Guide) - Optimization guide
- [📊 Stack Comparison Report](Advanced-Stack-Comparison-Report) - Technology comparisons
- [📈 Scaling](Advanced-Scaling) - Scaling strategies

### 🏗️ Infrastructure as Code
- [🏗️ Terraform Implementation](Advanced-Terraform-Implementation-Guide) - Infrastructure as code
- [🔄 Terraform Alternatives](Advanced-Terraform-And-Gitops-Alternatives) - Alternative approaches
- [🤖 Ansible](Advanced-Ansible) - Automation with Ansible
- [🔧 Customization](Advanced-Customization) - Advanced customization

### 🔗 Integration
- [🔗 Integrations](Advanced-Integrations) - Service integrations

---

## 📊 **Diagrams & Architecture**

### 🌐 Network Architecture
- [🌐 Network Topology](Diagrams-Network-Topology) - Network diagrams
- [⚡ 10GbE Backbone](Diagrams-10gbe-Backbone) - High-speed networking
- [🚇 Tailscale Mesh](Diagrams-Tailscale-Mesh) - VPN mesh network

### 🏗️ System Architecture
- [🏗️ Service Architecture](Diagrams-Service-Architecture) - Service architecture
- [💾 Storage Topology](Diagrams-Storage-Topology) - Storage layout
- [📍 Location Overview](Diagrams-Location-Overview) - Physical locations

---

## 🖥️ **Hardware**

### 🖥️ Equipment Documentation
- [🖥️ Hardware Overview](Hardware-Readme) - Hardware documentation
- [🌐 Network Equipment](Hardware-Network-Equipment) - Network hardware
- [💾 Atlantis Storage](Hardware-Atlantis-Storage) - Storage hardware
- [🖥️ Guava Server](Hardware-Guava) - Physical server
- [📺 NVIDIA Shield](Hardware-Nvidia-Shield) - Edge device

---

## 📋 **Runbooks & Procedures**

### 🔧 Service Management
- [➕ Add New Service](Runbooks-Add-New-Service) - Service deployment runbook
- [👥 Add New User](Runbooks-Add-New-User) - User management procedures
- [🔄 Service Migration](Runbooks-Service-Migration) - Service migration procedures

### 🔐 Security & Maintenance
- [🔐 Certificate Renewal](Runbooks-Certificate-Renewal) - SSL certificate management
- [💾 Disk Full Procedure](Runbooks-Disk-Full-Procedure) - Storage management

---

## 🌐 **Access Points**

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

---

## 📊 **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**: 300+ organized pages
- **📖 Wiki Coverage**: Complete hierarchical organization

---

*🏠 **Source Repository**: https://git.vish.gg/Vish/homelab*
*👨‍💻 **Maintainer**: Homelab Administrator*
*📚 **Documentation**: Fully organized and navigable*
EOF

total_count=$((total_count + 1))
if create_wiki_page "Home" "/tmp/organized_wiki_home.md" "Created organized hierarchical REDACTED_APP_PASSWORD comprehensive navigation"; then
    success_count=$((success_count + 1))
fi

echo ""
echo -e "${BLUE}📚 Creating category index pages...${NC}"

# Create Administration category index
cat > /tmp/admin_index.md << 'EOF'
# 🔧 Administration & Operations

*Complete administrative documentation for homelab management*

## 🚀 Deployment & GitOps
- [🎯 GitOps Comprehensive Guide](Admin-Gitops-Comprehensive-Guide) - Complete deployment procedures ⭐
- [📋 Deployment Documentation](Admin-Deployment-Documentation) - Deployment procedures
- [🔄 Deployment Workflow](Admin-Deployment-Workflow) - Step-by-step workflows

## 🔧 System Administration
- [🛠️ Development Guide](Admin-Development) - Development procedures
- [🤖 Agent Memory](Admin-Agents) - AI agent context and memory
- [📈 Monitoring Setup](Admin-Monitoring-Setup) - Monitoring configuration
- [💾 Backup Strategies](Admin-Backup-Strategies) - Backup procedures
- [🔧 Maintenance](Admin-Maintenance) - Maintenance procedures

## 📊 Reports & Audits
- [📊 Documentation Audit Report](Admin-Documentation-Audit-Report) - Audit results
- [📊 Operational Status](Admin-Operational-Status) - Current system status

## 📚 Integration Documentation
- [📖 DokuWiki Integration](Admin-Dokuwiki-Integration) - External wiki setup
- [📖 Gitea Wiki Integration](Admin-Gitea-Wiki-Integration) - Native wiki setup

---
[🏠 Back to Home](Home)
EOF

total_count=$((total_count + 1))
if create_wiki_page "Administration-Index" "/tmp/admin_index.md" "Created administration category index"; then
    success_count=$((success_count + 1))
fi

# Create Infrastructure category index
cat > /tmp/infrastructure_index.md << 'EOF'
# 🏗️ Infrastructure

*Complete infrastructure documentation and configuration guides*

## 🌐 Core Infrastructure
- [🏗️ Infrastructure Overview](Infrastructure-Infrastructure-Overview) - Complete infrastructure guide
- [📊 Infrastructure Health](Infrastructure-Infrastructure-Health-Report) - System health status
- [🌐 Networking](Infrastructure-Networking) - Network configuration
- [💾 Storage](Infrastructure-Storage) - Storage configuration
- [🖥️ Hosts](Infrastructure-Hosts) - Host management

## 🔐 Access & Security
- [🔑 SSH Access Guide](Infrastructure-Ssh-Access-Guide) - SSH access procedures
- [👥 User Access Guide](Infrastructure-User-Access-Guide) - User access management
- [🔐 Authentik SSO](Infrastructure-Authentik-Sso) - Single sign-on setup

## 🌐 Network Services
- [🚇 Tailscale Setup](Infrastructure-Tailscale-Setup-Guide) - VPN configuration
- [☁️ Cloudflare Tunnels](Infrastructure-Cloudflare-Tunnels) - Tunnel configuration
- [☁️ Cloudflare DNS](Infrastructure-Cloudflare-Dns) - DNS configuration
- [🌐 Network Performance](Infrastructure-Network-Performance-Tuning) - Performance optimization

## 🏠 Host Management
- [📊 Hardware Inventory](Infrastructure-Hardware-Inventory) - Hardware catalog
- [🔄 Atlantis Migration](Infrastructure-Atlantis-Migration) - Migration procedures
- [📱 Mobile Setup](Infrastructure-Mobile-Device-Setup) - Mobile device configuration
- [💻 Laptop Setup](Infrastructure-Laptop-Travel-Setup) - Laptop configuration

---
[🏠 Back to Home](Home)
EOF

total_count=$((total_count + 1))
if create_wiki_page "Infrastructure-Index" "/tmp/infrastructure_index.md" "Created infrastructure category index"; then
    success_count=$((success_count + 1))
fi

# Create Services category index
cat > /tmp/services_index.md << 'EOF'
# 🎯 Services

*Complete service documentation and configuration guides*

## 📊 Service Management
- [📋 Service Index](Services-Index) - All available services
- [✅ Verified Service Inventory](Services-Verified-Service-Inventory) - Service catalog
- [📊 Dashboard Setup](Services-Dashboard-Setup) - Dashboard configuration
- [🎨 Homarr Setup](Services-Homarr-Setup) - Homarr dashboard setup
- [🎨 Theme Park](Services-Theme-Park) - UI theming

## 🎬 Media Services
- [🎬 ARR Suite Enhancements](Services-Arr-Suite-Enhancements-Feb2025) - Media stack improvements
- [🎬 ARR Suite Language Config](Arr-Suite-Language-Configuration) - Language configuration

## 💬 Communication Services
- [💬 Stoatchat Setup](Services-Stoatchat-Setup) - Chat platform setup
- [💬 Stoatchat Next Steps](Services-Stoatchat-Next-Steps) - Future improvements
- [🗨️ Matrix Setup](Services-Matrix-Setup) - Matrix server configuration
- [💬 Mastodon Setup](Services-Mastodon-Setup) - Social media platform
- [💬 Mattermost Setup](Services-Mattermost-Setup) - Team communication

## 🔧 Development Services
- [🤖 OpenHands](Services-Openhands) - AI development assistant
- [📄 Paperless](Services-Paperless) - Document management
- [📝 Reactive Resume](Services-Reactive-Resume) - Resume builder

## 📋 Individual Services
- [📋 Individual Service Docs](Services-Individual-Index) - Complete service documentation

---
[🏠 Back to Home](Home)
EOF

total_count=$((total_count + 1))
if create_wiki_page "Services-Index" "/tmp/services_index.md" "Created services category index"; then
    success_count=$((success_count + 1))
fi

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

# Upload key documentation files with organized structure
declare -A doc_files=(
    # Core documentation
    ["README"]="README.md"
    ["Documentation-Index"]="docs/INDEX.md"
    ["Changelog"]="docs/CHANGELOG.md"

    # Administration
    ["Admin-Agents"]="docs/admin/AGENTS.md"
    ["Admin-Deployment-Documentation"]="docs/admin/DEPLOYMENT_DOCUMENTATION.md"
    ["Admin-Development"]="docs/admin/DEVELOPMENT.md"
    ["Admin-Documentation-Audit-Report"]="docs/admin/DOCUMENTATION_AUDIT_REPORT.md"
    ["Admin-Gitops-Comprehensive-Guide"]="docs/admin/GITOPS_COMPREHENSIVE_GUIDE.md"
    ["Admin-Operational-Status"]="docs/admin/OPERATIONAL_STATUS.md"
    ["Admin-Deployment-Workflow"]="docs/admin/DEPLOYMENT_WORKFLOW.md"
    ["Admin-Monitoring-Setup"]="docs/admin/monitoring-setup.md"
    ["Admin-Backup-Strategies"]="docs/admin/backup-strategies.md"
    ["Admin-Maintenance"]="docs/admin/maintenance.md"
    ["Admin-Dokuwiki-Integration"]="docs/admin/DOKUWIKI_INTEGRATION.md"
    ["Admin-Gitea-Wiki-Integration"]="docs/admin/GITEA_WIKI_INTEGRATION.md"

    # Infrastructure
    ["Infrastructure-Infrastructure-Overview"]="docs/infrastructure/INFRASTRUCTURE_OVERVIEW.md"
    ["Infrastructure-Infrastructure-Health-Report"]="docs/infrastructure/INFRASTRUCTURE_HEALTH_REPORT.md"
    ["Infrastructure-Monitoring-Architecture"]="docs/infrastructure/MONITORING_ARCHITECTURE.md"
    ["Infrastructure-Networking"]="docs/infrastructure/networking.md"
    ["Infrastructure-Storage"]="docs/infrastructure/storage.md"
    ["Infrastructure-Hosts"]="docs/infrastructure/hosts.md"
    ["Infrastructure-Ssh-Access-Guide"]="docs/infrastructure/SSH_ACCESS_GUIDE.md"
    ["Infrastructure-User-Access-Guide"]="docs/infrastructure/USER_ACCESS_GUIDE.md"
    ["Infrastructure-Authentik-Sso"]="docs/infrastructure/authentik-sso.md"
    ["Infrastructure-Tailscale-Setup-Guide"]="docs/infrastructure/tailscale-setup-guide.md"
    ["Infrastructure-Cloudflare-Tunnels"]="docs/infrastructure/cloudflare-tunnels.md"
    ["Infrastructure-Cloudflare-Dns"]="docs/infrastructure/cloudflare-dns.md"

    # Security
    ["Security-Server-Hardening"]="docs/security/SERVER_HARDENING.md"

    # Services
    ["Services-Verified-Service-Inventory"]="docs/services/VERIFIED_SERVICE_INVENTORY.md"
    ["Services-Dashboard-Setup"]="docs/services/DASHBOARD_SETUP.md"
    ["Services-Homarr-Setup"]="docs/services/HOMARR_SETUP.md"
    ["Services-Theme-Park"]="docs/services/theme-park.md"
    ["Services-Arr-Suite-Enhancements-Feb2025"]="docs/services/ARR_SUITE_ENHANCEMENTS_FEB2025.md"
    ["Arr-Suite-Language-Configuration"]="docs/arr-suite-language-configuration.md"
    ["Services-Stoatchat-Setup"]="docs/services/stoatchat-setup.md"
    ["Services-Stoatchat-Next-Steps"]="docs/services/stoatchat-next-steps.md"
    ["Services-Openhands"]="docs/services/openhands.md"

    # Getting Started
    ["Getting-Started-Beginner-Quickstart"]="docs/getting-started/BEGINNER_QUICKSTART.md"
    ["Getting-Started-What-Is-Homelab"]="docs/getting-started/what-is-homelab.md"
    ["Getting-Started-Prerequisites"]="docs/getting-started/prerequisites.md"
    ["Getting-Started-Architecture"]="docs/getting-started/architecture.md"
    ["Getting-Started-Shopping-Guide"]="docs/getting-started/shopping-guide.md"

    # Troubleshooting
    ["Troubleshooting-Emergency-Access-Guide"]="docs/troubleshooting/EMERGENCY_ACCESS_GUIDE.md"
    ["Troubleshooting-Disaster-Recovery"]="docs/troubleshooting/disaster-recovery.md"
    ["Troubleshooting-Common-Issues"]="docs/troubleshooting/common-issues.md"
    ["Troubleshooting-Container-Diagnosis-Report"]="docs/troubleshooting/CONTAINER_DIAGNOSIS_REPORT.md"

    # Hardware
    ["Hardware-Readme"]="docs/hardware/README.md"
    ["Hardware-Network-Equipment"]="docs/hardware/network-equipment.md"
    ["Hardware-Atlantis-Storage"]="docs/hardware/atlantis-storage.md"

    # Runbooks
    ["Runbooks-Add-New-Service"]="docs/runbooks/add-new-service.md"
    ["Runbooks-Add-New-User"]="docs/runbooks/add-new-user.md"
    ["Runbooks-Certificate-Renewal"]="docs/runbooks/certificate-renewal.md"

    # Diagrams
    ["Diagrams-Network-Topology"]="docs/diagrams/network-topology.md"
    ["Diagrams-Service-Architecture"]="docs/diagrams/service-architecture.md"
    ["Diagrams-Storage-Topology"]="docs/diagrams/storage-topology.md"
)

for title in "${!doc_files[@]}"; do
    file_path="${doc_files[$title]}"
    if [[ -f "$file_path" ]]; then
        total_count=$((total_count + 1))
        if create_wiki_page "$title" "$file_path" "Updated $title with organized structure"; then
            success_count=$((success_count + 1))
        fi
        sleep 0.1
    else
        echo -e "${YELLOW}⚠️  File not found: $file_path${NC}"
    fi
done

echo ""
echo -e "${BLUE}🎯 Organized Wiki 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}🌐 Organized 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}"

# 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}📊 Organized Wiki Statistics:${NC}"
echo -e "${GREEN}   Total Wiki Pages: $final_page_count${NC}"
echo -e "${GREEN}   Organized Structure: ✅ Hierarchical navigation${NC}"
echo -e "${GREEN}   Success Rate: $(( success_count * 100 / total_count ))%${NC}"

if [[ $success_count -eq $total_count ]]; then
    echo ""
    echo -e "${GREEN}✅ ORGANIZED Gitea Wiki upload completed successfully!${NC}"
    echo -e "${GREEN}🎉 Wiki now has proper hierarchical navigation!${NC}"
    exit 0
else
    echo ""
    echo -e "${YELLOW}⚠️  Organized Wiki upload completed with some issues.${NC}"
    echo -e "${YELLOW}📊 $success_count out of $total_count pages uploaded successfully.${NC}"
    exit 1
fi
