#!/usr/bin/env bash
# Usage: probe-typecheck.sh <worktree> <extra-methods>
# Adds N empty probe rpcs to WsRpcGroup (+ ws.ts handler, scope, instrumentation),
# runs apps/server typecheck, then restores the four files.
set -u
wt=$1; n=$2; cd "$wt"
files="packages/contracts/src/rpc.ts apps/server/src/ws.ts apps/server/src/auth/RpcAuthorization.ts apps/server/src/observability/RpcInstrumentation.ts"
git diff --quiet -- $files || { echo "refusing: probe target files are dirty"; exit 64; }
trap "cd \"$wt\" && git checkout -- $files" EXIT
rpcs=""; handlers=""; scopes=""; aggs=""
for i in $(seq 1 "$n"); do
  rpcs+="  Rpc.make(\"probe.method$i\", { payload: Schema.Struct({}), success: Schema.Struct({}) }),\n"
  handlers+="        [\"probe.method$i\"]: () => Effect.succeed({}),\n"
  scopes+="  [\"probe.method$i\"]: AuthOrchestrationReadScope,\n"
  aggs+="  [\"probe.method$i\"]: \"probe\",\n"
done
perl -0pi -e "s/(export const WsRpcGroup = RpcGroup\.make\(\n)/\$1$rpcs/" packages/contracts/src/rpc.ts
perl -0pi -e "s/(const handlers = ServerWsRpcGroup\.of\(\{\n)/\$1$handlers/" apps/server/src/ws.ts
perl -0pi -e "s/(export const RPC_REQUIRED_SCOPES = \{\n)/\$1$scopes/" apps/server/src/auth/RpcAuthorization.ts
perl -0pi -e "s/(const RPC_AGGREGATES = \{\n)/\$1$aggs/" apps/server/src/observability/RpcInstrumentation.ts
echo "WsRpcGroup methods: $(grep -c 'Rpc.make(' packages/contracts/src/rpc.ts) (rpc.ts Rpc.make count)"
(cd apps/server && vp run typecheck) > /tmp/triage-22364/probe-$n.log 2>&1; rc=$?
echo "typecheck exit $rc"
grep -E "error TS(377030|2589)" /tmp/triage-22364/probe-$n.log | sort -u | head -12
echo "error count: $(grep -c ': error TS' /tmp/triage-22364/probe-$n.log)"
exit $rc
