#!/bin/bash
# Universal remediation hook handler with error recovery
# Location: ~/.config/mosaic/tools/qa/remediation-hook-handler.sh

set -euo pipefail

PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
REPORT_FILE="${1:-}"

# Validate input
if [ -z "$REPORT_FILE" ] || [ ! -f "$REPORT_FILE" ]; then
    echo "[ERROR] Invalid or missing report file: $REPORT_FILE" >&2
    exit 1
fi

LOG_FILE="$PROJECT_ROOT/logs/qa-automation.log"
mkdir -p "$(dirname "$LOG_FILE")"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Remediation triggered for: $REPORT_FILE" | tee -a "$LOG_FILE"

# Extract components from path and filename
BASE_NAME=$(basename "$REPORT_FILE" _remediation_needed.md)
DIR_PATH=$(dirname "$REPORT_FILE")

# Validate directory structure
if [[ ! "$DIR_PATH" =~ /pending$ ]]; then
    echo "[ERROR] Report not in pending directory: $DIR_PATH" | tee -a "$LOG_FILE"
    exit 1
fi

# Setup in-progress directory
IN_PROGRESS_DIR="${DIR_PATH/pending/in-progress}"

# Handle missing in-progress directory
if [ ! -d "$IN_PROGRESS_DIR" ]; then
    echo "[WARN] Creating missing in-progress directory: $IN_PROGRESS_DIR" | tee -a "$LOG_FILE"
    mkdir -p "$IN_PROGRESS_DIR"
    
    # Also ensure done and escalated exist
    mkdir -p "${DIR_PATH/pending/done}"
    mkdir -p "${DIR_PATH/pending/escalated}"
fi

# Move from pending to in-progress (with error handling)
if ! mv "$REPORT_FILE" "$IN_PROGRESS_DIR/" 2>/dev/null; then
    echo "[ERROR] Failed to move report to in-progress" | tee -a "$LOG_FILE"
    # Check if already in progress
    if [ -f "$IN_PROGRESS_DIR/$(basename "$REPORT_FILE")" ]; then
        echo "[WARN] Report already in progress, skipping" | tee -a "$LOG_FILE"
        exit 0
    fi
    exit 1
fi

# Create actions file
ACTIONS_FILE="${BASE_NAME}_remediation_actions.md"
ACTIONS_PATH="$IN_PROGRESS_DIR/$ACTIONS_FILE"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting remediation: $ACTIONS_PATH" | tee -a "$LOG_FILE"

# Trigger remediation agent
claude -p "Use Task tool to launch auto-remediation-agent for:
- Remediation Report: $IN_PROGRESS_DIR/$(basename "$REPORT_FILE")
- Actions File: $ACTIONS_PATH
- Max Iterations: 5
Process the report, create action plan using Sequential Thinking, research with Context7, and execute fixes systematically." 2>&1 | tee -a "$LOG_FILE"
