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

# Dry-run cron/n8n advisory wrapper.
# It calls the advisory classifier and prints one compact decision line.
# It does not send, restart, route, execute tools, or write memory.

GATEWAY_URL="${NPU_ADVISORY_GATEWAY_URL:-http://172.19.0.1:18830}"
WORKFLOW="${1:-cron-advisory-sample}"
SEVERITY="${2:-normal}"
EVENT_KIND="${3:-health_check}"
SUBJECT="${4:-sample advisory event}"
DEDUPE_KEY="${5:-sample}"
TRACE_ID="${NPU_ADVISORY_TRACE_ID:-cron:${WORKFLOW}:$(date -u +%Y%m%dT%H%M%SZ)}"

TEXT="source=cron workflow=${WORKFLOW} severity=${SEVERITY} kind=${EVENT_KIND} subject=${SUBJECT} dedupe_key=${DEDUPE_KEY} dry_run=true authority=no-send,no-restart,no-memory"

payload=$(jq -nc --arg trace_id "$TRACE_ID" --arg text "$TEXT" '{trace_id:$trace_id,text:$text}')
response=$(curl -fsS "${GATEWAY_URL%/}/v1/advisory/classify" -H 'Content-Type: application/json' -d "$payload")

printf '%s\n' "$response" | jq -c --arg source cron --arg workflow "$WORKFLOW" --arg severity "$SEVERITY" --arg dedupe_key "$DEDUPE_KEY" '
  . as $env
  | ($env.result.labels.urgency.value // "normal") as $urgency
  | ($env.result.labels.urgency.confidence // 0) as $confidence
  | ($env.npu_proof.ok == true and (($env.npu_proof.npu_busy_delta_us // 0) > 0)) as $npu_ok
  | (if ($npu_ok | not) then "log"
     elif ($severity == "critical") then "escalate"
     elif ($severity == "warning" or $urgency == "high" or $urgency == "critical") then "summarize"
     else "log" end) as $recommendation
  | (if ($recommendation == "log" and $severity == "normal") then "no_op" else "action_required" end) as $classification
  | {
      schema: "cron_n8n_advisory_decision_v1",
      trace_id: $env.trace_id,
      source: $source,
      workflow: $workflow,
      dry_run: true,
      recommendation: $recommendation,
      classification: $classification,
      confidence: $confidence,
      reason_codes: ([
        (if $npu_ok then "npu_proof_ok" else "npu_proof_failed" end),
        ("severity_" + $severity),
        ("urgency_" + $urgency)
      ]),
      npu_proof: $env.npu_proof,
      authority: $env.authority,
      next_gate: (if $recommendation == "escalate" or $recommendation == "summarize" then "human_or_atlas_review_required_before_any_side_effect" else "none_in_dry_run" end)
    }'
