#!/usr/bin/env bash

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
FIXTURE_ROOT="$REPO_ROOT/tests/conformance/issue-tracker-runtime/app-packs-fixture"
FIXTURE_MODULE="github.com/nexuscrm/app-packs-conformance/issue-tracker"
REVISION_FILE="$REPO_ROOT/tests/performance/selected-root-read/revisions.env"
# shellcheck source=../../tests/performance/selected-root-read/revisions.env
source "$REVISION_FILE"
APP_PACKS_REVISION="$P1C_M1_APP_PACKS_REVISION"
FIXTURE_REVISION="$P1C_M1_FIXTURE_REVISION"

: "${TIDB_HOST:?TIDB_HOST is required}"
: "${TIDB_USER:?TIDB_USER is required}"
: "${TIDB_DATABASE:?TIDB_DATABASE must name the source environment database used to create the isolated scratch database}"

operation="${P1C_M1_OPERATION:-measure}"
if [[ "$operation" != measure && "$operation" != cleanup && "$operation" != recover ]]; then
  echo "P1C_M1_OPERATION must be measure, cleanup, or recover" >&2
  exit 2
fi

measurement_test="${P1C_M1_MEASUREMENT_TEST:-TestSelectedRootCapacityEvidence}"
if [[ "$measurement_test" != TestSelectedRootCapacityEvidence && "$measurement_test" != TestSelectedRootM2dAEvidence ]]; then
  echo "P1C_M1_MEASUREMENT_TEST must name a reviewed selected-root evidence test" >&2
  exit 2
fi
evidence_label="${P1C_M1_EVIDENCE_LABEL:-P1c-M1}"
if [[ "$operation" == measure ]]; then
  : "${P1C_M1_APP_PACKS_ROOT:?measure requires a nexuscrm-app-packs checkout containing the pinned commit}"
fi
if [[ "$operation" == cleanup ]]; then
  : "${P1C_M1_SCRATCH_DATABASE:?cleanup requires P1C_M1_SCRATCH_DATABASE}"
  : "${P1C_M1_SCRATCH_TOKEN:?cleanup requires P1C_M1_SCRATCH_TOKEN}"
fi
if [[ "$operation" == recover ]]; then
  : "${P1C_M1_RECOVERY_RUN_ID:?recover requires P1C_M1_RECOVERY_RUN_ID}"
fi

run_id="${P1C_M1_RUN_ID:-p1c-m1-$(date -u +%Y%m%dT%H%M%SZ)}"
if [[ ! "$run_id" =~ ^[A-Za-z0-9._-]+$ ]]; then
  echo "P1C_M1_RUN_ID may contain only A-Za-z0-9._-" >&2
  exit 2
fi

out_dir="${P1C_M1_OUT_DIR:-$REPO_ROOT/artifacts/p1c-m1/$run_id}"
work_dir="$(mktemp -d "${TMPDIR:-/tmp}/p1c-m1.XXXXXX")"
db_suffix="$(printf '%s' "$run_id" | tr -c 'A-Za-z0-9_' '_' | cut -c1-40)"
database_name="${P1C_M1_SCRATCH_DATABASE:-p1c_m1_${db_suffix}_$$}"
records_mod="$(mktemp "$REPO_ROOT/nexuscrm-records/.p1c-m1.XXXXXX.mod")"
records_sum="${records_mod%.mod}.sum"
source_database="$TIDB_DATABASE"
scratch_token="${P1C_M1_SCRATCH_TOKEN:-$(openssl rand -hex 32)}"
database_created=0

run_tagged_test() {
  local test_name="$1"
  (
    cd "$REPO_ROOT/nexuscrm-records"
    GOWORK=off GOFLAGS="-modfile=$records_mod -mod=mod" \
      go test -tags selected_root_capacity_evidence . \
        -run "^${test_name}$" -count=1 -timeout=85m -v
  )
}

cleanup() {
	local cleanup_rc=0
  if [[ "$database_created" == 1 ]]; then
		TIDB_DATABASE="$source_database" run_tagged_test TestSelectedRootCapacityEvidence_DropScratchDatabase >/dev/null 2>&1 || {
			echo "failed to verify/drop owned P1c-M1 scratch database $database_name" >&2
			cleanup_rc=1
		}
  fi
  rm -rf "$work_dir"
  rm -f "$records_mod" "$records_sum"
	return "$cleanup_rc"
}
trap cleanup EXIT

for command in git go openssl python3; do
  command -v "$command" >/dev/null || { echo "required command not found: $command" >&2; exit 2; }
done

nexus_revision="$(git -C "$REPO_ROOT" rev-parse HEAD)"
fixture_got="$(tr -d '[:space:]' < "$REPO_ROOT/tests/conformance/issue-tracker-runtime/app-packs-revision")"
if [[ "$fixture_got" != "$FIXTURE_REVISION" ]]; then
  echo "fixture provenance revision $fixture_got does not match required $FIXTURE_REVISION" >&2
  exit 2
fi
(cd "$REPO_ROOT" && scripts/ci/verify-sha256-manifest.sh tests/conformance/issue-tracker-runtime/app-packs-fixture.snapshot.sha256)

crm_spec="${P1C_M1_CRM_OBJECT_SPEC:-}"
if [[ "$operation" == measure ]]; then
  git -C "$P1C_M1_APP_PACKS_ROOT" cat-file -e "$APP_PACKS_REVISION^{commit}"
  crm_spec="$work_dir/standard_objects_spec.json"
  git -C "$P1C_M1_APP_PACKS_ROOT" show \
    "$APP_PACKS_REVISION:salesforce-crm-standard/objects/standard_objects_spec.json" > "$crm_spec"
fi

mkdir -p "$out_dir"
cp "$REPO_ROOT/nexuscrm-records/go.mod" "$records_mod"
if [[ -f "$REPO_ROOT/nexuscrm-records/go.sum" ]]; then
  cp "$REPO_ROOT/nexuscrm-records/go.sum" "$records_sum"
fi
(
  cd "$REPO_ROOT/nexuscrm-records"
  go mod edit -modfile="$records_mod" \
    -require="$FIXTURE_MODULE@v0.0.0" \
    -replace="$FIXTURE_MODULE=$FIXTURE_ROOT"
)

cpu="${P1C_M1_CPU:-}"
if [[ -z "$cpu" ]]; then
  cpu="$(sysctl -n machdep.cpu.brand_string 2>/dev/null || sed -n 's/^model name[[:space:]]*: //p' /proc/cpuinfo 2>/dev/null | head -1 || true)"
fi
memory_bytes="${P1C_M1_MEMORY_BYTES:-}"
if [[ -z "$memory_bytes" ]]; then
  memory_bytes="$(sysctl -n hw.memsize 2>/dev/null || awk '/MemTotal/ {print $2*1024}' /proc/meminfo 2>/dev/null || true)"
fi

export TIDB_PORT="${TIDB_PORT:-4000}"
export TIDB_PASSWORD="${TIDB_PASSWORD:-}"
export TIDB_DATABASE="$source_database"
export P1C_M1_SOURCE_DATABASE="$source_database"
export P1C_M1_SCRATCH_DATABASE="$database_name"
export P1C_M1_SCRATCH_TOKEN="$scratch_token"
export P1C_M1_RUN_ID="$run_id"
export P1C_M1_OUT_DIR="$out_dir"
export P1C_M1_CRM_OBJECT_SPEC="$crm_spec"
export P1C_M1_NEXUSCRM_REVISION="$nexus_revision"
export P1C_M1_APP_PACKS_REVISION="$APP_PACKS_REVISION"
export P1C_M1_FIXTURE_REVISION="$FIXTURE_REVISION"
export P1C_M1_CPU="${cpu:-not-recorded}"
export P1C_M1_MEMORY_BYTES="${memory_bytes:-0}"
export P1C_M1_COMMAND="${P1C_M1_COMMAND:-P1C_M1_APP_PACKS_ROOT=<checkout> P1C_M1_RUN_ID=$run_id P1C_M1_ENVIRONMENT=${P1C_M1_ENVIRONMENT:-local-development-probe} P1C_M1_REPRESENTATIVE=${P1C_M1_REPRESENTATIVE:-false} P1C_M1_REPRESENTATIVENESS_SCOPE=<declared-scope> P1C_M1_SAMPLES=${P1C_M1_SAMPLES:-1200} P1C_M1_WARMUP=${P1C_M1_WARMUP:-100} P1C_M1_CONCURRENCY=${P1C_M1_CONCURRENCY:-1,4,16,64} P1C_M1_READ_TIMEOUT=${P1C_M1_READ_TIMEOUT:-30s} scripts/performance/run-selected-root-capacity-evidence.sh}"

if [[ "$operation" == cleanup ]]; then
  run_tagged_test TestSelectedRootCapacityEvidence_DropScratchDatabase
  exit 0
fi
if [[ "$operation" == recover ]]; then
  run_tagged_test TestSelectedRootCapacityEvidence_RecoverScratchDatabase
  exit 0
fi

run_tagged_test TestSelectedRootCapacityEvidence_CreateScratchDatabase
database_created=1
if [[ -n "${P1C_M1_ANON_AGGREGATES_FILE:-}" ]]; then
	: "${P1C_M1_AGGREGATE_ENVIRONMENT:?P1C_M1_AGGREGATE_ENVIRONMENT is required when anonymous aggregates are requested}"
	run_tagged_test TestSelectedRootCapacityEvidence_CollectAnonymousAggregates
fi
export TIDB_DATABASE="$database_name"
run_tagged_test "$measurement_test"

python3 -m json.tool "$out_dir/result.json" >/dev/null
echo "$evidence_label evidence: $out_dir"
