#!/bin/bash
# Analyze Java classes using javap (built-in)
# Usage: ./analyze-with-javap.sh <classes_dir> <output_file>

set -e

CLASSES_DIR="${1:?Usage: analyze-with-javap.sh <classes_dir> <output_file>}"
OUTPUT_FILE="${2:-analysis-report.txt}"

echo "=== Java Project Analysis Report ===" > "$OUTPUT_FILE"
echo "Generated: $(date)" >> "$OUTPUT_FILE"
echo "" >> "$OUTPUT_FILE"

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

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

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

# Analyze each class with javap
echo "=== Class Details ===" >> "$OUTPUT_FILE"
find "$CLASSES_DIR" -name "*.class" | while read class_file; do
    rel_path="${class_file#$CLASSES_DIR/}"
    echo "" >> "$OUTPUT_FILE"
    echo "--- $rel_path ---" >> "$OUTPUT_FILE"

    # Get class info
    FULL_PATH=$(realpath "$class_file")
    javap -p "$FULL_PATH" 2>/dev/null >> "$OUTPUT_FILE" || echo "  [Error reading class]" >> "$OUTPUT_FILE"
done

echo "" >> "$OUTPUT_FILE"
echo "=== Analysis Complete ===" >> "$OUTPUT_FILE"

echo "Report generated: $OUTPUT_FILE"
echo "Total classes analyzed: $TOTAL"
