#!/bin/bash
# =============================================================================
# phoenix-core.sh -- Phoenix AI Orchestrator Interface
# =============================================================================
# Category: phoenix | Bird: eagle | Tier: 1 | Node-aware: yes
# =============================================================================

TOOL_NAME="phoenix-core"
TOOL_VERSION="2.0.0"
TOOL_TIER=1
TOOL_BIRD="eagle"
TOOL_LOG="/opt/binary/logs/tools/${TOOL_NAME}.log"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
if [[ -f "${SCRIPT_DIR}/common.sh" ]]; then source "${SCRIPT_DIR}/common.sh"
elif [[ -f "${SCRIPT_DIR}/../common.sh" ]]; then source "${SCRIPT_DIR}/../common.sh"
else echo "FATAL: common.sh not found" >&2; exit 1; fi

export BIRD_ID="${TOOL_BIRD}"

_do_send_impl() {
    echo "=== Phoenix Status: ${NODE_ID} ==="
    # Check if phoenix containers are running
    local phoenix_svcs=(phoenix-gateway phoenix-orchestrator ollama)
    for svc in "${phoenix_svcs[@]}"; do
        if systemctl cat "${svc}.service" &>/dev/null; then
            local state
            state=$(systemctl is-active "$svc" 2>/dev/null)
            echo "  ${svc}: ${state}"
        fi
    done
    # Check bird containers
    local birds=(dove eagle swan falcon owl hawk heron pigeon kestrel cormorant raven sparrow)
    local up=0 total=0
    for bird in "${birds[@]}"; do
        if systemctl cat "phoenix-${bird}.service" &>/dev/null; then
            total=$((total + 1))
            local state
            state=$(systemctl is-active "phoenix-${bird}" 2>/dev/null)
            [ "$state" = "active" ] && up=$((up + 1))
        fi
    done
    echo "  Birds: ${up}/${total} active"
    tool_audit "send" "birds_up=${up} birds_total=${total} node=${NODE_ID}"
}

_do_status_impl() {
    local gateway="not_installed" orchestrator="not_installed" birds_up=0 birds_total=0
    systemctl cat phoenix-gateway.service &>/dev/null && gateway=$(systemctl is-active phoenix-gateway 2>/dev/null)
    systemctl cat phoenix-orchestrator.service &>/dev/null && orchestrator=$(systemctl is-active phoenix-orchestrator 2>/dev/null)
    local birds=(dove eagle swan falcon owl hawk heron pigeon kestrel cormorant raven sparrow)
    for bird in "${birds[@]}"; do
        if systemctl cat "phoenix-${bird}.service" &>/dev/null; then
            birds_total=$((birds_total + 1))
            [ "$(systemctl is-active phoenix-${bird} 2>/dev/null)" = "active" ] && birds_up=$((birds_up + 1))
        fi
    done
    local status="healthy"
    [ "$birds_up" -lt "$birds_total" ] && status="degraded"
    echo "{\"tool\":\"${TOOL_NAME}\",\"node\":\"${NODE_ID}\",\"status\":\"${status}\",\"gateway\":\"${gateway}\",\"orchestrator\":\"${orchestrator}\",\"birds_up\":${birds_up},\"birds_total\":${birds_total},\"checked_at\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
}

_do_digest_impl() { echo "=== Phoenix Report: ${NODE_ID} ==="; _do_send_impl; }
_do_flush_impl() { [ -f "$TOOL_LOG" ] && truncate -s 0 "$TOOL_LOG" && echo "  [CHANGED] Log truncated"; }

tool_help() {
    echo "${TOOL_NAME} v${TOOL_VERSION} -- Phoenix AI Orchestrator"
    echo "  --send     Check Phoenix services + bird status"
    echo "  --status   JSON pill"
    echo "  --digest   Full report"
    echo "  --flush    Truncate log"
}

do_send()   { tool_wrap "send"   _do_send_impl "$@"; }
do_status() { tool_wrap "status" _do_status_impl "$@"; }
do_digest() { tool_wrap "digest" _do_digest_impl "$@"; }
do_flush()  { tool_wrap "flush"  _do_flush_impl "$@"; }

tool_init; trap 'tool_complete' EXIT
case "${1:---help}" in
    --send) shift; do_send "$@" ;; --status) shift; do_status "$@" ;;
    --digest) shift; do_digest "$@" ;; --flush) shift; do_flush "$@" ;;
    --help) tool_help ;; *) handle_standard_command "$@" ;;
esac
