#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TARGET_DIR="${1:-$ROOT_DIR/frontend/src}"
WARN_BYTES=$((80 * 1024))
REFACTOR_BYTES=$((120 * 1024))

if [[ ! -d "$TARGET_DIR" ]]; then
  echo "Directory not found: $TARGET_DIR" >&2
  exit 1
fi

echo "Frontend size audit"
echo "Target: $TARGET_DIR"
echo "Warn threshold: ${WARN_BYTES} bytes (~80 KB)"
echo "Refactor threshold: ${REFACTOR_BYTES} bytes (~120 KB)"
echo

find "$TARGET_DIR" -type f \( -name '*.vue' -o -name '*.js' -o -name '*.ts' -o -name '*.scss' \) -printf '%s %p\n' \
  | sort -nr \
  | awk -v warn="$WARN_BYTES" -v refactor="$REFACTOR_BYTES" '
    BEGIN {
      printf "%-12s %-12s %s\n", "Size (KB)", "Status", "File";
      print "---------------------------------------------------------------";
    }
    {
      size_bytes = $1;
      size_kb = size_bytes / 1024;
      $1 = "";
      sub(/^ /, "", $0);
      status = "ok";
      if (size_bytes >= refactor) {
        status = "refactor";
      } else if (size_bytes >= warn) {
        status = "warn";
      }
      printf "%-12.1f %-12s %s\n", size_kb, status, $0;
    }
  ' \
  | sed -n '1,40p'
