#!/usr/bin/env sh
set -eu

BASE_URL="${DAREBUILD_BASE_URL:-https://elonman.darebuild.com}"
DEST_DIR="${DAREBUILD_AGENT_DIR:-.darebuild}"
CLIENT_PATH="${DEST_DIR}/darebuild_agent.py"
MANIFEST_PATH="${DEST_DIR}/darebuild-agent.json"

if command -v python3 >/dev/null 2>&1; then
  PYTHON_BIN="${PYTHON_BIN:-python3}"
elif command -v python >/dev/null 2>&1; then
  PYTHON_BIN="${PYTHON_BIN:-python}"
else
  echo "python3 or python is required." >&2
  exit 1
fi

mkdir -p "${DEST_DIR}"

download() {
  url="$1"
  target="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "${url}" -o "${target}"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "${target}" "${url}"
  else
    echo "curl or wget is required." >&2
    exit 1
  fi
}

verify_client_artifact() {
  "${PYTHON_BIN}" - "${MANIFEST_PATH}" "${CLIENT_PATH}" <<'PY'
import hashlib
import json
import pathlib
import sys

manifest_path = pathlib.Path(sys.argv[1])
client_path = pathlib.Path(sys.argv[2])
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
artifact = manifest.get("artifacts", {}).get("client", {})
expected_hash = artifact.get("sha256")
expected_bytes = artifact.get("bytes")
if not expected_hash:
    raise SystemExit("Manifest did not include artifacts.client.sha256")
client_bytes = client_path.read_bytes()
actual_hash = hashlib.sha256(client_bytes).hexdigest()
if actual_hash != expected_hash:
    raise SystemExit(f"Artifact hash mismatch for {client_path}: expected {expected_hash}, got {actual_hash}")
if expected_bytes is not None and len(client_bytes) != expected_bytes:
    raise SystemExit(f"Artifact byte count mismatch for {client_path}: expected {expected_bytes}, got {len(client_bytes)}")
PY
}

download "${BASE_URL}/.well-known/darebuild-agent.json" "${MANIFEST_PATH}"
download "${BASE_URL}/agents/client.py" "${CLIENT_PATH}"
verify_client_artifact
rm -f "${MANIFEST_PATH}"
"${PYTHON_BIN}" -m py_compile "${CLIENT_PATH}"
"${PYTHON_BIN}" "${CLIENT_PATH}" check --base-url "${BASE_URL}"
chmod +x "${CLIENT_PATH}" 2>/dev/null || true

cat <<EOF

DareBuild agent client installed:
  ${CLIENT_PATH}

Next commands:
  ${PYTHON_BIN} ${CLIENT_PATH} commands --format json
  ${PYTHON_BIN} ${CLIENT_PATH} bootstrap --magic-link "https://darebuild.com/magic/..." --run-smoke --editor-email "editor@example.com"
  ${PYTHON_BIN} ${CLIENT_PATH} account --account-webhook-url "https://darebuild.com/api/codex/v1/account/TOKEN/projects/" --action list
  ${PYTHON_BIN} ${CLIENT_PATH} smoke --account-webhook-url "https://darebuild.com/api/codex/v1/account/TOKEN/projects/"

Security:
  The account webhook is private. Get it by sending the user a DareBuild login-link email
  from the homepage in tool-capable agents, or by having them log in and copy it from
  the dashboard Agent webhooks section or Team settings.
EOF
