#!/bin/bash

# Clean Organized Gitea Wiki Creation Script
# Creates a fresh, properly organized wiki with hierarchical 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}🚀 Creating CLEAN organized Gitea Wiki 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
    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 organized navigation hub...${NC}"

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

*Organized documentation for Vish's homelab infrastructure*

## 🎯 Quick Access

| Category | Description | Key Pages |
|----------|-------------|-----------|
| [🔧 **Administration**](Administration) | System management & operations | [GitOps Guide](GitOps-Guide), [Deployment](Deployment-Guide) |
| [🏗️ **Infrastructure**](Infrastructure) | Core infrastructure & networking | [Overview](Infrastructure-Overview), [Networking](Networking-Guide) |
| [🎯 **Services**](Services) | Application services & setup | [Service Index](Service-Index), [Dashboard Setup](Dashboard-Setup) |
| [🚀 **Getting Started**](Getting-Started) | Beginner guides & quickstart | [Quickstart](Beginner-Quickstart), [What is Homelab](What-Is-Homelab) |
| [🛠️ **Troubleshooting**](Troubleshooting) | Problem solving & diagnostics | [Common Issues](Common-Issues), [Emergency Guide](Emergency-Guide) |
| [🔬 **Advanced**](Advanced) | Advanced topics & optimization | [Maturity Roadmap](Maturity-Roadmap), [Scaling](Scaling-Guide) |

---

## 📊 **System Status**

- **🚀 GitOps Status**: ✅ 18 active stacks, 50+ containers
- **🖥️ Active Servers**: 5 (Atlantis, Calypso, Gaming VPS, Homelab VM, Concord NUC)
- **🎯 Services**: 100+ containerized services
- **📚 Documentation**: 300+ organized pages

---

## 🌐 **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

---

## 📚 **Documentation Categories**

### 🔧 Administration
Essential system management and operational procedures.
- [GitOps Comprehensive Guide](GitOps-Guide) - Complete deployment procedures ⭐
- [Deployment Documentation](Deployment-Guide) - Step-by-step deployment
- [Operational Status](Operational-Status) - Current system status
- [Security Hardening](Security-Guide) - Security procedures

### 🏗️ Infrastructure
Core infrastructure, networking, and host management.
- [Infrastructure Overview](Infrastructure-Overview) - Complete infrastructure guide
- [Networking Guide](Networking-Guide) - Network configuration
- [SSH Access Guide](SSH-Guide) - Access procedures
- [Hardware Inventory](Hardware-Inventory) - Equipment catalog

### 🎯 Services
Application services, dashboards, and service management.
- [Service Index](Service-Index) - All available services
- [Dashboard Setup](Dashboard-Setup) - Dashboard configuration
- [Stoatchat Setup](Stoatchat-Guide) - Chat platform
- [Media Services](Media-Services) - ARR suite and media

### 🚀 Getting Started
Beginner-friendly guides and quick start procedures.
- [Beginner Quickstart](Beginner-Quickstart) - Quick start guide
- [What Is Homelab](What-Is-Homelab) - Introduction to homelabs
- [Prerequisites](Prerequisites) - Requirements and setup
- [Architecture Overview](Architecture-Overview) - System architecture

### 🛠️ Troubleshooting
Problem solving, diagnostics, and emergency procedures.
- [Common Issues](Common-Issues) - Frequently encountered problems
- [Emergency Access Guide](Emergency-Guide) - Emergency procedures
- [Disaster Recovery](Disaster-Recovery) - Recovery procedures
- [Container Diagnosis](Container-Diagnosis) - Container troubleshooting

### 🔬 Advanced Topics
Advanced configuration, optimization, and scaling.
- [Homelab Maturity Roadmap](Maturity-Roadmap) - Growth planning
- [Repository Optimization](Optimization-Guide) - Optimization strategies
- [Terraform Implementation](Terraform-Guide) - Infrastructure as code
- [Scaling Strategies](Scaling-Guide) - Growth and scaling

---

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

total_count=$((total_count + 1))
if create_wiki_page "Home" "/tmp/clean_wiki_home.md" "Created clean organized wiki home page"; then
    success_count=$((success_count + 1))
fi

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

# Create Administration category page
cat > /tmp/administration.md << 'EOF'
# 🔧 Administration

*System management and operational procedures*

## 🚀 Deployment & GitOps
- [GitOps Comprehensive Guide](GitOps-Guide) - Complete deployment procedures ⭐
- [Deployment Documentation](Deployment-Guide) - Step-by-step deployment
- [Deployment Workflow](Deployment-Workflow) - Workflow procedures

## 🔧 System Administration
- [Development Guide](Development-Guide) - Development procedures
- [Agent Memory](Agent-Memory) - AI agent context
- [Monitoring Setup](Monitoring-Setup) - Monitoring configuration
- [Backup Strategies](Backup-Strategies) - Backup procedures
- [Maintenance Procedures](Maintenance-Guide) - System maintenance

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

## 📚 Integration
- [DokuWiki Integration](DokuWiki-Integration) - External wiki setup
- [Gitea Wiki Integration](Gitea-Wiki-Integration) - Native wiki setup

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

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

# Create Infrastructure category page
cat > /tmp/infrastructure.md << 'EOF'
# 🏗️ Infrastructure

*Core infrastructure, networking, and host management*

## 🌐 Core Infrastructure
- [Infrastructure Overview](Infrastructure-Overview) - Complete infrastructure guide
- [Infrastructure Health](Infrastructure-Health) - System health status
- [Networking Guide](Networking-Guide) - Network configuration
- [Storage Guide](Storage-Guide) - Storage configuration
- [Host Management](Host-Management) - Host administration

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

## 🌐 Network Services
- [Tailscale Setup](Tailscale-Guide) - VPN configuration
- [Cloudflare Tunnels](Cloudflare-Tunnels) - Tunnel configuration
- [Cloudflare DNS](Cloudflare-DNS) - DNS configuration
- [Network Performance](Network-Performance) - Performance tuning

## 🏠 Hardware & Hosts
- [Hardware Inventory](Hardware-Inventory) - Equipment catalog
- [Atlantis Migration](Atlantis-Migration) - Migration procedures
- [Mobile Setup](Mobile-Setup) - Mobile device configuration
- [Laptop Setup](Laptop-Setup) - Laptop configuration

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

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

# Create Services category page
cat > /tmp/services.md << 'EOF'
# 🎯 Services

*Application services and configuration guides*

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

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

## 💬 Communication Services
- [Stoatchat Setup](Stoatchat-Guide) - Chat platform setup
- [Matrix Setup](Matrix-Guide) - Matrix server configuration
- [Mastodon Setup](Mastodon-Guide) - Social media platform
- [Mattermost Setup](Mattermost-Guide) - Team communication

## 🔧 Development Services
- [OpenHands](OpenHands-Guide) - AI development assistant
- [Paperless](Paperless-Guide) - Document management
- [Reactive Resume](Reactive-Resume-Guide) - Resume builder

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

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

# Create Getting Started category page
cat > /tmp/getting-started.md << 'EOF'
# 🚀 Getting Started

*Beginner guides and quick start procedures*

## 🎯 Quick Start
- [Beginner Quickstart](Beginner-Quickstart) - Quick start guide
- [What Is Homelab](What-Is-Homelab) - Introduction to homelabs
- [Prerequisites](Prerequisites) - Requirements and setup
- [Architecture Overview](Architecture-Overview) - System architecture

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

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

total_count=$((total_count + 1))
if create_wiki_page "Getting-Started" "/tmp/getting-started.md" "Created getting started category page"; then
    success_count=$((success_count + 1))
fi

# Create Troubleshooting category page
cat > /tmp/troubleshooting.md << 'EOF'
# 🛠️ Troubleshooting

*Problem solving, diagnostics, and emergency procedures*

## 🚨 Emergency Procedures
- [Emergency Access Guide](Emergency-Guide) - Emergency procedures
- [Disaster Recovery](Disaster-Recovery) - Recovery procedures
- [Recovery Guide](Recovery-Guide) - System recovery

## 🔍 Diagnostics
- [Common Issues](Common-Issues) - Frequently encountered problems
- [Diagnostics Guide](Diagnostics-Guide) - Diagnostic procedures
- [Container Diagnosis](Container-Diagnosis) - Container troubleshooting
- [Performance Issues](Performance-Issues) - Performance troubleshooting

## 🔧 Specific Issues
- [Watchtower Emergency](Watchtower-Emergency) - Watchtower issues
- [Authentik SSO Rebuild](Authentik-Rebuild) - SSO troubleshooting
- [Beginner Troubleshooting](Beginner-Troubleshooting) - Beginner help

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

total_count=$((total_count + 1))
if create_wiki_page "Troubleshooting" "/tmp/troubleshooting.md" "Created troubleshooting category page"; then
    success_count=$((success_count + 1))
fi

# Create Advanced category page
cat > /tmp/advanced.md << 'EOF'
# 🔬 Advanced Topics

*Advanced configuration, optimization, and scaling*

## 🚀 Growth & Optimization
- [Homelab Maturity Roadmap](Maturity-Roadmap) - Growth planning
- [Repository Optimization](Optimization-Guide) - Optimization strategies
- [Stack Comparison Report](Stack-Comparison) - Technology comparisons
- [Scaling Strategies](Scaling-Guide) - Growth and scaling

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

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

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

total_count=$((total_count + 1))
if create_wiki_page "Advanced" "/tmp/advanced.md" "Created advanced topics category page"; then
    success_count=$((success_count + 1))
fi

echo ""
echo -e "${BLUE}📚 Creating key documentation pages...${NC}"

# Create key pages that exist in the docs
declare -A key_pages=(
    # Core pages
    ["GitOps-Guide"]="docs/admin/GITOPS_DEPLOYMENT_GUIDE.md"
    ["Deployment-Guide"]="docs/admin/DEPLOYMENT_DOCUMENTATION.md"
    ["Operational-Status"]="docs/admin/OPERATIONAL_STATUS.md"
    ["Development-Guide"]="docs/admin/DEVELOPMENT.md"
    ["Agent-Memory"]="docs/admin/AGENTS.md"

    # Infrastructure
    ["Infrastructure-Overview"]="docs/infrastructure/INFRASTRUCTURE_OVERVIEW.md"
    ["Infrastructure-Health"]="docs/infrastructure/INFRASTRUCTURE_HEALTH_REPORT.md"
    ["SSH-Guide"]="docs/infrastructure/SSH_ACCESS_GUIDE.md"
    ["User-Access-Guide"]="docs/infrastructure/USER_ACCESS_GUIDE.md"

    # Security
    ["Security-Guide"]="docs/security/SECURITY_HARDENING_SUMMARY.md"

    # Services
    ["Service-Index"]="docs/services/VERIFIED_SERVICE_INVENTORY.md"
    ["Dashboard-Setup"]="docs/services/DASHBOARD_SETUP.md"
    ["Homarr-Setup"]="docs/services/HOMARR_SETUP.md"
    ["ARR-Suite-Enhancements"]="docs/services/ARR_SUITE_ENHANCEMENTS_FEB2025.md"

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

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

    # Hardware
    ["Hardware-Inventory"]="docs/hardware/README.md"
)

for title in "${!key_pages[@]}"; do
    file_path="${key_pages[$title]}"
    if [[ -f "$file_path" ]]; then
        total_count=$((total_count + 1))
        if create_wiki_page "$title" "$file_path" "Created organized page: $title"; 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}🎯 Clean Organized Wiki Creation 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}🌐 Clean 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}📊 Clean Organized Wiki Statistics:${NC}"
echo -e "${GREEN}   Total Wiki Pages: $final_page_count${NC}"
echo -e "${GREEN}   Organized Structure: ✅ Clean 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}✅ CLEAN Organized Gitea Wiki created successfully!${NC}"
    echo -e "${GREEN}🎉 Wiki now has clean, navigable structure!${NC}"
    exit 0
else
    echo ""
    echo -e "${YELLOW}⚠️  Clean Wiki creation completed with some issues.${NC}"
    echo -e "${YELLOW}📊 $success_count out of $total_count pages created successfully.${NC}"
    exit 1
fi
