#!/usr/bin/env bash
# Current inbound identity ownership and retained-history proof, shared by local
# verification and trusted-main CI. Retired outbound execution is not an owner.
set -euo pipefail

connector_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
connector_results_dir="${OUT_DIR:-$(mktemp -d)}"
mkdir -p "$connector_results_dir"
: "${TIDB_HOST:?declare the candidate TiDB host}"
: "${TIDB_PORT:?declare the candidate TiDB port}"
export NEXUSCRM_TIDB_REQUIRED=1
export GOWORK=off
cd "$connector_root/nexuscrm-automation"

# One list selects the tests and checks their pass events. A removed or renamed
# proof, an unavailable database, or any skipped subtest must fail this gate.
connector_tests=(
  TestConnectorInboundFinalizationConcurrentRemoteLocatorOwnership
  TestConnectorPushDurablePointReadOutcomesOnTiDB
  TestConnectorPushDurableSnapshotDecodingOnTiDB
  TestConnectorIntegrationTransferSourcesOnTiDB
  TestConnectorIntegrationTransferMirrorsAreNotAuthorityOnTiDB
  TestConnectorIntegrationTransferAtomicPublicationFailuresOnTiDB
  TestConnectorIntegrationTransferProofRejectionsOnTiDB
  TestConnectorIntegrationTransferTargetReplayOnTiDB
  TestConnectorIntegrationTransferFreshCommandFenceOnTiDB
  TestConnectorIntegrationV1BridgeOwnerMutationFenceOnTiDB
  TestConnectorIntegrationV1BridgeFreshDispatchFenceOnTiDB
  TestConnectorIntegrationV1BridgeOwnerMutationWinsOnTiDB
  TestConnectorIntegrationOwnerDeleteBeforeFirstLinkRequiresSettledIntentOnTiDB
  TestConnectorIntegrationOwnerDeleteRequiresV2ProofOnTiDB
)
connector_pattern="^($(IFS='|'; echo "${connector_tests[*]}"))$|^(TestSQLConnector(Inbound|Transfer|Adopt)|TestFindRecordPushState_)"
connector_results="$connector_results_dir/connector-identity-ownership.jsonl"
if go test . -run "$connector_pattern" -count=1 -json -timeout=10m >"$connector_results" 2>&1; then
  python3 - "$connector_results" "${connector_tests[@]}" <<'PY'
import json
import sys

with open(sys.argv[1]) as source:
    rows = [json.loads(line) for line in source if line.startswith('{')]
passed = {row.get('Test') for row in rows if row.get('Action') == 'pass'}
skipped = [row.get('Test') for row in rows if row.get('Action') == 'skip']
missing = set(sys.argv[2:]) - passed
if skipped or missing:
    raise SystemExit(f'identity ownership proof did not execute: skipped={skipped}, missing={sorted(missing)}')
print(f'{sys.argv[1]}: {len(passed - {None})} tests/subtests passed; no skips')
PY
else
  connector_exit=$?
  tail -n 80 "$connector_results"
  exit "$connector_exit"
fi
