#!/bin/bash

# Categories generator for LibrePortal
# Creates apps-categories.json and apps-categories.json files

webuiCreateAppsCategories() {
    local output_dir="$1"
    
    if [[ -z "$output_dir" ]]; then
        isError " Output directory not specified"
    fi
    
    echo "Generating apps-categories.json..."
    
    # Create output directory if it doesn't exist
    runFileOp mkdir -p "$output_dir"
    
    # Create temp file first, then atomic move
    local temp_file="$(mktemp)"
    local final_file="${output_dir}/apps-categories.json"
    
    # Generate apps-categories.json for data-loader.js
    cat > "$temp_file" << 'EOF'
{
  "categories": [
    {
      "id": "recommended",
      "name": "Recommended",
      "icon": "/icons/categories/recommended.svg",
      "description": "Hand-picked apps to round out your install"
    },
    {
      "id": "communication",
      "name": "Communication",
      "icon": "/icons/categories/communication.svg",
      "description": "Communication and collaboration tools"
    },
    {
      "id": "development",
      "name": "Development",
      "icon": "/icons/categories/development.svg",
      "description": "Development tools and version control"
    },
    {
      "id": "knowledge",
      "name": "Knowledge",
      "icon": "/icons/categories/knowledge.svg",
      "description": "Knowledge management and wikis"
    },
    {
      "id": "media",
      "name": "Media",
      "icon": "/icons/categories/media.svg",
      "description": "Media streaming and entertainment"
    },
    {
      "id": "monitoring",
      "name": "Monitoring",
      "icon": "/icons/categories/monitoring.svg",
      "description": "Metrics, dashboards and observability"
    },
    {
      "id": "networking",
      "name": "Networking",
      "icon": "/icons/categories/networking.svg",
      "description": "Network tools and services"
    },
    {
      "id": "productivity",
      "name": "Productivity",
      "icon": "/icons/categories/productivity.svg",
      "description": "Productivity and business tools"
    },
    {
      "id": "security",
      "name": "Security",
      "icon": "/icons/categories/security.svg",
      "description": "Security and privacy tools"
    },
    {
      "id": "storage",
      "name": "Storage",
      "icon": "/icons/categories/storage.svg",
      "description": "File storage and sharing solutions"
    },
    {
      "id": "system",
      "name": "System",
      "icon": "/icons/categories/system.svg",
      "description": "LibrePortal itself and platform-level services"
    }
  ]
}
EOF

    # Atomic move to final location
    if [ $? -eq 0 ]; then
        runFileWrite "$final_file" < "$temp_file"; rm -f "$temp_file"
    else
        rm -f "$temp_file" 2>/dev/null
    fi
}
