#!/usr/bin/env bash
# team-kpi-visibility-test — validate per-team KPI surfaces in ARQERA.
#
# Per operator directive 2026-05-18 (operational-organization-activation-wave-1):
# each ARQERA operational function should answer 8 questions:
#   1. what matters now?
#   2. what is blocked?
#   3. what is active?
#   4. what was completed?
#   5. what evidence exists?
#   6. what KPI changed?
#   7. what needs escalation?
#   8. which habitat/worker owns the next action?
#
# This script tests EACH of the 9 functions for whether a substrate
# body or staging surface exists that answers those questions:
#   product, engineering, design, marketing, sales,
#   customer-support, customer-success, operations/cost, governance/survivability
#
# For functions WITHOUT a surface: classify GAP and emit as operational
# pressure for the next bounded wave. The substrate now SEES which
# functions are operationally orphan.
#
# Habitat-portable. No mutations.

set -euo pipefail

FORMAT="human"
EMIT="false"
STAGING="${ARQERA_STAGING_URL:-https://staging.arqera.io}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --json) FORMAT="json"; shift ;;
    --emit) EMIT="true"; FORMAT="json"; shift ;;
    --staging) STAGING="$2"; shift 2 ;;
    --help|-h) sed -n '2,20p' "$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
if ! command -v curl >/dev/null 2>&1; then
  echo "error: curl not on PATH" >&2; exit 2
fi
if ! command -v python3 >/dev/null 2>&1; then
  echo "error: python3 not on PATH" >&2; exit 2
fi

RESULTS=""
record() {
  RESULTS+="$1|$2|$3|$4|$5"$'\n'
}

# Check substrate body exists at address. Outputs "yes" or "".
substrate_body_exists() {
  local addr="$1"
  twin --use-keychain address fetch "$addr" --json 2>/dev/null \
    | python3 -c "import json,sys
try:
    d=json.loads(sys.stdin.read())
    print('yes' if d.get('sha256') else '')
except: print('')" 2>/dev/null || echo ""
}

# Check staging route reachable. Outputs "code|spa_fallback" where
# spa_fallback="yes" if the page body indicates a generic not-found
# view (Next.js often returns http=200 for any path + client-renders a
# 404). A real KPI surface has neither "404" nor "not found" in body.
staging_route_code() {
  local route="$1"
  local code body_check
  curl -s -L -o /tmp/team_kpi_$$ --max-time 10 -w '%{http_code}' "${STAGING}${route}" 2>/dev/null > /tmp/team_kpi_code_$$
  code=$(cat /tmp/team_kpi_code_$$ 2>/dev/null || echo "000")
  if [[ -f /tmp/team_kpi_$$ ]]; then
    # SPA-fallback markers: explicit "404", "page not found", "this page
    # could not be found". Case-insensitive grep on the rendered HTML.
    if grep -qiE "(this page (could not be|does not) (found|exist)|page not found|^\s*404\s*$|>404<|>Not Found<)" /tmp/team_kpi_$$; then
      body_check="yes"
    else
      body_check="no"
    fi
  else
    body_check="unknown"
  fi
  rm -f /tmp/team_kpi_$$ /tmp/team_kpi_code_$$
  echo "${code}|${body_check}"
}

# For each function: try a SUBSTRATE body OR a STAGING route. If either is
# present, PASS. If neither, GAP. We test the 9 functions defined in the
# operator directive.

check_function() {
  local fn="$1" substrate_addr="$2" staging_route="$3" matters_via="$4"
  local body=$(substrate_body_exists "$substrate_addr")
  local code="000" spa_fallback="unknown"
  if [[ -n "$staging_route" ]]; then
    local probe=$(staging_route_code "$staging_route")
    code="${probe%%|*}"
    spa_fallback="${probe##*|}"
  fi
  if [[ -n "$body" ]]; then
    record "team-kpi" "$fn" "PASS" "substrate: $substrate_addr" "$matters_via"
  elif [[ "$code" =~ ^[23] ]] && [[ "$spa_fallback" != "yes" ]]; then
    record "team-kpi" "$fn" "PASS" "staging: ${STAGING}${staging_route} http=$code (real surface)" "$matters_via"
  elif [[ "$code" =~ ^[23] ]] && [[ "$spa_fallback" == "yes" ]]; then
    record "team-kpi" "$fn" "GAP" "staging route returns 200 but body indicates not-found (SPA fallback) — no real surface" "$matters_via"
  else
    record "team-kpi" "$fn" "GAP" "no substrate body + no staging surface (probe http=$code)" "$matters_via"
  fi
}

# 9 functions × (substrate addr | staging route | what-it-answers)
# Substrate-body candidates were chosen from what exists today; staging
# routes correspond to surfaces actually built.

check_function \
  "product" \
  "arq://body/convergence_queue/v2" \
  "/system/substrate-health" \
  "convergence queue + substrate-health panels answer what-matters/active/completed/evidence/owner"

check_function \
  "engineering" \
  "arq://body/peer_workspace_state/578412e7b083b40e56e228779804582a-current" \
  "/system/substrate-health" \
  "PeerWorkspacePanel + DeployRealityPanel + recent merge_landed acts answer active/completed/owner"

check_function \
  "design" \
  "arq://body/design_system_state/v1" \
  "/design" \
  "design-system body + /design surface (gap likely — no current substrate evidence)"

check_function \
  "marketing" \
  "arq://body/marketing_state/v1" \
  "/marketing" \
  "marketing surface body + /marketing route (gap likely)"

check_function \
  "sales" \
  "arq://body/sales_pipeline/v1" \
  "/sales" \
  "sales pipeline body + /sales route (gap likely)"

check_function \
  "customer-support" \
  "arq://body/support_queue/v1" \
  "/help" \
  "support queue body + /help route"

check_function \
  "customer-success" \
  "arq://body/customer_success_state/v1" \
  "/success" \
  "customer-success body + /success route (gap likely)"

check_function \
  "operations-cost" \
  "arq://body/cost_topology/v1" \
  "/system/substrate-health" \
  "OperationalGravityPanel + cost_topology body answer cost/operations KPIs"

check_function \
  "governance-survivability" \
  "arq://body/sovereignty_metrics/aggregate-current" \
  "/system/substrate-health" \
  "SovereigntyDistributionPanel + sovereignty_metrics body answer governance/survivability KPIs"

# --- Tally + output ---
RESULTS_JSON=$(RAW="$RESULTS" STAGING="$STAGING" 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('|', 4)
    if len(parts) != 5: continue
    section, fn, verdict, evidence, matters_via = parts
    checks.append({
        "function": fn,
        "verdict": verdict,
        "evidence": evidence,
        "answers_8_questions_via": matters_via,
    })
    totals[verdict] = totals.get(verdict, 0) + 1
print(json.dumps({
    "schema_version": 1,
    "test": "team-kpi-visibility-test",
    "tested_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
    "staging_base": os.environ.get("STAGING", ""),
    "operator_directive": "operational-organization-activation-wave-1",
    "totals": totals,
    "functions": 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 team_kpi_visibility_test_completed "$TODAY" \
    --payload "$PAYLOAD" --source twin-team-kpi-visibility-test --sync >/dev/null
fi

if [[ "$FORMAT" == "json" ]]; then
  echo "$RESULTS_JSON"
  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 "=== team-kpi-visibility-test ($STAGING) ==="
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 "  %-26s %-7s %s\n" "function" "verdict" "evidence"
echo "$RESULTS_JSON" | python3 -c "
import json,sys
d=json.load(sys.stdin)
for f in d['functions']:
    print(f\"  {f['function']:<26} {f['verdict']:<7} {f['evidence'][:90]}\")"
echo ""
if [[ "$F" -gt 0 ]]; then
  echo "  verdict: FAIL ($F function-KPI surfaces broken)"
  exit 1
elif [[ "$G" -gt 0 ]]; then
  echo "  verdict: PASS-with-gaps ($G functions lack KPI surfaces — operational pressure)"
else
  echo "  verdict: PASS (every function has substrate-canonical KPI visibility)"
fi
