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

ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

if [[ ! -f package.json ]]; then
  echo "FEHLER: package.json fehlt." >&2
  exit 1
fi

if [[ -f pnpm-lock.yaml ]]; then
  PM="pnpm"
elif [[ -f yarn.lock ]]; then
  PM="yarn"
else
  PM="npm"
fi

has_script() {
  node -e 'const p=require("./package.json"); process.exit(p.scripts && p.scripts[process.argv[1]] ? 0 : 1)' "$1"
}

run_script() {
  local name="$1"
  if has_script "$name"; then
    echo
    echo "==> $PM run $name"
    "$PM" run "$name"
  else
    echo "SKIP: package.json enthält kein Script '$name'."
  fi
}

mode="${1:-focused}"

run_script typecheck
run_script lint

if [[ "$mode" == "full" ]]; then
  run_script test
  run_script test:unit
  run_script test:integration
  run_script test:e2e
  run_script build
  run_script portability
  run_script security
  run_script semgrep
  run_script gitleaks
else
  run_script test:unit
fi

bash scripts/qaf-v2/check-confidential-files.sh
