#!/usr/bin/env bash
# audit_registry_paths
# --------------------
# Audita file_path de functions y types en registry.db.
# Genera un txt con las rutas rotas para que agentes puedan arreglarlas.
#
# Compone: assert_command_exists + assert_file_exists +
#          validate_registry_paths + report_execution_json + exit_with_status
#
# USO:
#   ./audit_registry_paths.sh [OUTPUT_FILE]
#
# ARGUMENTOS (opcionales):
#   OUTPUT_FILE   Ruta del archivo de salida
#                 Default: $REGISTRY_ROOT/broken_paths.txt

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REGISTRY_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

source "$REGISTRY_ROOT/bash/functions/shell/assert_command_exists.sh"
source "$REGISTRY_ROOT/bash/functions/shell/assert_file_exists.sh"
source "$REGISTRY_ROOT/bash/functions/shell/validate_registry_paths.sh"
source "$REGISTRY_ROOT/bash/functions/shell/report_execution_json.sh"
source "$REGISTRY_ROOT/bash/functions/shell/exit_with_status.sh"

OUTPUT_FILE="${1:-$REGISTRY_ROOT/broken_paths.txt}"
DB_PATH="$REGISTRY_ROOT/registry.db"

STARTED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
START_MS=$(date +%s%3N)
STEPS_FILE=$(mktemp)
trap 'rm -f "$STEPS_FILE"' EXIT

ok_steps=0
failed_steps=0

log_step() {
    local name="$1" action="$2" status="$3" elapsed="$4" output="${5:-}" error="${6:-}"
    printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$name" "$action" "$status" "$elapsed" "$output" "$error" >> "$STEPS_FILE"
    if [[ "$status" == "ok" ]]; then ok_steps=$((ok_steps + 1)); else failed_steps=$((failed_steps + 1)); fi
}

# Paso 1: verificar sqlite3
step_start=$(date +%s%3N)
if assert_command_exists sqlite3; then
    log_step "assert_command_exists" "check sqlite3" "ok" $(( $(date +%s%3N) - step_start ))
else
    log_step "assert_command_exists" "check sqlite3" "error" $(( $(date +%s%3N) - step_start )) "" "sqlite3 not found"
    ENDED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
    DURATION=$(( $(date +%s%3N) - START_MS ))
    set +e; report_execution_json "audit_registry_paths" "failure" 1 "$STARTED_AT" "$ENDED_AT" "$DURATION" "$STEPS_FILE"; set -e
    exit 1
fi

# Paso 2: verificar registry.db
step_start=$(date +%s%3N)
if db_size=$(assert_file_exists "$DB_PATH"); then
    log_step "assert_file_exists" "check registry.db" "ok" $(( $(date +%s%3N) - step_start )) "${db_size} bytes"
else
    log_step "assert_file_exists" "check registry.db" "error" $(( $(date +%s%3N) - step_start )) "" "registry.db not found"
    ENDED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
    DURATION=$(( $(date +%s%3N) - START_MS ))
    set +e; report_execution_json "audit_registry_paths" "failure" 1 "$STARTED_AT" "$ENDED_AT" "$DURATION" "$STEPS_FILE"; set -e
    exit 1
fi

# Paso 3: validar functions
step_start=$(date +%s%3N)
fn_broken=$(validate_registry_paths "$DB_PATH" functions "$REGISTRY_ROOT")
fn_count=$(printf '%s' "$fn_broken" | grep -c . || true)
log_step "validate_registry_paths" "check functions" "ok" $(( $(date +%s%3N) - step_start )) "$fn_count broken"

# Paso 4: validar types
step_start=$(date +%s%3N)
ty_broken=$(validate_registry_paths "$DB_PATH" types "$REGISTRY_ROOT")
ty_count=$(printf '%s' "$ty_broken" | grep -c . || true)
log_step "validate_registry_paths" "check types" "ok" $(( $(date +%s%3N) - step_start )) "$ty_count broken"

# Paso 5: generar archivo de salida
step_start=$(date +%s%3N)
total_broken=$(( fn_count + ty_count ))

{
    echo "# Broken file_path entries in registry.db"
    echo "# Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
    echo "# Total: $total_broken broken paths"
    echo "#"
    echo "# Format: id | file_path (in .md) | domain | table"
    echo "# ---"
    if [[ $total_broken -eq 0 ]]; then
        echo "# All paths are valid."
    else
        if [[ -n "$fn_broken" ]]; then
            echo ""
            echo "## Functions ($fn_count)"
            printf '%s\n' "$fn_broken" | while IFS=$'\t' read -r id fp domain table; do
                echo "$id | $fp | $domain | $table"
            done
        fi
        if [[ -n "$ty_broken" ]]; then
            echo ""
            echo "## Types ($ty_count)"
            printf '%s\n' "$ty_broken" | while IFS=$'\t' read -r id fp domain table; do
                echo "$id | $fp | $domain | $table"
            done
        fi
    fi
} > "$OUTPUT_FILE"

log_step "write_output" "generate $OUTPUT_FILE" "ok" $(( $(date +%s%3N) - step_start )) "$total_broken entries"

# Reporte final
ENDED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
DURATION=$(( $(date +%s%3N) - START_MS ))
total_steps=$(( ok_steps + failed_steps ))

if [[ $total_broken -eq 0 ]]; then
    status="success"
else
    status="partial"
fi

set +e
report_execution_json "audit_registry_paths" "$status" 0 "$STARTED_AT" "$ENDED_AT" "$DURATION" "$STEPS_FILE"
set -e

echo ""
echo "--- Results ---"
echo "Broken paths: $total_broken"
echo "Output: $OUTPUT_FILE"

exit_with_status "$total_steps" "$ok_steps" "$failed_steps" > /dev/null
