#!/bin/bash
#
# Requirements Coverage Checker
# Extracts @req tags from codebase and compares with README.md
#

set -e

REQUIREMENTS_FILE="README.md"
SOURCE_DIRS="src-tauri/ src/"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  Requirements Coverage Report"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Extract requirement IDs from README.md (UR-, IR-, DR-, JA-)
echo "📊 Scanning requirements from $REQUIREMENTS_FILE..."
requirements=$(grep -E "^\| (UR|IR|DR|JA)-[0-9]+" "$REQUIREMENTS_FILE" | \
               sed -E 's/^\| ([A-Z]+-[0-9]+).*/\1/' | \
               sort -u)

total_reqs=$(echo "$requirements" | wc -l)
implemented=0
partial=0
planned=0
missing=0

echo ""
echo "Category Breakdown:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

for category in UR IR DR JA; do
    cat_count=$(echo "$requirements" | grep "^$category-" | wc -l)
    printf "%-4s %3d requirements\n" "$category:" "$cat_count"
done

echo ""
echo "Implementation Status:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

for req in $requirements; do
    # Count full implementations
    full_count=$(grep -r "@req: $req" $SOURCE_DIRS 2>/dev/null | grep -v "@req-partial" | grep -v "@req-planned" | wc -l)

    # Count partial implementations
    partial_count=$(grep -r "@req-partial: $req" $SOURCE_DIRS 2>/dev/null | wc -l)

    # Count planned
    planned_count=$(grep -r "@req-planned: $req" $SOURCE_DIRS 2>/dev/null | wc -l)

    if [ "$full_count" -gt 0 ]; then
        echo "✅ $req: $full_count implementation(s)"
        ((implemented++))
    elif [ "$partial_count" -gt 0 ]; then
        echo "🔶 $req: $partial_count partial implementation(s)"
        ((partial++))
    elif [ "$planned_count" -gt 0 ]; then
        echo "📋 $req: Planned (not yet implemented)"
        ((planned++))
    else
        echo "❌ $req: No implementation found"
        ((missing++))
    fi
done

echo ""
echo "Summary:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
printf "Total Requirements:     %3d\n" "$total_reqs"
printf "✅ Fully Implemented:   %3d (%.0f%%)\n" "$implemented" "$(echo "scale=0; $implemented * 100 / $total_reqs" | bc)"
printf "🔶 Partially Implemented: %3d (%.0f%%)\n" "$partial" "$(echo "scale=0; $partial * 100 / $total_reqs" | bc)"
printf "📋 Planned:             %3d (%.0f%%)\n" "$planned" "$(echo "scale=0; $planned * 100 / $total_reqs" | bc)"
printf "❌ Missing:             %3d (%.0f%%)\n" "$missing" "$(echo "scale=0; $missing * 100 / $total_reqs" | bc)"
echo ""

# Exit code based on missing critical requirements
if [ "$missing" -gt 0 ]; then
    echo "⚠️  Warning: $missing requirements have no implementation"
    exit 1
else
    echo "✨ All requirements have implementations!"
    exit 0
fi
