#!/usr/bin/env bash
set -euo pipefail
source "$(dirname "$0")/_beagle-racket"

if [[ $# -lt 1 ]]; then
    echo "usage: beagle-provides <file-or-dir> ..." >&2
    exit 2
fi

# Route through daemon if running
PORTFILE="${BEAGLE_DAEMON_PORTFILE:-/var/tmp/beagle-daemon.port}"
if [[ -f "$PORTFILE" ]]; then
    port=$(cat "$PORTFILE")
    if (exec 3<>/dev/tcp/127.0.0.1/"$port") 2>/dev/null; then
        exec 3<>/dev/tcp/127.0.0.1/"$port"
        echo "provides $*" >&3
        read -r response <&3
        exec 3>&-
        echo "$response" | python3 -c "
import json, sys
data = json.load(sys.stdin)
if not data.get('ok'):
    print(data.get('error', 'unknown error'), file=sys.stderr); sys.exit(1)
if data.get('namespace'):
    print(f'namespace: {data[\"namespace\"]}\n')
recs = data.get('records', [])
if recs:
    print('records:')
    for r in recs:
        fields = ' '.join(f'{f[\"name\"]}:{f[\"type\"]}' for f in r.get('fields', []))
        print(f'  {r[\"name\"]} [{fields}]')
    print()
fns = data.get('functions', [])
if fns:
    print('functions:')
    for f in fns:
        print(f'  {f[\"name\"]} : {f[\"signature\"]}')
    print()
"
        exit 0
    fi
fi

"$RACKET" -e "(require beagle/private/query) (run-query (cons \"provides\" (vector->list (current-command-line-arguments))))" -- "$@"
