#!/usr/bin/env bash
# gniza4cp/lib/snapshot.sh — Timestamp naming, list/resolve snapshots, latest symlink

get_remote_account_base() {
    local user="$1"
    local hostname; hostname=$(hostname -f)
    echo "${REMOTE_BASE}/${hostname}/accounts/${user}"
}

get_snapshot_dir() {
    local user="$1"
    echo "$(get_remote_account_base "$user")/snapshots"
}

list_remote_snapshots() {
    local user="$1"

    if _is_rclone_mode; then
        rclone_list_remote_snapshots "$user"
        return
    fi

    local snap_dir; snap_dir=$(get_snapshot_dir "$user")

    # List completed snapshots (no .partial suffix), sorted newest first
    local raw; raw=$(remote_exec "ls -1d '$snap_dir'/[0-9]* 2>/dev/null | grep -v '\\.partial$' | sort -r" 2>/dev/null) || true
    if [[ -n "$raw" ]]; then
        echo "$raw" | xargs -I{} basename {} | sort -r
    fi
}

get_latest_snapshot() {
    local user="$1"

    if _is_rclone_mode; then
        rclone_get_latest_snapshot "$user"
        return
    fi

    list_remote_snapshots "$user" | head -1
}

resolve_snapshot_timestamp() {
    local user="$1"
    local requested="$2"

    if [[ -z "$requested" || "$requested" == "LATEST" || "$requested" == "latest" ]]; then
        get_latest_snapshot "$user"
    elif _is_rclone_mode; then
        rclone_resolve_snapshot "$user" "$requested"
    else
        # Verify it exists
        local snap_dir; snap_dir=$(get_snapshot_dir "$user")
        if remote_exec "test -d '$snap_dir/$requested'" 2>/dev/null; then
            echo "$requested"
        else
            log_error "Snapshot not found for $user: $requested"
            return 1
        fi
    fi
}

update_latest_symlink() {
    local user="$1"
    local timestamp="$2"

    if _is_rclone_mode; then
        rclone_update_latest "$user" "$timestamp"
        return
    fi

    local base; base=$(get_remote_account_base "$user")
    local snap_dir; snap_dir=$(get_snapshot_dir "$user")

    remote_exec "ln -sfn '$snap_dir/$timestamp' '$base/latest'" || {
        log_warn "Failed to update latest symlink for $user"
        return 1
    }
    log_debug "Updated latest symlink for $user -> $timestamp"
}

clean_partial_snapshots() {
    local user="$1"

    if _is_rclone_mode; then
        rclone_clean_partial_snapshots "$user"
        return
    fi

    local snap_dir; snap_dir=$(get_snapshot_dir "$user")

    local partials; partials=$(remote_exec "ls -1d '$snap_dir'/*.partial 2>/dev/null" 2>/dev/null) || true
    if [[ -n "$partials" ]]; then
        log_info "Cleaning partial snapshots for $user..."
        remote_exec "rm -rf '$snap_dir'/*.partial" || {
            log_warn "Failed to clean partial snapshots for $user"
        }
    fi
}

list_remote_accounts() {
    if _is_rclone_mode; then
        rclone_list_dirs "accounts"
        return
    fi

    local hostname; hostname=$(hostname -f)
    local accounts_dir="${REMOTE_BASE}/${hostname}/accounts"
    remote_exec "ls -1 '$accounts_dir' 2>/dev/null" 2>/dev/null || true
}
