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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORKFLOW_FILE="$ROOT_DIR/.gitea/workflows/code_check.yml"

fail() {
  echo "ERROR: $*" >&2
  exit 1
}

job_block() {
  local job="$1"
  awk -v job="    ${job}:" '
    $0 == job { in_job = 1; print; next }
    in_job && /^    [a-zA-Z0-9_-]+:/ { exit }
    in_job { print }
  ' "$WORKFLOW_FILE"
}

lint_block="$(job_block lint)"
biome_block="$(job_block biome-check)"

if printf '%s\n' "$lint_block" | grep -Eq 'Biome check (adminfront|devfront|orgfront)|npx biome check'; then
  fail "lint job must not duplicate frontend Biome checks; keep them in biome-check"
fi

for app in adminfront devfront orgfront; do
  printf '%s\n' "$biome_block" | grep -Fq "Install ${app} dependencies" ||
    fail "biome-check job must install ${app} dependencies"
  printf '%s\n' "$biome_block" | grep -Fq "Biome check ${app}" ||
    fail "biome-check job must check ${app}"
done

for job in \
  adminfront-vitest-coverage \
  devfront-vitest-coverage \
  orgfront-vitest-coverage \
  adminfront-tests \
  devfront-tests \
  orgfront-tests; do
  block="$(job_block "$job")"
  printf '%s\n' "$block" | grep -Fq "            - biome-check" ||
    fail "${job} must depend on biome-check instead of duplicating/depending on lint for frontend quality gate"
done

echo "OK: Code Check runs frontend Biome only in the biome-check job"
