#!/usr/bin/env bash
# askmail — Hardened AI query client
set -euo pipefail
shopt -s inherit_errexit 2>/dev/null || true

SDIR="$(cd "$(dirname "$0")" && pwd)"
source "${SDIR}/se_client.sh"

# ── Input validation ───────────────────────────────────────────────────────
if [[ $# -lt 1 ]]; then
    printf 'Usage: %s prompt [system_prompt]\n' "$0" >&2
    exit 1
fi

readonly PROMPT="${1:-}"
readonly SYSTEM="${2:-You are a security analysis assistant. Provide concise threat assessments.}"

# Validate prompt length and content
if [[ "${#PROMPT}" -gt 4096 ]]; then
    se_log "err" "askmail: prompt exceeds 4096 chars"
    exit 1
fi
if [[ "${#SYSTEM}" -gt 2048 ]]; then
    se_log "err" "askmail: system prompt exceeds 2048 chars"
    exit 1
fi

# Sanitize inputs
readonly SAFE_PROMPT="${PROMPT//[$'\x00-\x08\x0b\x0c\x0e-\x1f']}"
readonly SAFE_SYSTEM="${SYSTEM//[$'\x00-\x08\x0b\x0c\x0e-\x1f']}"

# ── Build request ──────────────────────────────────────────────────────────
BODY="$(jq -n \
    --arg p "${SAFE_PROMPT}" \
    --arg s "${SAFE_SYSTEM}" \
    '{"model":"mistral","prompt":$p,"system":$s}')"

# ── Sign and send ──────────────────────────────────────────────────────────
TS="$(date -u +%s)"
NONCE="$(openssl rand -hex 16)"
readonly PAYLOAD="POST/a/ai/generate${BODY}"
SIG="$(printf '%s' "${PAYLOAD}" | openssl dgst -sha256 -hmac "${VAULT_KEY}" -binary | xxd -p -c 64)"

RESP=""
RESP="$(curl -sS --fail-with-body \
    --connect-timeout 5 -m 30 \
    -X POST "${ENGINE_URL}/a/ai/generate" \
    -H "Content-Type: application/json" \
    -H "x-engine-ts: ${TS}" \
    -H "x-engine-nonce: ${NONCE}" \
    -H "x-engine-sig: ${SIG}" \
    -H "x-engine-node: ${NODE_ID}" \
    -d "${BODY}" 2>/dev/null)" || RESP=''

# ── Parse response ─────────────────────────────────────────────────────────
if [[ -n "${RESP}" ]]; then
    TXT="$(printf '%s' "${RESP}" | jq -r '.text // .response // .output // .result // empty' 2>/dev/null || printf '%s' '')"
    if [[ -n "${TXT}" ]]; then
        printf '%s\n' "${TXT}"
        se_log "info" "ai_query: success len=${#TXT}"
        exit 0
    fi
fi

se_log "err" "ai_query: failed or empty response"
exit 1
