#!/usr/bin/env bash
# validate_registry_paths
# -----------------------
# Consulta registry.db y verifica que cada file_path apunte a un archivo existente.
# Recibe la ruta a registry.db y la tabla a validar (functions o types).
# Imprime a stdout las lineas con rutas rotas en formato TSV:
#   id<TAB>file_path<TAB>domain<TAB>tabla
# Exit code 0 siempre (es una consulta, no una asercion).
#
# USO (sourced):
#   source validate_registry_paths.sh
#   validate_registry_paths /ruta/registry.db functions /ruta/raiz
#
# USO (directo):
#   bash validate_registry_paths.sh /ruta/registry.db functions /ruta/raiz

validate_registry_paths() {
    local db_path="$1"
    local table="$2"
    local root_dir="$3"

    if [[ -z "$db_path" || -z "$table" || -z "$root_dir" ]]; then
        echo "validate_registry_paths: uso: validate_registry_paths <db_path> <table> <root_dir>" >&2
        return 1
    fi

    if [[ "$table" != "functions" && "$table" != "types" ]]; then
        echo "validate_registry_paths: tabla debe ser 'functions' o 'types'" >&2
        return 1
    fi

    local broken=0
    while IFS='|' read -r id fp domain; do
        if [[ ! -f "$root_dir/$fp" ]]; then
            printf '%s\t%s\t%s\t%s\n' "$id" "$fp" "$domain" "$table"
            ((broken++))
        fi
    done < <(sqlite3 "$db_path" "SELECT id, file_path, domain FROM $table ORDER BY id;")

    return 0
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    validate_registry_paths "$@"
fi
