#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ENV_FILE="${1:-$SCRIPT_DIR/ecosystem-hunter.env}"

if [[ -f "$ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$ENV_FILE"
fi

export PYTHON_BIN="${PYTHON_BIN:-/usr/bin/python3}"
export APP_ROOT="${APP_ROOT:-$REPO_ROOT}"
export MCP_API_BASE="${MCP_API_BASE:-https://agent.wooo.work}"
export MCP_API_KEY="${MCP_API_KEY:-}"
export MCP_AGENT_ID="${MCP_AGENT_ID:-vibe-hunter-$(date +%s)}"
export DEVELOPER_WALLET="${DEVELOPER_WALLET:-acct_ecosystem_hunter}"
export AUTO_CLAIM="${AUTO_CLAIM:-false}"
export AUTO_SUBMIT="${AUTO_SUBMIT:-false}"
export AUTO_SUBMIT_PR_URL="${AUTO_SUBMIT_PR_URL:-https://github.com/vibework/a2a-ecosystem-hunter/pull/1}"
export RUN_DAEMON="${RUN_DAEMON:-true}"
export SCAN_INTERVAL_SECONDS="${SCAN_INTERVAL_SECONDS:-300}"
export RECONNECTION_BACKOFF_SECONDS="${RECONNECTION_BACKOFF_SECONDS:-20}"
export NOSTR_RELAY_URL="${NOSTR_RELAY_URL:-wss://relay.damus.io}"
export NOSTR_TAG="${NOSTR_TAG:-VibeWork_Bounty}"
export NOSTR_LIMIT="${NOSTR_LIMIT:-40}"
export EXTERNAL_MCP_ENDPOINTS="${EXTERNAL_MCP_ENDPOINTS:-$MCP_API_BASE}"
export KNOWN_MCP_ENDPOINTS="${KNOWN_MCP_ENDPOINTS:-}"
export MCP_TIMEOUT_SECONDS="${MCP_TIMEOUT_SECONDS:-12}"
export ECOSYSTEM_REPORT_PATH="${ECOSYSTEM_REPORT_PATH:-$REPO_ROOT/artifacts/ecosystem_hunter_report.jsonl}"

mkdir -p "$REPO_ROOT/artifacts"
export REPORT_LOG_DIR="${REPORT_LOG_DIR:-$REPO_ROOT/.local/logs/agent-bounty-ecosystem-hunter}"
mkdir -p "$REPORT_LOG_DIR"

cd "$REPO_ROOT"

if [[ ! -x "$PYTHON_BIN" ]]; then
  echo "[runner] PYTHON_BIN not executable: $PYTHON_BIN"
  exit 1
fi

if [[ -z "${MCP_API_KEY}" ]]; then
  echo "[runner] MCP_API_KEY is empty. Set MCP_API_KEY before running."
  exit 1
fi

STDOUT_LOG="${STDOUT_LOG:-$REPORT_LOG_DIR/ecosystem-hunter.stdout.log}"
STDERR_LOG="${STDERR_LOG:-$REPORT_LOG_DIR/ecosystem-hunter.stderr.log}"

exec "$PYTHON_BIN" scripts/nostr_agent_client.py \
  >>"$STDOUT_LOG" \
  2>>"$STDERR_LOG"
