#!/usr/bin/env bash
# ── Deep Triage — Hermes + Timmy collaborative issue triage ────────────
# Runs periodically (every ~20 dev cycles). Wakes Hermes for intelligent
# triage, then consults Timmy for feedback before finalizing.
#
# Output: updated .loop/queue.json, refined issues, retro entry
# ───────────────────────────────────────────────────────────────────────

set -uo pipefail

REPO="$HOME/Timmy-Time-dashboard"
QUEUE="$REPO/.loop/queue.json"
RETRO="$REPO/.loop/retro/deep-triage.jsonl"
TIMMY="$REPO/.venv/bin/timmy"
PROMPT_FILE="$REPO/scripts/deep_triage_prompt.md"

export PATH="$HOME/.local/bin:$HOME/.hermes/bin:/usr/local/bin:$PATH"

mkdir -p "$(dirname "$RETRO")"

log() { echo "[deep-triage] $(date '+%H:%M:%S') $*"; }

# ── Gather context for the prompt ──────────────────────────────────────
QUEUE_CONTENTS=""
if [ -f "$QUEUE" ]; then
    QUEUE_CONTENTS=$(cat "$QUEUE")
fi

LAST_RETRO=""
if [ -f "$RETRO" ]; then
    LAST_RETRO=$(tail -1 "$RETRO" 2>/dev/null)
fi

SUMMARY=""
if [ -f "$REPO/.loop/retro/summary.json" ]; then
    SUMMARY=$(cat "$REPO/.loop/retro/summary.json")
fi

# ── Build dynamic prompt ──────────────────────────────────────────────
PROMPT=$(cat "$PROMPT_FILE")

PROMPT="$PROMPT

═══════════════════════════════════════════════════════════════════════════════
CURRENT CONTEXT (auto-injected)
═══════════════════════════════════════════════════════════════════════════════

CURRENT QUEUE (.loop/queue.json):
$QUEUE_CONTENTS

CYCLE SUMMARY (.loop/retro/summary.json):
$SUMMARY

LAST DEEP TRIAGE RETRO:
$LAST_RETRO

Do your work now."

# ── Run Hermes ─────────────────────────────────────────────────────────
log "Starting deep triage..."
RESULT=$(hermes chat --yolo -q "$PROMPT" 2>&1)
EXIT_CODE=$?

if [ $EXIT_CODE -ne 0 ]; then
    log "Deep triage failed (exit $EXIT_CODE)"
fi

log "Deep triage complete."
