#!/bin/bash

# ============================================================================
# Générateur de Rapport de Bugs pour Tests MVP
# ============================================================================
# Ce script génère un rapport JSON des bugs trouvés pendant les tests
# ============================================================================

set -euo pipefail

REPORT_FILE="${1:-mvp-bug-report-$(date +%Y%m%d-%H%M%S).json}"
TIMESTAMP=$(date -Iseconds)

# Structure du rapport
cat > "$REPORT_FILE" <<EOF
{
  "report_date": "$TIMESTAMP",
  "test_suite": "MVP Integration Tests",
  "bugs": [],
  "summary": {
    "total_bugs": 0,
    "critical": 0,
    "high": 0,
    "medium": 0,
    "low": 0
  }
}
EOF

log_info() {
    echo "[INFO] $1"
}

log_success() {
    echo "[✓] $1"
}

# Fonction pour ajouter un bug au rapport
add_bug() {
    local id=$1
    local title=$2
    local description=$3
    local severity=$4
    local category=$5
    local steps=$6
    local expected=$7
    local actual=$8
    
    # Créer l'objet bug
    local bug_json=$(cat <<BUG_JSON
    {
      "id": "$id",
      "title": "$title",
      "description": "$description",
      "severity": "$severity",
      "category": "$category",
      "steps_to_reproduce": "$steps",
      "expected_behavior": "$expected",
      "actual_behavior": "$actual",
      "status": "open",
      "created_at": "$TIMESTAMP"
    }
BUG_JSON
)
    
    # Ajouter le bug au rapport (nécessite jq)
    if command -v jq &> /dev/null; then
        jq ".bugs += [$bug_json] | .summary.total_bugs += 1 | .summary.$severity += 1" "$REPORT_FILE" > "${REPORT_FILE}.tmp" && mv "${REPORT_FILE}.tmp" "$REPORT_FILE"
    else
        log_warning "jq not installed, cannot update JSON report. Bug details:"
        echo "$bug_json"
    fi
}

# Exemple d'utilisation (à adapter selon les résultats des tests)
log_info "Bug report generator initialized"
log_info "Report file: $REPORT_FILE"
log_info ""
log_info "To add bugs manually, use:"
log_info "  add_bug \"BUG-001\" \"Title\" \"Description\" \"critical\" \"auth\" \"Steps\" \"Expected\" \"Actual\""
log_info ""
log_info "Or parse test results and call add_bug() for each failure"

# Si des arguments sont fournis, créer un bug d'exemple
if [ $# -gt 1 ]; then
    add_bug "$2" "$3" "$4" "${5:-medium}" "${6:-general}" "$7" "$8" "$9"
    log_success "Bug added to report"
fi

log_info "Report saved to: $REPORT_FILE"

