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

failures=0

pass() {
  echo "[pass] $1"
}

fail() {
  echo "[fail] $1"
  failures=$((failures + 1))
}

echo "HarmonyOS lint configuration guard"

if [[ -f "code-linter.json5" ]]; then
  if node -e "JSON.parse(require('fs').readFileSync('code-linter.json5', 'utf8'))" >/dev/null 2>&1; then
    pass "code-linter.json5 is valid JSON"
  else
    fail "code-linter.json5 is not valid JSON. Keep it parseable until a JSON5-aware CLI linter is wired."
  fi
else
  fail "code-linter.json5 is missing."
fi

required_files=(
  "AppScope/app.json5"
  "build-profile.json5"
  "entry/build-profile.json5"
  "entry/src/main/ets/core/config/AppConfig.ets"
  "entry/src/main/ets/core/designsystem/Tokens.ets"
  "entry/src/main/module.json5"
  "entry/src/main/ets/pages/Index.ets"
  "entry/src/main/ets/pages/Settings.ets"
  "entry/src/test/List.test.ets"
  "entry/src/main/resources/base/profile/main_pages.json"
  "hvigor/hvigor-config.json5"
  "oh-package.json5"
  "oh-package-lock.json5"
  "scripts/artifact-info"
  "scripts/release-build"
  "scripts/release-preflight"
  "scripts/verify-release-artifact"
  "scripts/verify-supply-chain"
  "scripts/test"
)

for path in "${required_files[@]}"; do
  if [[ -f "$path" ]]; then
    pass "$path exists"
  else
    fail "$path is missing."
  fi
done

for executable_script in scripts/artifact-info scripts/release-build scripts/release-preflight scripts/test scripts/verify-release-artifact scripts/verify-supply-chain; do
  if [[ -x "$executable_script" ]]; then
    pass "$executable_script is executable"
  else
    fail "$executable_script must be executable."
  fi
done

if grep -q '"pages/Settings"' entry/src/main/resources/base/profile/main_pages.json; then
  pass "Settings page is registered in main_pages.json"
else
  fail "pages/Settings is not registered in main_pages.json."
fi

if grep -q "class AppConfig" entry/src/main/ets/core/config/AppConfig.ets &&
   grep -q "class BiucingSpacing" entry/src/main/ets/core/designsystem/Tokens.ets; then
  pass "config and design system sources expose expected starter symbols"
else
  fail "config or design system starter symbols are missing."
fi

if grep -q "@ohos/hypium" oh-package.json5 &&
   grep -q "export default function testsuite" entry/src/test/List.test.ets; then
  pass "Hypium test dependency and starter test suite are present"
else
  fail "Hypium dependency or starter test suite is missing."
fi

placeholder_hits="$(
  find AppScope entry hvigor -type f \
    ! -path '*/build/*' \
    ! -path '*/.hvigor/*' \
    ! -path '*/.test/*' \
    -print0 \
    | xargs -0 grep -n '{{' 2>/dev/null || true
)"
if [[ -n "$placeholder_hits" ]]; then
  printf '%s\n' "$placeholder_hits"
  fail "unrendered template placeholders remain in generated project files."
else
  pass "no unrendered template placeholders found"
fi

if (( failures > 0 )); then
  echo "Lint guard found ${failures} issue(s)."
  exit 1
fi

echo "Lint guard passed."
