#!/bin/bash
set -euo pipefail

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
REPO_ROOT=$( cd -- "${SCRIPT_DIR}/.." &> /dev/null && pwd )
source "${SCRIPT_DIR}/common.sh"

LABEL="${1:-suite}"
PROFILE_SEARCH_ROOT="${REPO_ROOT}/target"
PROFILES_DIR="${REPO_ROOT}/target/llvm-cov-target/profiles"
SNAPSHOT_FILE="${PROFILES_DIR}/.last_snapshot"

if [ ! -d "${PROFILES_DIR}" ]; then
    mkdir -p "${PROFILES_DIR}"
fi

snapshot_profiles() {
    python3 - "$1" <<'PY'
import hashlib
import json
import os
import sys

root = sys.argv[1]
entries = []
for dirpath, _, files in os.walk(root):
    for name in files:
        if not name.endswith('.profraw'):
            continue
        path = os.path.join(dirpath, name)
        stat = os.stat(path)
        entries.append((os.path.relpath(path, root), stat.st_size, stat.st_mtime_ns))

entries.sort()
digest = hashlib.sha256(json.dumps(entries).encode('utf-8')).hexdigest()
print(digest, len(entries))
PY
}

CONFIG_PATH_FILE="${COMMON_DIR}/pgdog.config"
PID_FILE="${COMMON_DIR}/pgdog.pid"
RESTART_CONFIG=""
RESTART_REQUIRED=0
ORIGINAL_CONFIG=""

if [ -f "${CONFIG_PATH_FILE}" ]; then
    RESTART_CONFIG=$(cat "${CONFIG_PATH_FILE}")
    ORIGINAL_CONFIG="${RESTART_CONFIG}"
fi

if [ -f "${PID_FILE}" ]; then
    ACTIVE_PID=$(cat "${PID_FILE}")
    if [ -n "${ACTIVE_PID}" ] && kill -0 "${ACTIVE_PID}" 2> /dev/null; then
        RESTART_REQUIRED=1
    fi
fi

stop_pgdog

PREV_HASH=""
PREV_COUNT=0
if [ -f "${SNAPSHOT_FILE}" ]; then
    read -r PREV_HASH PREV_COUNT < "${SNAPSHOT_FILE}"
fi

ATTEMPTS=0
MAX_ATTEMPTS=15
sleep 2
while :; do
    read -r CURRENT_HASH CURRENT_COUNT <<< "$(snapshot_profiles "${PROFILE_SEARCH_ROOT}")"
    if [ "${CURRENT_COUNT}" != "0" ]; then
        break
    fi
    if [ ${ATTEMPTS} -ge ${MAX_ATTEMPTS} ]; then
        break
    fi
    ATTEMPTS=$((ATTEMPTS + 1))
    sleep 2
done

if [ "${CURRENT_COUNT}" = "0" ]; then
    echo "No coverage profiles were generated by '${LABEL}'" >&2
    find "${PROFILE_SEARCH_ROOT}" -name '*.profraw' -print || true
    exit 1
fi


if [ "${CURRENT_HASH}" = "${PREV_HASH}" ]; then
    echo "Note: coverage artifacts unchanged after '${LABEL}'" >&2
    find "${PROFILE_SEARCH_ROOT}" -name '*.profraw' -print || true
fi

echo "${CURRENT_HASH} ${CURRENT_COUNT}" > "${SNAPSHOT_FILE}"
DELTA=$((CURRENT_COUNT - PREV_COUNT))
echo "Coverage profile fingerprint updated after '${LABEL}': count=${CURRENT_COUNT} (delta=${DELTA})"
echo "Profile files after '${LABEL}':"
find "${PROFILE_SEARCH_ROOT}" -name '*.profraw' -print | sort | tail -n 20

if [ ${RESTART_REQUIRED} -eq 1 ] && [ -n "${RESTART_CONFIG}" ] && [ "${PGDOG_NO_RESTART:-0}" != "1" ]; then
    echo "Restarting PgDog with config '${RESTART_CONFIG}'"
    run_pgdog "${RESTART_CONFIG}"
    CURRENT_CONFIG=$(cat "${CONFIG_PATH_FILE}" 2>/dev/null || echo "")
    if [ -n "${ORIGINAL_CONFIG}" ] && [ "${CURRENT_CONFIG}" != "${ORIGINAL_CONFIG}" ]; then
        echo "Warning: PgDog restarted with different config: '${CURRENT_CONFIG}'" >&2
    fi
    wait_for_pgdog
fi
