#!/usr/bin/env bash
# orchestrate.sh — Sovereign Orchestrator wrapper
# Sets environment and runs orchestrator.py
#
# Usage:
#   ./orchestrate.sh              # dry-run (safe default)
#   ./orchestrate.sh --once       # single live dispatch cycle
#   ./orchestrate.sh --daemon     # continuous (every 15 min)
#   ./orchestrate.sh --dry-run    # explicit dry-run

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HERMES_DIR="${HOME}/.hermes"

# Load Gitea token
if [[ -z "${GITEA_TOKEN:-}" ]]; then
    if [[ -f "${HERMES_DIR}/gitea_token_vps" ]]; then
        export GITEA_TOKEN="$(cat "${HERMES_DIR}/gitea_token_vps")"
    else
        echo "[FATAL] No GITEA_TOKEN and ~/.hermes/gitea_token_vps not found"
        exit 1
    fi
fi

# Load Telegram token
if [[ -z "${TELEGRAM_BOT_TOKEN:-}" ]]; then
    if [[ -f "${HOME}/.config/telegram/special_bot" ]]; then
        export TELEGRAM_BOT_TOKEN="$(cat "${HOME}/.config/telegram/special_bot")"
    fi
fi

# Run preflight checks if available
if [[ -x "${HERMES_DIR}/bin/api-key-preflight.sh" ]]; then
    "${HERMES_DIR}/bin/api-key-preflight.sh" 2>/dev/null || true
fi

# Run the orchestrator
exec python3 "${SCRIPT_DIR}/orchestrator.py" "$@"
