#!/bin/bash

webuiGenerateBackupDashboard()
{
    local output_dir="$containers_dir/libreportal/frontend/data/backup/generated"
    local output_file="$output_dir/dashboard.json"
    local temp_file="${output_file}.tmp.$$"

    runFileOp mkdir -p "$output_dir"

    local generated_at
    generated_at=$(date -Iseconds)

    local locations_json="["
    local first=true
    local idx
    while IFS= read -r idx; do
        [[ -z "$idx" ]] && continue
        local name uri append_only
        name=$(resticLocationName "$idx")
        uri=$(resticLocationUri "$idx")
        append_only="false"; resticLocationAppendOnly "$idx" && append_only="true"

        local stats_json total_size="0" total_files="0"
        stats_json=$(engineLocationStats "$idx" 2>/dev/null)
        if [[ -n "$stats_json" ]]; then
            total_size=$(echo "$stats_json" | grep -o '"total_size":[0-9]*' | head -1 | cut -d':' -f2)
            total_files=$(echo "$stats_json" | grep -o '"total_file_count":[0-9]*' | head -1 | cut -d':' -f2)
            [[ -z "$total_size" ]] && total_size="0"
            [[ -z "$total_files" ]] && total_files="0"
        fi

        local name_esc uri_esc
        name_esc=$(printf '%s' "$name" | sed 's/\\/\\\\/g; s/"/\\"/g')
        uri_esc=$(printf '%s' "$uri" | sed 's/\\/\\\\/g; s/"/\\"/g')

        $first || locations_json+=","
        first=false
        locations_json+="{"
        locations_json+="\"idx\":$idx,"
        locations_json+="\"name\":\"$name_esc\","
        locations_json+="\"type\":\"$(resticLocationType "$idx")\","
        locations_json+="\"uri\":\"$uri_esc\","
        locations_json+="\"append_only\":$append_only,"
        locations_json+="\"total_size_bytes\":$total_size,"
        locations_json+="\"total_files\":$total_files"
        locations_json+="}"
    done < <(resticEnabledLocations)
    locations_json+="]"

    local apps_json="["
    first=true
    if [[ -f "$docker_dir/$db_file" ]]; then
        local primary_idx
        primary_idx=$(resticEnabledLocations | head -1)
        while IFS= read -r app; do
            [[ -z "$app" ]] && continue
            # The WebUI app is reproducible and skipped by backupAllApps — its
            # state rides in the system-config snapshot below, so don't show a
            # perpetually-"No backup yet" tile for it.
            [[ "$app" == "libreportal" ]] && continue
            local latest_id="" latest_time=""
            if [[ -n "$primary_idx" ]]; then
                local snap_json
                snap_json=$(engineSnapshotsJson "$primary_idx" "$app" "$CFG_INSTALL_NAME" 2>/dev/null)
                latest_id=$(echo "$snap_json" | grep -o '"short_id":"[^"]*"' | tail -1 | cut -d'"' -f4)
                latest_time=$(echo "$snap_json" | grep -o '"time":"[^"]*"' | tail -1 | cut -d'"' -f4)
            fi
            $first || apps_json+=","
            first=false
            apps_json+="{\"app\":\"$app\",\"latest_snapshot\":\"$latest_id\",\"latest_time\":\"$latest_time\"}"
        done < <(runInstallOp sqlite3 "$docker_dir/$db_file" "SELECT name FROM apps WHERE status = 1;" 2>/dev/null)
    fi
    apps_json+="]"

    # System-config backup status (tag system=config) — its own tracked item.
    local system_id="" system_time=""
    local sys_idx
    sys_idx=$(resticEnabledLocations | head -1)
    if [[ -n "$sys_idx" ]]; then
        local sys_json
        sys_json=$(engineSystemSnapshotsJson "$sys_idx" "$CFG_INSTALL_NAME" 2>/dev/null)
        system_id=$(echo "$sys_json" | grep -o '"short_id":"[^"]*"' | tail -1 | cut -d'"' -f4)
        system_time=$(echo "$sys_json" | grep -o '"time":"[^"]*"' | tail -1 | cut -d'"' -f4)
    fi

    local content="{"
    content+="\"generated_at\":\"$generated_at\","
    content+="\"install_name\":\"${CFG_INSTALL_NAME:-libreportal}\","
    content+="\"engine\":\"restic\","
    content+="\"verify_after\":${CFG_BACKUP_VERIFY_AFTER:-false},"
    content+="\"strategy\":\"${CFG_BACKUP_STRATEGY:-auto}\","
    content+="\"locations\":$locations_json,"
    content+="\"apps\":$apps_json,"
    content+="\"system\":{\"latest_snapshot\":\"$system_id\",\"latest_time\":\"$system_time\"}"
    content+="}"

    echo "$content" | runFileWrite "$output_file"
    isSuccessful "Backup dashboard JSON regenerated"
}
