#!/usr/bin/env bash
# arq-context — substrate-native runtime context query.
#
# Per arq://doc/principle/substrate-native-execution-v1.
#
# Use BEFORE any substrate read when you're unsure of the env. Prints a
# deterministic JSON snapshot of where you are + what you can do. If
# can_import_app is false, FIX THE ENV — don't retry the same command.
#
#   arq-context                      # human-readable summary
#   arq-context --json               # raw JSON
#   arq-context --envelope <addr>    # check against a specific envelope
#
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

FORMAT="summary"
ENVELOPE_ARG=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        --json) FORMAT="json"; shift ;;
        --envelope) ENVELOPE_ARG="$2"; shift 2 ;;
        -h|--help) sed -n '2,15p' "$0"; exit 0 ;;
        *) echo "unknown arg: $1" >&2; exit 2 ;;
    esac
done

cd "$REPO_ROOT/backend"

PY_ARGS=""
if [[ -n "$ENVELOPE_ARG" ]]; then
    PY_ARGS="$ENVELOPE_ARG"
fi

if [[ "$FORMAT" == "json" ]]; then
    python3 -c "
import json, sys
from app.tools.runtime_context import current_context
addr = sys.argv[1] if len(sys.argv) > 1 else None
ctx = current_context(addr) if addr else current_context()
print(json.dumps(ctx.to_dict(), indent=2, default=str))
" "$PY_ARGS"
else
    python3 -c "
import sys
from app.tools.runtime_context import current_context
addr = sys.argv[1] if len(sys.argv) > 1 else None
ctx = current_context(addr) if addr else current_context()
ok = '✓'
no = '✗'
print(f'  cwd                : {ctx.cwd}')
print(f'  venv               : {ctx.venv or \"(none)\"}')
print(f'  can_import_app     : {ok if ctx.can_import_app else no}')
print(f'  retrieval prims    : {\", \".join(ctx.available_retrieval_primitives) or \"(none)\"}')
print(f'  envelope           : {ctx.active_envelope}')
print(f'    findable         : {ok if ctx.envelope_findable else no}')
print(f'    scopes           : {ctx.envelope_scopes}')
print(f'    expires          : {ctx.envelope_expires}')
print(f'    expired          : {no if ctx.envelope_expired else ok}')
print(f'  act_queue depth    : {ctx.act_queue_depth}')
if ctx.substrate_snapshot_age_seconds is not None:
    print(f'  substrate snap age : {ctx.substrate_snapshot_age_seconds:.0f}s  cycle={ctx.substrate_snapshot_cycle_id}')
else:
    print(f'  substrate snap     : (no local snapshot)')
print(f'  addressing base    : {ctx.governed_endpoint_addressing_base}')
if ctx.notes:
    print()
    print(f'  ⚠ NOTES ({len(ctx.notes)}):')
    for n in ctx.notes:
        print(f'    • {n}')
" "$PY_ARGS"
fi
