#!/usr/bin/env bash
# org-operating-test — validate ARQERA-as-an-operating-organization.
#
# Per operator directive 2026-05-18 (operational-organization-activation-wave-1):
# "ARQERA must increasingly behave like a real decentralized operational
# company." This script tests whether the substrate currently exhibits
# organizational behavior, not just observability.
#
# Habitat-portable: runs on Mac, GH Actions, Homebase, DGX, customer Mac.
# Pure substrate reads + classification. No mutations. No paid calls.
#
# Test sections:
#   1. Org primitives present       — sovereignty + activation + queue + envelopes
#   2. Verifier/executor separation — role transitions + Mac-not-builder
#   3. Decisions sourced from substrate — recent merge_landed / deploy / handoff acts
#   4. Distributed habitats         — ≥2 distinct peer triads
#   5. No operator-as-message-bus   — substrate-routable continuation pickup works
#   6. No hidden habitat sovereignty — Mac in habitats_at_risk visible
#
# Each check: PASS / GAP (substrate evidence missing) / FAIL.
# `--emit` posts a `arq://act/org_operating_test_completed/<date>` act.
#
# Usage:
#   scripts/org-operating-test                # human-readable
#   scripts/org-operating-test --json         # JSON
#   scripts/org-operating-test --emit         # substrate-emit findings

set -euo pipefail

FORMAT="human"
EMIT="false"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --json) FORMAT="json"; shift ;;
    --emit) EMIT="true"; FORMAT="json"; shift ;;
    --help|-h) sed -n '2,30p' "$0"; exit 0 ;;
    *) echo "unknown arg: $1" >&2; exit 2 ;;
  esac
done

if ! command -v twin >/dev/null 2>&1; then
  echo "error: twin CLI not on PATH" >&2; exit 2
fi

# Result accumulator: each line "section|check|verdict|evidence"
RESULTS=""
record() {
  RESULTS+="$1|$2|$3|$4"$'\n'
}

check_address_exists() {
  local label="$1" addr="$2"
  local out
  out=$(twin --use-keychain address fetch "$addr" --json 2>/dev/null | python3 -c "import json,sys;print(json.loads(sys.stdin.read()).get('sha256',''))" 2>/dev/null || echo "")
  if [[ -n "$out" ]]; then
    record "org-primitives" "$label" "PASS" "$addr@${out:0:12}"
  else
    record "org-primitives" "$label" "GAP" "$addr not on substrate"
  fi
}

# --- Section 1: org primitives present ---
check_address_exists "sovereignty-metrics-aggregate"  "arq://body/sovereignty_metrics/aggregate-current"
check_address_exists "activation-map-v1"              "arq://body/activation_map/v1"
check_address_exists "convergence-queue-v2"           "arq://body/convergence_queue/v2"
check_address_exists "cost-topology-v1"               "arq://body/cost_topology/v1"
check_address_exists "Mac-peer-workspace-state"       "arq://body/peer_workspace_state/578412e7b083b40e56e228779804582a-current"
check_address_exists "Mac-peer-operational-state"     "arq://body/peer_operational_state/578412e7b083b40e56e228779804582a-current"
check_address_exists "Mac-peer-routing-readiness"     "arq://body/peer_routing_readiness/578412e7b083b40e56e228779804582a-current"
check_address_exists "Homebase-peer-workspace-state"   "arq://body/peer_workspace_state/2e172c010ebcd3e8ce39cd33b34b49f6-current"
check_address_exists "Homebase-peer-operational-state" "arq://body/peer_operational_state/2e172c010ebcd3e8ce39cd33b34b49f6-current"
check_address_exists "Homebase-peer-routing-readiness" "arq://body/peer_routing_readiness/2e172c010ebcd3e8ce39cd33b34b49f6-current"

# --- Section 2: verifier/executor separation ---
ROLE_ACT="arq://act/peer_role_transition/mac-builder-to-uat-verifier-2026-05-18"
ROLE_SHA=$(twin --use-keychain address fetch "$ROLE_ACT" --json 2>/dev/null | python3 -c "import json,sys;print(json.loads(sys.stdin.read()).get('sha256',''))" 2>/dev/null || echo "")
if [[ -n "$ROLE_SHA" ]]; then
  record "verifier-executor-separation" "mac-role-transition-recorded" "PASS" "$ROLE_ACT"
else
  record "verifier-executor-separation" "mac-role-transition-recorded" "GAP" "no role transition act"
fi

# Check Mac's peer_routing_readiness reports code_authoring=suspended (verifier mode)
MAC_RR=$(twin --use-keychain address fetch arq://body/peer_routing_readiness/578412e7b083b40e56e228779804582a-current --json 2>/dev/null | python3 -c "import json,sys;d=json.loads(sys.stdin.read());p=d.get('payload_preview','');import re;m=re.search(r'\"code_authoring\":\s*\"([^\"]+)\"',p);print(m.group(1) if m else '')" 2>/dev/null || echo "")
if [[ "$MAC_RR" == *"suspended"* ]]; then
  record "verifier-executor-separation" "mac-code-authoring-suspended" "PASS" "routing_readiness.code_authoring=$MAC_RR"
elif [[ -n "$MAC_RR" ]]; then
  record "verifier-executor-separation" "mac-code-authoring-suspended" "GAP" "code_authoring=$MAC_RR (expected suspended)"
else
  record "verifier-executor-separation" "mac-code-authoring-suspended" "GAP" "no code_authoring field in routing readiness"
fi

# --- Section 3: decisions sourced from substrate ---
RECENT_MERGES=$(twin --use-keychain index --type merge_landed --since 2026-05-18 2>&1 | wc -l | tr -d ' ')
if [[ "$RECENT_MERGES" -ge 5 ]]; then
  record "decisions-sourced-from-substrate" "recent-merge-acts-today" "PASS" "${RECENT_MERGES} merge_landed acts since 2026-05-18"
else
  record "decisions-sourced-from-substrate" "recent-merge-acts-today" "GAP" "only $RECENT_MERGES merge_landed acts since today"
fi

OP_APPROVAL_ACT="arq://act/operator_approval_granted/substrate-authority-blanket-approval-pre-uat-2026-05-18"
APPROVAL_SHA=$(twin --use-keychain address fetch "$OP_APPROVAL_ACT" --json 2>/dev/null | python3 -c "import json,sys;print(json.loads(sys.stdin.read()).get('sha256',''))" 2>/dev/null || echo "")
if [[ -n "$APPROVAL_SHA" ]]; then
  record "decisions-sourced-from-substrate" "operator-approval-substrate-attested" "PASS" "$OP_APPROVAL_ACT"
else
  record "decisions-sourced-from-substrate" "operator-approval-substrate-attested" "FAIL" "blanket approval not on substrate"
fi

# --- Section 4: distributed habitats (≥2 distinct peers emitting state) ---
KNOWN_PEERS=$(twin --use-keychain index --class body --type peer_workspace_state --since 2026-05-17 2>&1 | grep -oE 'arq://body/peer_workspace_state/[0-9a-f]+' | sort -u | wc -l | tr -d ' ')
if [[ "$KNOWN_PEERS" -ge 2 ]]; then
  record "distributed-habitats" "≥2-peers-with-workspace-state" "PASS" "$KNOWN_PEERS distinct peers"
else
  record "distributed-habitats" "≥2-peers-with-workspace-state" "GAP" "only $KNOWN_PEERS peer(s) with workspace state"
fi

# --- Section 5: no operator-as-message-bus (continuation pickup substrate-only) ---
if scripts/twin-pickup-continuation --json 2>/dev/null | python3 -c "import json,sys;d=json.loads(sys.stdin.read());assert d.get('schema_version')" 2>/dev/null; then
  record "no-operator-as-message-bus" "substrate-only-pickup-works" "PASS" "scripts/twin-pickup-continuation returns valid queue"
else
  record "no-operator-as-message-bus" "substrate-only-pickup-works" "FAIL" "pickup script cannot read substrate queue"
fi

# --- Section 6: no hidden habitat sovereignty (sovereignty_metrics shows Mac at risk) ---
HABITATS_AT_RISK=$(twin --use-keychain address fetch arq://body/sovereignty_metrics/aggregate-current --json 2>/dev/null | python3 -c "import json,sys;d=json.loads(sys.stdin.read());p=d.get('payload_preview','');import re;m=re.search(r'\"habitats_at_risk\":\s*\[(.*?)\]',p,re.S);print('present' if m and m.group(1).strip() else 'empty')" 2>/dev/null || echo "")
if [[ "$HABITATS_AT_RISK" == "present" ]]; then
  record "no-hidden-habitat-sovereignty" "habitats-at-risk-substrate-visible" "PASS" "sovereignty_metrics reports habitats_at_risk"
else
  record "no-hidden-habitat-sovereignty" "habitats-at-risk-substrate-visible" "GAP" "habitats_at_risk not populated"
fi

# --- Tally + output ---
RESULTS_JSON=$(RAW="$RESULTS" python3 - <<'PY'
import os, json, datetime
checks = []
totals = {"PASS": 0, "GAP": 0, "FAIL": 0}
for line in os.environ.get("RAW", "").strip().splitlines():
    if not line: continue
    parts = line.split('|', 3)
    if len(parts) != 4: continue
    section, check, verdict, evidence = parts
    checks.append({"section": section, "check": check, "verdict": verdict, "evidence": evidence})
    totals[verdict] = totals.get(verdict, 0) + 1
print(json.dumps({
    "schema_version": 1,
    "test": "org-operating-test",
    "tested_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "totals": totals,
    "checks": checks,
}, indent=2))
PY
)

if [[ "$EMIT" == "true" ]]; then
  TODAY=$(date -u +%Y-%m-%d)
  PAYLOAD=$(echo "$RESULTS_JSON" | python3 -c "import json,sys;print(json.dumps(json.load(sys.stdin)))")
  twin --use-keychain act emit act org_operating_test_completed "$TODAY" \
    --payload "$PAYLOAD" --source twin-org-operating-test --sync >/dev/null
fi

if [[ "$FORMAT" == "json" ]]; then
  echo "$RESULTS_JSON"
  PASS=$(echo "$RESULTS_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin)['totals'].get('PASS',0))")
  FAIL=$(echo "$RESULTS_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin)['totals'].get('FAIL',0))")
  [[ "$FAIL" -gt 0 ]] && exit 1 || exit 0
fi

echo "=== org-operating-test ==="
echo ""
P=$(echo "$RESULTS_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin)['totals'].get('PASS',0))")
G=$(echo "$RESULTS_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin)['totals'].get('GAP',0))")
F=$(echo "$RESULTS_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin)['totals'].get('FAIL',0))")
echo "  PASS: $P  GAP: $G  FAIL: $F"
echo ""
printf "  %-32s %-40s %-6s %s\n" "section" "check" "verdict" "evidence"
echo "$RESULTS_JSON" | python3 -c "
import json,sys
d=json.load(sys.stdin)
for c in d['checks']:
    print(f\"  {c['section']:<32} {c['check']:<40} {c['verdict']:<6} {c['evidence'][:80]}\")"
echo ""
if [[ "$F" -gt 0 ]]; then
  echo "  verdict: FAIL ($F substrate-canonical failures)"
  exit 1
elif [[ "$G" -gt 0 ]]; then
  echo "  verdict: PASS-with-gaps ($G gaps surfaced as operational pressure)"
else
  echo "  verdict: PASS (org-operating signals all green)"
fi
