#!/bin/bash
# check-ui-enforcement.sh
# Checks for orphan features (backend without UI)
# This enforces the "No Orphan Features" rule

set -o pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

cd "$PROJECT_ROOT"

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 UI ENFORCEMENT CHECK"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

ORPHANS_FOUND=0
WARNINGS=""

# ─────────────────────────────────────────────────────────────
# Check 1: API Routes without UI consumers
# ─────────────────────────────────────────────────────────────

echo "📋 Checking API routes..."

# Find API route files (Next.js style)
API_ROUTES=$(find . -path "*/api/*" -name "*.ts" -o -path "*/api/*" -name "*.tsx" 2>/dev/null | grep -v node_modules || true)

if [ -n "$API_ROUTES" ]; then
    while IFS= read -r route; do
        # Extract endpoint path from file path
        endpoint=$(echo "$route" | sed 's|.*api/||' | sed 's|/route\.\(ts\|tsx\)||' | sed 's|\.\(ts\|tsx\)||')

        # Check if any component imports or fetches this endpoint
        if [ -n "$endpoint" ]; then
            USAGE=$(grep -r "/api/$endpoint" --include="*.tsx" --include="*.ts" . 2>/dev/null | grep -v "api/" | grep -v node_modules || true)

            if [ -z "$USAGE" ]; then
                echo -e "  ${RED}⛔ Orphan API: /api/$endpoint${NC}"
                echo "     File: $route"
                echo "     No UI component calls this endpoint"
                ORPHANS_FOUND=1
            fi
        fi
    done <<< "$API_ROUTES"

    if [ $ORPHANS_FOUND -eq 0 ]; then
        echo -e "  ${GREEN}✓ All API routes have UI consumers${NC}"
    fi
else
    echo -e "  ${CYAN}○ No API routes found (or not using /api/ pattern)${NC}"
fi

echo ""

# ─────────────────────────────────────────────────────────────
# Check 2: Hooks not used by any component
# ─────────────────────────────────────────────────────────────

echo "📋 Checking custom hooks..."

# Find hook files
HOOKS=$(find . -path "*/hooks/*" -name "use*.ts" -o -path "*/hooks/*" -name "use*.tsx" 2>/dev/null | grep -v node_modules || true)

if [ -n "$HOOKS" ]; then
    while IFS= read -r hook; do
        # Extract hook name
        hook_name=$(basename "$hook" | sed 's/\.\(ts\|tsx\)//')

        # Check if hook is imported anywhere
        USAGE=$(grep -r "from.*hooks.*$hook_name\|import.*$hook_name" --include="*.tsx" --include="*.ts" . 2>/dev/null | grep -v "hooks/" | grep -v node_modules | grep -v ".test." || true)

        if [ -z "$USAGE" ]; then
            echo -e "  ${RED}⛔ Unused Hook: $hook_name${NC}"
            echo "     File: $hook"
            echo "     Not imported by any component"
            ORPHANS_FOUND=1
        fi
    done <<< "$HOOKS"

    if [ $ORPHANS_FOUND -eq 0 ]; then
        echo -e "  ${GREEN}✓ All hooks are used${NC}"
    fi
else
    echo -e "  ${CYAN}○ No custom hooks found${NC}"
fi

echo ""

# ─────────────────────────────────────────────────────────────
# Check 3: Utility functions not imported
# ─────────────────────────────────────────────────────────────

echo "📋 Checking utility functions..."

# Find utility files (excluding index and test files)
UTILS=$(find . -path "*/lib/*" -name "*.ts" -o -path "*/utils/*" -name "*.ts" 2>/dev/null | grep -v node_modules | grep -v "index.ts" | grep -v ".test." | grep -v ".spec." || true)

if [ -n "$UTILS" ]; then
    UNUSED_UTILS=0
    while IFS= read -r util; do
        # Extract file name without extension
        util_name=$(basename "$util" .ts)

        # Check if utility is imported anywhere
        USAGE=$(grep -r "from.*\(lib\|utils\).*$util_name\|import.*$util_name" --include="*.tsx" --include="*.ts" . 2>/dev/null | grep -v "lib/" | grep -v "utils/" | grep -v node_modules || true)

        if [ -z "$USAGE" ]; then
            echo -e "  ${YELLOW}⚠ Potentially unused: $util_name${NC}"
            echo "     File: $util"
            UNUSED_UTILS=1
        fi
    done <<< "$UTILS"

    if [ $UNUSED_UTILS -eq 0 ]; then
        echo -e "  ${GREEN}✓ All utilities appear to be used${NC}"
    fi
else
    echo -e "  ${CYAN}○ No utility files found${NC}"
fi

echo ""

# ─────────────────────────────────────────────────────────────
# Check 4: Pages without routes (for file-based routing)
# ─────────────────────────────────────────────────────────────

echo "📋 Checking page accessibility..."

# This is a basic check - can be expanded based on routing system
PAGES=$(find . -path "*/pages/*" -name "*.tsx" -o -path "*/app/*" -name "page.tsx" 2>/dev/null | grep -v node_modules | grep -v "_app" | grep -v "_document" | grep -v "layout" || true)

if [ -n "$PAGES" ]; then
    echo -e "  ${GREEN}✓ Found $(echo "$PAGES" | wc -l | tr -d ' ') page(s)${NC}"
    # Note: Actual route accessibility check would require analyzing router config
else
    echo -e "  ${CYAN}○ No page files found (or using different routing)${NC}"
fi

echo ""

# ─────────────────────────────────────────────────────────────
# Summary
# ─────────────────────────────────────────────────────────────

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if [ $ORPHANS_FOUND -eq 1 ]; then
    echo -e "${RED}⛔ UI ENFORCEMENT FAILED${NC}"
    echo ""
    echo "Orphan features detected. Per the workflow rules:"
    echo ""
    echo "  FEATURE IS NOT COMPLETE UNLESS:"
    echo "  ├── Backend (API/logic)     ✓"
    echo "  ├── Frontend (UI component) ✓  ← REQUIRED"
    echo "  ├── Connection (UI calls API) ✓"
    echo "  └── Access (user can reach it) ✓"
    echo ""
    echo -e "${YELLOW}Fix: Add UI components for orphan features before committing.${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    exit 1
else
    echo -e "${GREEN}✅ UI ENFORCEMENT PASSED${NC}"
    echo ""
    echo "No orphan features detected."
    echo "All backend features have corresponding UI."
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    exit 0
fi
