#!/usr/bin/env bash
# One local/CI walking slice, using the host's pinned release dependencies and
# this exact Core checkout's canonical schema. No private schema copy.
set -euo pipefail
connector_candidate_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
export NEXUSCRM_REPO_ROOT="$connector_candidate_root"
export NEXUSCRM_TIDB_REQUIRED=1
connector_results_dir="${CONNECTOR_PROJECTION_RESULTS_DIR:-$(mktemp -d)}"
mkdir -p "$connector_results_dir"

run_connector_proof() {
  local proof_name="$1" proof_pattern="$2" proof_package="$3"
  shift 3
  local proof_log="$connector_results_dir/$proof_name.jsonl"
  if ! go test "$proof_package" -run "$proof_pattern" -count=1 -json -timeout=3m >"$proof_log" 2>&1; then
    tail -n 60 "$proof_log"
    return 1
  fi
  python3 - "$proof_log" "$@" <<'PY'
import json, sys
rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')]
passed = {r.get('Test') for r in rows if r.get('Action') == 'pass'}
skipped = [r.get('Test') for r in rows if r.get('Action') == 'skip']
missing = set(sys.argv[2:]) - passed
if skipped or missing:
    raise SystemExit(f'proof did not execute: skipped={skipped}, missing={sorted(missing)}')
print(f'{sys.argv[1]}: {len(passed - {None})} tests/subtests passed; no skips')
PY
}

# A canonical table must have explicit managed inventory and scope-floor entries.
# Run the existing shared checks before the database-dependent walking slice.
(
  cd "$connector_candidate_root/shared"
  run_connector_proof schema-inventory '^(TestAllSystemTableNamesCoversSchemaCatalog|TestScopeFloorDocumentsManagedTables)$' \
    ./pkg/constants TestAllSystemTableNamesCoversSchemaCatalog TestScopeFloorDocumentsManagedTables
)

: "${TIDB_HOST:?declare the candidate TiDB host}"
: "${TIDB_PORT:?declare the candidate TiDB port}"
cd "$connector_candidate_root/backend"

connector_events_proofs=(
  TestService_SourceProjectionDuplicateLifecycle
  TestSourceProjectionRangeLegacyClockAndCoalescing
  TestSourceProjectionRangeEventOwnedCompletionDoesNotRejectSafeBatch
  TestSourceProjectionRangeFrozenActiveAndQueuedSuccessor
  TestSourceProjectionRangeUnconvertedActiveRollsBackFreshInput
  TestSourceProjectionRangeEnqueueClaimRace
  TestSourceProjectionRangeRetryThenExplicitReplay
  TestSourceProjectionRangeCommandInsideOrdinalRangeIsExcluded
  TestService_SourceProjectionDuplicateSeesCommittedGenerationAfterWaiting
  TestService_SettledProjectionConcurrentCompleteAndEnqueueNeverLoseSuccessor
  TestRepository_SourceProjectionCompletionDoesNotInvertEnqueueLocks
  TestServiceEnqueueBatchConvergesSnapshotStaleWorkItemRepair49By89TiDB
  TestService_NamespaceFenceArmWaitsForAlreadyAdmittedMaterialization
  TestService_NamespaceFenceRejectsPostArmEnqueueAndFastReadIsNotAuthority
  TestService_NamespaceFenceEpochDistinguishesPauseResumePauseABA
  TestService_NamespaceFenceRejectsAmbiguousLegacyGlobalRows
  TestService_NamespaceFenceArmWaitsForAlreadyAdmittedReplay
)
connector_events_pattern="^($(IFS='|'; echo "${connector_events_proofs[*]}"))$"
run_connector_proof events "$connector_events_pattern" \
  github.com/pingcap-inc/nexuscrm-connectors/features/connector/events "${connector_events_proofs[@]}"
run_connector_proof worker '^TestProjectionRangeEnqueueThroughWorkerFlowInputsTiDB$' \
  github.com/pingcap-inc/nexuscrm-connectors/features/connector/inbound TestProjectionRangeEnqueueThroughWorkerFlowInputsTiDB
run_connector_proof pressure '^TestNormalEnqueuePressureUsesCanonicalSchemaTiDB$' \
  github.com/pingcap-inc/nexuscrm-connectors/tools/local_workitem_pressure TestNormalEnqueuePressureUsesCanonicalSchemaTiDB
# Scheduling is a separate fix in the selected connector release. Verify its
# driver-visible time contract without changing the projection acceptance claim.
run_connector_proof outbound-deadlines '^TestRepository(NextWorkAtSchedulingBoundariesTiDB|WorkHintCoversPendingExpiredAndWritebackAgainstTiDB)$' \
  github.com/pingcap-inc/nexuscrm-connectors/features/connector/outboundintent TestRepositoryNextWorkAtSchedulingBoundariesTiDB TestRepositoryWorkHintCoversPendingExpiredAndWritebackAgainstTiDB
run_connector_proof ingress-deadlines '^TestNextClaimableAtSchedulingBoundariesTiDB$' \
  github.com/pingcap-inc/nexuscrm-connectors/features/connector/ingressreceipts TestNextClaimableAtSchedulingBoundariesTiDB
run_connector_proof cutover '^TestProjectionRangeCutover' \
  github.com/pingcap-inc/nexuscrm-controlplane TestProjectionRangeCutoverProof TestProjectionRangeCutoverTiDB TestProjectionRangeCutoverThenNativeExecutionTiDB TestProjectionRangeCutoverLifecycleBoundariesTiDB TestProjectionRangeCutoverExecutionAuthorityTiDB TestProjectionRangeCutoverRetiredHistoryTiDB \
  TestProjectionRangeCutoverNonConnectorActivationTiDB TestProjectionRangeCutoverConnectorActivationTiDB TestProjectionRangeCutoverOrdinaryCompletionTiDB TestProjectionRangeCutoverFenceDSNTiDB
GOFLAGS="${GOFLAGS:+$GOFLAGS }-tags=integration" run_connector_proof activation '^TestProjectionRangeCutoverSourceRevisionActivationTiDB$' \
  github.com/pingcap-inc/nexuscrm-controlplane TestProjectionRangeCutoverSourceRevisionActivationTiDB \
  TestProjectionRangeCutoverSourceRevisionActivationTiDB/unclaimed_projection_blocks_revision

connector_host_proofs=(
  TestProductionCompositionStartsAgainstPublishedSchema
  TestProductionCompositionBindsSelectedConnectorGeneration
  TestIntegrationServingAuthorityRejectsUnexecutableRuntimeCommandRoute
  TestIntegrationServingAuthorityRejectsNonActiveSelectedGeneration
  TestM2IntegrationHandoffCrossesSeparateRuntimeProcess
  TestM2V2ExecutionConformanceCrossesSeparateRuntimeProcessWithoutProductionReachability
)
connector_host_pattern="^($(IFS='|'; echo "${connector_host_proofs[*]}"))$"
GOFLAGS="${GOFLAGS:+$GOFLAGS }-tags=integration_service_integration" run_connector_proof host "$connector_host_pattern" \
  ./internal/integrationservice "${connector_host_proofs[@]}"
