#!/bin/bash
# Analyze Java class dependencies
# Usage: ./analyze-deps.sh <classes_dir>

set -e

CLASSES_DIR="${1:?Usage: analyze-deps.sh <classes_dir>}"

if [ ! -d "$CLASSES_DIR" ]; then
    echo "Error: Directory not found: $CLASSES_DIR"
    exit 1
fi

echo "=== Java Dependency Analysis ==="
echo ""

# Count class files
TOTAL=$(find "$CLASSES_DIR" -name "*.class" | wc -l)
echo "Total class files: $TOTAL"
echo ""

# Package structure
echo "=== Package Structure ==="
find "$CLASSES_DIR" -name "*.class" | \
    sed "s|$CLASSES_DIR/||" | \
    sed 's|/[^/]*\.class$||' | \
    sort -u | \
    sed 's|/|.|g'
echo ""

# Class count per package
echo "=== Classes per Package ==="
find "$CLASSES_DIR" -name "*.class" | \
    sed "s|$CLASSES_DIR/||" | \
    sed 's|/[^/]*\.class$||' | \
    sort | uniq -c | sort -rn
echo ""

# Find inner classes
echo "=== Inner Classes ==="
INNER_COUNT=$(find "$CLASSES_DIR" -name "*\$*.class" | wc -l)
echo "Inner/anonymous classes: $INNER_COUNT"
echo ""

# Extract imports from decompiled files if available
echo "=== External Dependencies (from JARs) ==="
if [ -d "$CLASSES_DIR/../lib" ]; then
    echo "JAR dependencies:"
    ls -1 "$CLASSES_DIR/../lib/"*.jar 2>/dev/null | xargs -I {} basename {} .jar
else
    echo "No lib directory found"
fi
echo ""

# Interface and abstract class analysis
echo "=== Interface Implementation Hints ==="
echo "Looking for common patterns..."
find "$CLASSES_DIR" -name "*.class" | while read f; do
    name=$(basename "$f" .class)
    # Check for common naming patterns
    case "$name" in
        *Dao|*DAO) echo "  DAO: $name" ;;
        *Service) echo "  Service: $name" ;;
        *Action) echo "  Action: $name" ;;
        *Domain) echo "  Domain: $name" ;;
        *Bean) echo "  Bean: $name" ;;
        *Impl) echo "  Implementation: $name" ;;
        *Interface) echo "  Interface: $name" ;;
        *Exception) echo "  Exception: $name" ;;
    esac
done | sort | head -50

echo ""
echo "=== Analysis Complete ==="
