#!/bin/sh
# Install or reconcile the current teammate's DramaFoundry access and skill.
# Requires FORNACE_TOKEN, normally supplied by `pi fornace install|update`.
set -eu
BASE="${PI_SETUP_BASE:-https://onboarding.fornace.app}"
PI_DIR="${PI_DIR:-$HOME/.pi/agent}"
TOKEN="${FORNACE_TOKEN:-}"
if [ -z "$TOKEN" ] && [ -f "$PI_DIR/auth.json" ]; then
  TOKEN="$(node -e 'try{const a=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));process.stdout.write(a?.mantice?.key||a?.fornace?.key||"");}catch(_){}' "$PI_DIR/auth.json")"
fi
ACTION="${1:-install}"
case "$ACTION" in install|update) ;; *) echo "Usage: $0 [install|update]"; exit 2 ;; esac
[ -n "$TOKEN" ] || { echo "FORNACE_TOKEN is required for DramaFoundry $ACTION."; exit 1; }
case "$TOKEN" in mantice_[A-Za-z0-9_-]*|sk-[A-Za-z0-9_-]*) ;; *) echo "FORNACE_TOKEN must be the teammate key from @fornaceaibot."; exit 1 ;; esac
command -v node >/dev/null 2>&1 || { echo "Node.js is required."; exit 1; }

CREDENTIAL_DIR="$PI_DIR/credentials"
CREDENTIAL_FILE="$CREDENTIAL_DIR/dramafoundry.json"
EXISTING=""
if [ -f "$CREDENTIAL_FILE" ]; then
  EXISTING="$(node -e '
    const fs=require("fs");
    try { process.stdout.write(JSON.parse(fs.readFileSync(process.argv[1],"utf8")).token || ""); } catch (_) {}
  ' "$CREDENTIAL_FILE")"
fi
PAYLOAD="$(DF_EXISTING="$EXISTING" node -e 'process.stdout.write(JSON.stringify(process.env.DF_EXISTING ? {existing_token:process.env.DF_EXISTING} : {}))')"
TMP_RESPONSE="$(mktemp)"
trap 'rm -f "$TMP_RESPONSE" "${TMP_SKILLS:-}"' EXIT HUP INT TERM
CODE="$(curl -sS -o "$TMP_RESPONSE" -w '%{http_code}' \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  --data "$PAYLOAD" --max-time 20 \
  https://llm.fornace.net/auth/dramafoundry/provision 2>/dev/null || echo 000)"
[ "$CODE" = "200" ] || { echo "DramaFoundry provisioning failed (HTTP $CODE)."; exit 1; }
mkdir -p "$CREDENTIAL_DIR"
DF_RESPONSE="$TMP_RESPONSE" node -e '
  const fs=require("fs"), src=JSON.parse(fs.readFileSync(process.env.DF_RESPONSE,"utf8"));
  if(!src.ok || !src.username || !src.token) throw new Error("invalid DramaFoundry provisioning response");
  fs.writeFileSync(process.argv[1],JSON.stringify({gateway_url:src.gateway_url,username:src.username,token:src.token},null,2)+"\n",{mode:0o600});
' "$CREDENTIAL_FILE"
chmod 600 "$CREDENTIAL_FILE"

if [ ! -f "$PI_DIR/skills/dramafoundry/SKILL.md" ]; then
  TMP_SKILLS="$(mktemp)"
  curl -fsSL "$BASE/pi-skills.zip" -o "$TMP_SKILLS"
  mkdir -p "$PI_DIR/skills"
  rm -rf "$PI_DIR/skills/dramafoundry"
  unzip -oq "$TMP_SKILLS" 'dramafoundry/*' -d "$PI_DIR/skills"
  [ -f "$PI_DIR/skills/dramafoundry/SKILL.md" ] || { echo "DramaFoundry skill missing from the team bundle."; exit 1; }
fi

echo "DramaFoundry $ACTION complete for $(node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).username)' "$CREDENTIAL_FILE")."
echo "Credentials: $CREDENTIAL_FILE"
