#!/bin/bash

# QSSH Technical Debt Analyzer
# Run this script regularly to track technical debt metrics

set -e

OUTPUT_DIR="technical_debt_reports"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
REPORT_FILE="$OUTPUT_DIR/debt_analysis_$TIMESTAMP.md"

# Create reports directory if it doesn't exist
mkdir -p "$OUTPUT_DIR"

echo "# Technical Debt Analysis Report" > "$REPORT_FILE"
echo "Generated: $(date)" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Function to count occurrences
count_pattern() {
    local pattern="$1"
    local description="$2"
    local count=$(grep -r "$pattern" src/ --exclude-dir=.git 2>/dev/null | wc -l | tr -d ' ')
    echo "- $description: $count" >> "$REPORT_FILE"
    echo "$count"
}

echo "## Code Quality Metrics" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Count various debt indicators
echo "### Potential Issues" >> "$REPORT_FILE"
unwraps=$(count_pattern "\.unwrap()" "unwrap() calls (panic points)")
expects=$(count_pattern "\.expect(" "expect() calls (panic points)")
todos=$(count_pattern "TODO\|todo!" "TODO comments")
fixmes=$(count_pattern "FIXME\|fixme!" "FIXME comments")
hacks=$(count_pattern "HACK\|hack" "HACK comments")
xxx=$(count_pattern "XXX" "XXX markers")

echo "" >> "$REPORT_FILE"
echo "### Placeholder Code" >> "$REPORT_FILE"
placeholders=$(count_pattern "placeholder\|stub\|dummy" "Placeholder/stub/dummy references")
unimplemented=$(count_pattern "unimplemented!" "unimplemented! macros")
unreachable=$(count_pattern "unreachable!" "unreachable! macros")

echo "" >> "$REPORT_FILE"
echo "### Error Handling" >> "$REPORT_FILE"
generic_errors=$(grep -r "Box<dyn.*Error" src/ --exclude-dir=.git 2>/dev/null | wc -l | tr -d ' ')
echo "- Generic error types (Box<dyn Error>): $generic_errors" >> "$REPORT_FILE"
ignored_results=$(grep -r "let _" src/ --exclude-dir=.git 2>/dev/null | wc -l | tr -d ' ')
echo "- Ignored results (let _): $ignored_results" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "### Hardcoded Values" >> "$REPORT_FILE"
hardcoded_ips=$(grep -r "127\.0\.0\.1\|192\.168\|10\.0\|172\.16" src/ --exclude-dir=.git 2>/dev/null | wc -l | tr -d ' ')
echo "- Hardcoded IP addresses: $hardcoded_ips" >> "$REPORT_FILE"
hardcoded_ports=$(grep -rE ":[0-9]{4,5}[^0-9]" src/ --exclude-dir=.git 2>/dev/null | wc -l | tr -d ' ')
echo "- Hardcoded ports: $hardcoded_ports" >> "$REPORT_FILE"
localhost=$(grep -r "localhost" src/ --exclude-dir=.git 2>/dev/null | wc -l | tr -d ' ')
echo "- Localhost references: $localhost" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "### Code Complexity" >> "$REPORT_FILE"

# Count long functions (more than 50 lines)
echo "- Functions over 50 lines:" >> "$REPORT_FILE"
find src/ -name "*.rs" -exec awk '/^[[:space:]]*(pub[[:space:]]+)?(async[[:space:]]+)?fn[[:space:]]+/ {
    start = NR
    name = $0
}
/^[[:space:]]*}[[:space:]]*$/ {
    if (start && (NR - start) > 50) {
        gsub(/^[[:space:]]*/, "", name)
        print "  - " substr(name, 1, 60) " (" (NR - start) " lines)"
    }
    start = 0
}' {} \; 2>/dev/null | head -10 >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "### Documentation Coverage" >> "$REPORT_FILE"

# Count public items without docs
total_pub=$(grep -r "^pub " src/ --include="*.rs" 2>/dev/null | wc -l | tr -d ' ')
documented_pub=$(grep -B1 "^pub " src/ --include="*.rs" 2>/dev/null | grep "^///" | wc -l | tr -d ' ')
doc_percentage=$((documented_pub * 100 / (total_pub + 1)))
echo "- Public items: $total_pub" >> "$REPORT_FILE"
echo "- Documented public items: $documented_pub (~$doc_percentage%)" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "### Test Coverage" >> "$REPORT_FILE"

# Count test functions
test_count=$(grep -r "#\[test\]\|#\[tokio::test\]" src/ tests/ --include="*.rs" 2>/dev/null | wc -l | tr -d ' ')
echo "- Test functions: $test_count" >> "$REPORT_FILE"

# Count source files vs test files
src_files=$(find src/ -name "*.rs" -not -path "*/tests/*" -not -name "*test*.rs" 2>/dev/null | wc -l | tr -d ' ')
test_files=$(find src/ tests/ -name "*test*.rs" -o -path "*/tests/*" 2>/dev/null | wc -l | tr -d ' ')
echo "- Source files: $src_files" >> "$REPORT_FILE"
echo "- Test files: $test_files" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "## Risk Assessment" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Calculate risk score
risk_score=0
critical_issues=0

if [ "$unwraps" -gt 50 ]; then
    echo "⚠️ HIGH RISK: $unwraps unwrap() calls could cause production panics" >> "$REPORT_FILE"
    risk_score=$((risk_score + 30))
    critical_issues=$((critical_issues + 1))
elif [ "$unwraps" -gt 20 ]; then
    echo "⚠️ MEDIUM RISK: $unwraps unwrap() calls present" >> "$REPORT_FILE"
    risk_score=$((risk_score + 15))
fi

if [ "$todos" -gt 10 ]; then
    echo "⚠️ MEDIUM RISK: $todos TODO items indicate incomplete features" >> "$REPORT_FILE"
    risk_score=$((risk_score + 10))
fi

if [ "$doc_percentage" -lt 50 ]; then
    echo "⚠️ MEDIUM RISK: Documentation coverage is only $doc_percentage%" >> "$REPORT_FILE"
    risk_score=$((risk_score + 10))
fi

if [ "$placeholders" -gt 5 ]; then
    echo "⚠️ HIGH RISK: $placeholders placeholder implementations found" >> "$REPORT_FILE"
    risk_score=$((risk_score + 20))
    critical_issues=$((critical_issues + 1))
fi

echo "" >> "$REPORT_FILE"
echo "### Overall Risk Score: $risk_score/100" >> "$REPORT_FILE"
echo "### Critical Issues: $critical_issues" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "## Debt Trends" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

# Compare with previous report if it exists
PREVIOUS_REPORT=$(ls -t "$OUTPUT_DIR"/debt_analysis_*.md 2>/dev/null | sed -n '2p')
if [ -n "$PREVIOUS_REPORT" ]; then
    echo "Comparing with previous report: $(basename $PREVIOUS_REPORT)" >> "$REPORT_FILE"

    # Extract previous metrics
    prev_unwraps=$(grep "unwrap() calls" "$PREVIOUS_REPORT" | grep -oE '[0-9]+' | head -1)
    prev_todos=$(grep "TODO comments" "$PREVIOUS_REPORT" | grep -oE '[0-9]+' | head -1)

    if [ -n "$prev_unwraps" ]; then
        unwrap_diff=$((unwraps - prev_unwraps))
        if [ "$unwrap_diff" -gt 0 ]; then
            echo "- ⬆️ Unwraps increased by $unwrap_diff" >> "$REPORT_FILE"
        elif [ "$unwrap_diff" -lt 0 ]; then
            echo "- ⬇️ Unwraps decreased by ${unwrap_diff#-}" >> "$REPORT_FILE"
        else
            echo "- ➡️ Unwraps unchanged" >> "$REPORT_FILE"
        fi
    fi

    if [ -n "$prev_todos" ]; then
        todo_diff=$((todos - prev_todos))
        if [ "$todo_diff" -gt 0 ]; then
            echo "- ⬆️ TODOs increased by $todo_diff" >> "$REPORT_FILE"
        elif [ "$todo_diff" -lt 0 ]; then
            echo "- ⬇️ TODOs decreased by ${todo_diff#-}" >> "$REPORT_FILE"
        else
            echo "- ➡️ TODOs unchanged" >> "$REPORT_FILE"
        fi
    fi
else
    echo "No previous report found for comparison" >> "$REPORT_FILE"
fi

echo "" >> "$REPORT_FILE"
echo "## Recommendations" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"

if [ "$critical_issues" -gt 0 ]; then
    echo "### 🔴 Critical (Address Immediately)" >> "$REPORT_FILE"
    if [ "$unwraps" -gt 50 ]; then
        echo "- Replace unwrap() calls with proper error handling" >> "$REPORT_FILE"
    fi
    if [ "$placeholders" -gt 5 ]; then
        echo "- Remove or implement placeholder code" >> "$REPORT_FILE"
    fi
    echo "" >> "$REPORT_FILE"
fi

echo "### 🟡 Important (Address This Sprint)" >> "$REPORT_FILE"
if [ "$doc_percentage" -lt 70 ]; then
    echo "- Improve documentation coverage (currently $doc_percentage%)" >> "$REPORT_FILE"
fi
if [ "$generic_errors" -gt 20 ]; then
    echo "- Replace generic error types with specific ones" >> "$REPORT_FILE"
fi
echo "" >> "$REPORT_FILE"

echo "### 🟢 Nice to Have (Address When Possible)" >> "$REPORT_FILE"
echo "- Add more test coverage" >> "$REPORT_FILE"
echo "- Reduce hardcoded values" >> "$REPORT_FILE"
echo "- Refactor long functions" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "---" >> "$REPORT_FILE"
echo "Report saved to: $REPORT_FILE" >> "$REPORT_FILE"

# Also create a summary JSON for tracking
JSON_FILE="$OUTPUT_DIR/debt_metrics_$TIMESTAMP.json"
cat > "$JSON_FILE" << EOF
{
  "timestamp": "$(date -Iseconds)",
  "metrics": {
    "unwraps": $unwraps,
    "expects": $expects,
    "todos": $todos,
    "fixmes": $fixmes,
    "placeholders": $placeholders,
    "generic_errors": $generic_errors,
    "hardcoded_ips": $hardcoded_ips,
    "doc_percentage": $doc_percentage,
    "test_count": $test_count,
    "risk_score": $risk_score,
    "critical_issues": $critical_issues
  }
}
EOF

# Display summary
echo "================== Technical Debt Analysis =================="
echo "Report generated: $REPORT_FILE"
echo ""
echo "Summary:"
echo "  Critical Issues: $critical_issues"
echo "  Risk Score: $risk_score/100"
echo "  Unwraps: $unwraps"
echo "  TODOs: $todos"
echo "  Documentation: $doc_percentage%"
echo ""
if [ "$critical_issues" -gt 0 ]; then
    echo "⚠️  CRITICAL ISSUES DETECTED - Review report immediately!"
fi
echo "============================================================="

# Keep only last 30 reports
ls -t "$OUTPUT_DIR"/debt_analysis_*.md 2>/dev/null | tail -n +31 | xargs -r rm
ls -t "$OUTPUT_DIR"/debt_metrics_*.json 2>/dev/null | tail -n +31 | xargs -r rm