name: CI

on:
  push: {}
  pull_request:
    branches: ["master"]
  workflow_dispatch: {}

env:
  NODE_OPTIONS: --dns-result-order=ipv4first

defaults:
  run:
    shell: bash

jobs:
  build-and-anchors:
    runs-on: ubuntu-latest
    container:
      image: mcr.microsoft.com/devcontainers/javascript-node:22-bookworm

    steps:
      - name: Tools sanity
        run: |
          set -euo pipefail
          git --version
          node --version
          npm --version
          npm ping --registry=https://registry.npmjs.org

      - name: Checkout (from event.json, no external actions)
        run: |
          set -euo pipefail
          EVENT_JSON="/var/run/act/workflow/event.json"
          test -f "$EVENT_JSON" || (echo "❌ Missing $EVENT_JSON" && exit 1)

          eval "$(node - <<'NODE'
          import fs from "node:fs";
          const ev = JSON.parse(fs.readFileSync("/var/run/act/workflow/event.json","utf8"));
          const repo =
            ev?.repository?.clone_url ||
            (ev?.repository?.html_url ? (ev.repository.html_url.replace(/\/$/,'') + ".git") : "");
          const sha =
            ev?.after ||
            ev?.pull_request?.head?.sha ||
            ev?.head_commit?.id ||
            ev?.sha ||
            "";
          if (!repo) { console.error("No repository.clone_url/html_url in event.json"); process.exit(1); }
          if (!sha)  { console.error("No sha/after/pull_request.head.sha in event.json"); process.exit(1); }
          console.log(`REPO_URL=${JSON.stringify(repo)}`);
          console.log(`SHA=${JSON.stringify(sha)}`);
NODE
          )"

          echo "Repo URL: $REPO_URL"
          echo "SHA:      $SHA"

          rm -rf .git
          git init
          git remote add origin "$REPO_URL"
          git fetch --depth 1 origin "$SHA"
          git checkout -q FETCH_HEAD
          git log -1 --oneline

      - name: Anchor aliases schema
        run: |
          set -euo pipefail
          node scripts/check-anchor-aliases.mjs

      - name: NPM harden
        run: |
          set -euo pipefail
          npm config set fetch-retries 5
          npm config set fetch-retry-mintimeout 20000
          npm config set fetch-retry-maxtimeout 120000
          npm config set registry https://registry.npmjs.org
          npm config get registry

      - name: Install deps
        run: |
          set -euo pipefail
          npm ci

      - name: Inline scripts syntax check
        run: |
          set -euo pipefail
          node scripts/check-inline-js.mjs

      - name: Build (includes postbuild injection + pagefind)
        run: |
          set -euo pipefail
          npm run build

      - name: Anchors contract
        run: |
          set -euo pipefail
          npm run test:anchors

      - name: Verify anchor aliases injected in dist
        run: |
          set -euo pipefail
          node scripts/verify-anchor-aliases-in-dist.mjs
