#!/bin/bash

# ================================================================================
# TypeScript Error Analyzer - Quick Stats
# ================================================================================
# Analyzes pnpm type-check output and generates statistics
# ================================================================================

echo "🔍 TypeScript Error Analyzer"
echo "============================"
echo ""

# Run type-check and capture output
echo "⏳ Running type-check (this may take 30-60 seconds)..."
OUTPUT=$(pnpm type-check 2>&1)

# Count total errors
TOTAL_ERRORS=$(echo "$OUTPUT" | grep -c "error TS" || true)

echo ""
echo "📊 Summary"
echo "----------"
echo "Total errors: $TOTAL_ERRORS"
echo ""

# Top 10 error types
echo "🔝 Top 10 Error Types:"
echo "$OUTPUT" | grep "error TS" | sed 's/^.*error //' | cut -d: -f1 | sort | uniq -c | sort -rn | head -10 | \
  awk '{printf "  %3d  %-10s\n", $1, $2}'

echo ""

# Error distribution by file
echo "📁 Files with most errors (top 10):"
echo "$OUTPUT" | grep "error TS" | sed 's/^.*\/\([^:]*\):.*/\1/' | sort | uniq -c | sort -rn | head -10 | \
  awk '{printf "  %3d  %s\n", $1, $2}'

echo ""

# Error types breakdown
echo "📋 Error Type Descriptions:"
echo ""
echo "  TS4111  Property from index signature (process.env.X)"
echo "  TS18048 Possibly undefined (index access)"
echo "  TS6133  Unused variable/parameter"
echo "  TS2532  Object possibly undefined"
echo "  TS2322  Type not assignable"
echo "  TS2345  Argument type mismatch"
echo "  TS6196  Property not used"
echo "  TS6138  Declared but never read"
echo "  TS2538  Cannot be used as index type"
echo "  TS7027  Unreachable code"

echo ""
echo "✅ Analysis complete!"
echo ""
echo "💡 Tips:"
echo "  - Run './fix-env-access.sh' to auto-fix TS4111 errors"
echo "  - Use 'pnpm type-check 2>&1 | grep TS18048' to find specific errors"
echo "  - Check TYPESCRIPT_STRICT_CHECKS.md for full documentation"
