#!/bin/bash
# Verify API Type Safety
#
# This script validates that all API code follows strict typing standards.
# No dynamic types, all explicit types, compile-time safety.

set -e

echo "🔍 Verifying API Type Safety..."
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

ERRORS=0

# Check for dynamic types
echo "1. Checking for forbidden 'dynamic' types..."
if grep -rn "\bdynamic\b" lib/api --include="*.dart" 2>/dev/null | grep -v "// " | grep -v "/// "; then
    echo -e "${RED}❌ Found forbidden 'dynamic' types${NC}"
    ERRORS=$((ERRORS + 1))
else
    echo -e "${GREEN}✅ No 'dynamic' types found${NC}"
fi
echo ""

# Check for untyped var
echo "2. Checking for untyped 'var' declarations..."
if grep -rn "\bvar\s" lib/api --include="*.dart" 2>/dev/null | grep -v "// " | grep -v "/// " | grep -v "for (var"; then
    echo -e "${YELLOW}⚠️  Found 'var' declarations (verify they have type inference)${NC}"
else
    echo -e "${GREEN}✅ No problematic 'var' declarations${NC}"
fi
echo ""

# Run static analysis
echo "3. Running static analysis..."
flutter analyze lib/api 2>&1 | tee /tmp/analyze_output.txt

if grep -q "error •" /tmp/analyze_output.txt; then
    echo -e "${RED}❌ Static analysis found errors${NC}"
    ERRORS=$((ERRORS + 1))
else
    echo -e "${GREEN}✅ Static analysis passed${NC}"
fi
echo ""

# Check for proper Serializable implementation
echo "4. Checking Serializable implementations..."
CLASSES=$(grep -rn "class.*implements Serializable" lib/api --include="*.dart" | wc -l | tr -d ' ')
echo "   Found ${CLASSES} Serializable classes"

if [ "$CLASSES" -eq 0 ]; then
    echo -e "${YELLOW}⚠️  No Serializable classes found (add queries/commands/DTOs)${NC}"
else
    echo -e "${GREEN}✅ Serializable implementations found${NC}"
fi
echo ""

# Check for Result type usage
echo "5. Checking Result<T> usage in endpoints..."
if grep -rn "Future<Result<" lib/api/endpoints --include="*.dart" 2>/dev/null; then
    echo -e "${GREEN}✅ Endpoints use Result<T> pattern${NC}"
else
    echo -e "${YELLOW}⚠️  No endpoints found or not using Result<T>${NC}"
fi
echo ""

# Summary
echo "════════════════════════════════════════"
if [ $ERRORS -eq 0 ]; then
    echo -e "${GREEN}✅ All type safety checks passed!${NC}"
    echo ""
    echo "Your API code follows strict typing standards:"
    echo "  • No dynamic types"
    echo "  • Explicit type annotations"
    echo "  • Serializable interface enforced"
    echo "  • Result<T> for error handling"
    echo ""
    exit 0
else
    echo -e "${RED}❌ Type safety verification failed with ${ERRORS} error(s)${NC}"
    echo ""
    echo "Please fix the issues above and run again."
    echo ""
    exit 1
fi
