#!/bin/bash

# Check if correct number of arguments are provided (now 4)
if [ "$#" -ne 4 ]; then
    echo "Usage: $0 <task_id> <command> <result_dir> <repo_path>"
    exit 1
fi

TASK_ID=$1
CMD=$2
RESULT_DIR=$3
REPO_PATH=$4
echo $TASK_ID
# Create result directory if it doesn't exist (absolute path)
mkdir -p "$RESULT_DIR"
# Use realpath on the (now-existing) result dir and a clearer filename
LOG_FILE="$(realpath "$RESULT_DIR")/${TASK_ID}-logging.html"

# Initialize HTML file with basic styling
cat <<EOF > "$LOG_FILE"
<html>
<head>
<style>
    body { font-family: monospace; background-color: #1e1e1e; color: #d4d4d4; padding: 20px; }
    .cmd { color: #569cd6; font-weight: bold; }
    .repo { color: #ce9178; }
    .output { white-space: pre-wrap; display: block; margin-top: 10px; border-left: 3px solid #666; padding-left: 10px; }
</style>
</head>
<body>
<h2>Execution Log for Task: $TASK_ID</h2>
<p class="repo">Working Directory: $REPO_PATH</p>
<p class="cmd">Executing: $CMD</p>
<hr>
<div class="output">
EOF

# 1. CD into the repo path
# 2. Execute command and capture output
# 3. PIPESTATUS[1] captures the exit code of the CMD, not the 'cd' or 'tee'
cd "$REPO_PATH" && eval "$CMD" 2>&1 | tee -a >(sed 's/$/<br>/' >> "$LOG_FILE")
EXIT_CODE=${PIPESTATUS[0]}

# Close HTML tags
echo "</div></body></html>" >> "$LOG_FILE"

# Determine PASS/FAIL
if [ $EXIT_CODE -eq 0 ]; then
    RESULT="PASS"
else
    RESULT="FAIL"
fi

EVIDENCE_URL="file://$LOG_FILE"

# Return JSON output
# ... (rest of the script remains the same)

# Return JSON output with a unique marker prefix
printf 'FINAL_JSON_OUTPUT:{"%s": ["%s", "%s"]}\n' "$TASK_ID" "$RESULT" "$EVIDENCE_URL"