#!/usr/bin/env bash
# ask-agent — Délègue une question à un agent Funk via LiteLLM.
#
# Usage:
#   ask-agent <agent> "<question>"
#   ask-agent <agent> "<question>" [--max-tokens N] [--system "<prompt>"]
#
# Agents: system | monitor | brain | funk-ai

set -euo pipefail

LITELLM_URL="http://127.0.0.1:4000/v1/chat/completions"
API_KEY="lm-studio"
MAX_TOKENS=1000
SYSTEM_PROMPT=""

declare -A MODELS=(
    [system]="qwen3-1.7b-system"
    [monitor]="qwen3-1.7b-monitor"
    [brain]="claude-sonnet-4-6"
    [funk-ai]="qwen3-8b"
)

usage() {
    echo "Usage: ask-agent <agent> \"<question>\" [--max-tokens N] [--system \"<prompt>\"]"
    echo "Agents: system | monitor | brain | funk-ai"
    exit 1
}

[ $# -lt 2 ] && usage

AGENT="$1"
QUESTION="$2"
shift 2

# Qwen3 thinking mode : les agents rapides (system/monitor) doivent répondre
# directement sans passer du temps en raisonnement interne.
# /no_think désactive le mode thinking pour system et monitor.
case "$AGENT" in
    system|monitor) QUESTION="/no_think ${QUESTION}" ;;
esac

while [ $# -gt 0 ]; do
    case "$1" in
        --max-tokens) MAX_TOKENS="$2"; shift 2 ;;
        --system)     SYSTEM_PROMPT="$2"; shift 2 ;;
        *) echo "Option inconnue : $1" >&2; exit 1 ;;
    esac
done

MODEL="${MODELS[$AGENT]:-}"
if [ -z "$MODEL" ]; then
    echo "Agent inconnu : $AGENT. Agents valides : ${!MODELS[*]}" >&2
    exit 1
fi

# Construire le tableau messages JSON
if [ -n "$SYSTEM_PROMPT" ]; then
    MESSAGES=$(jq -n \
        --arg sp "$SYSTEM_PROMPT" \
        --arg q  "$QUESTION" \
        '[{"role":"system","content":$sp},{"role":"user","content":$q}]')
else
    MESSAGES=$(jq -n \
        --arg q "$QUESTION" \
        '[{"role":"user","content":$q}]')
fi

PAYLOAD=$(jq -n \
    --arg model "$MODEL" \
    --argjson messages "$MESSAGES" \
    --argjson max_tokens "$MAX_TOKENS" \
    '{model:$model, messages:$messages, max_tokens:$max_tokens, stream:false}')

curl -s -f \
    -X POST "$LITELLM_URL" \
    -H "Authorization: Bearer $API_KEY" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD" \
| jq -r '.choices[0].message.content'
