#!/bin/bash
# =============================================================================
# WOOO AIOps - Langfuse 備份腳本
# 版本: 1.0.0
# 建立日期: 2026-04-05
# 2026-04-05 Claude Code: 新增 Langfuse AI 追蹤數據備份 — 首席架構師備份審計
# =============================================================================

set -euo pipefail

source "$(dirname "$0")/common.sh"

SERVICE="langfuse"
LOCAL_REPO="${BACKUP_BASE}/langfuse"
DUMP_DIR="/tmp/langfuse-backup-$$"

cleanup() {
    rm -rf "${DUMP_DIR}"
}

main() {
    local start_time=$(date +%s)
    log_info "========== 開始 Langfuse 備份 =========="
    mkdir -p "${DUMP_DIR}"

    local timestamp=$(date "+%Y%m%d_%H%M%S")

    # Step 1: Langfuse PostgreSQL dump
    log_info "執行 Langfuse DB dump..."
    if docker exec langfuse-db pg_dump -U langfuse langfuse > "${DUMP_DIR}/langfuse_${timestamp}.sql" 2>&1; then
        local size=$(du -h "${DUMP_DIR}/langfuse_${timestamp}.sql" | cut -f1)
        log_success "Langfuse DB dump 完成 (${size})"
    else
        log_error "Langfuse DB dump 失敗"
        notify_clawbot "failed" "${SERVICE}" "Langfuse 備份失敗"
        cleanup
        exit 1
    fi

    # Step 2: 初始化 Restic 倉庫 (如果不存在)
    if [ ! -d "${LOCAL_REPO}/data" ]; then
        log_info "初始化 Restic 倉庫: ${LOCAL_REPO}"
        restic -r "${LOCAL_REPO}" init --password-file "${RESTIC_PASSWORD_FILE}" 2>&1 || {
            log_error "Restic 倉庫初始化失敗"
            cleanup
            exit 1
        }
    fi

    # Step 3: Restic 備份
    log_info "建立 Restic 備份..."
    local tags=$(build_tags "${SERVICE}")
    restic -r "${LOCAL_REPO}" backup "${DUMP_DIR}"         --password-file "${RESTIC_PASSWORD_FILE}"         ${tags} 2>&1

    local snapshot_id=$(restic -r "${LOCAL_REPO}" snapshots --latest 1 --json --password-file "${RESTIC_PASSWORD_FILE}" 2>/dev/null | grep -oP '"short_id":"\K[^"]+' | head -1)
    log_success "Restic 備份完成: ${snapshot_id}"

    # Step 4: GFS 清理
    cleanup_old_backups "${LOCAL_REPO}"

    cleanup

    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    log_success "========== Langfuse 備份完成 (${duration}s) =========="
    notify_clawbot "success" "${SERVICE}" "Langfuse 備份完成" "${duration}"
}

main "$@"
