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

fail() {
  echo "check-release-surfaces: $*" >&2
  exit 1
}

version="$(sed -nE 's/^const Version = "([^"]+)"/\1/p' internal/engine/engine.go)"
[[ -n "$version" ]] || fail "could not read internal/engine Version"

grep -q "Homebrew-v$version-" README.md \
  || fail "README Homebrew badge is not aligned with engine version $version"
grep -q "AGENTTRACE v$version" README.md \
  || fail "README sample output is not aligned with engine version $version"
grep -q "version \"$version\"" homebrew/Formula/agenttrace.rb \
  || fail "Homebrew formula version is not aligned with engine version $version"
grep -q "agenttrace v$version" homebrew/Formula/agenttrace.rb \
  || fail "Homebrew formula test is not aligned with engine version $version"
grep -q "\"softwareVersion\": \"$version\"" site/index.html \
  || fail "site structured metadata is not aligned with engine version $version"

while IFS= read -r file; do
  [[ ! -e "$file" ]] || fail "npm wrapper files should not be tracked"
done < <(git ls-files 'npm/*')

if grep -R -Eqi "npm (wrapper|package)|npm install -g agenttrace|AGENTTRACE_RELEASE_TAG|npm/" \
  README.md CONTRIBUTING.md CHANGELOG.md docs/launch-kit.md site homebrew; then
  fail "public release surfaces must not advertise npm package support"
fi

if ! grep -q "<div class=\"meta\">v$version" site/demo-report.html &&
  ! grep -qi "static sample data" site/demo-report.html; then
  fail "site demo report must use current version metadata or clearly identify static sample data"
fi

node -e '
const fs = require("fs");
const version = process.argv[1];
const files = ["README.md", "homebrew/Formula/agenttrace.rb", "site/index.html", "site/demo-report.html"];
const pattern = /\bv?(\d+\.\d+\.\d+)\b/g;
for (const file of files) {
  const text = fs.readFileSync(file, "utf8");
  for (const match of text.matchAll(pattern)) {
    if (match[1] !== version) {
      throw new Error(`${file} contains stale version ${match[0]}, expected ${version}`);
    }
  }
}
' "$version" || fail "release surface version drift detected"
