#!/usr/bin/env bash
# Runs the WordPress.org Theme Check plugin on one theme, the same way the
# theme-check CI workflow does: WordPress Playground, latest WordPress, the
# plugin's master branch. Prints one "TYPE: message" line per finding.
#
# Usage, from the repo root: .claude/skills/theme-review/scripts/theme-check.sh <slug>
# Takes a minute or two. Needs Node and network access.
set -euo pipefail

SLUG="${1:?Usage: theme-check.sh <theme-slug>}"
THEME_DIR="$(pwd)/$SLUG"
[ -f "$THEME_DIR/style.css" ] || { echo "No theme at $THEME_DIR" >&2; exit 1; }

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
mkdir -p "$WORK/runner" "$WORK/out"

cat > "$WORK/runner/one.php" <<'PHP'
<?php
$slug   = $args[0];
$result = WP_CLI::runcommand(
	sprintf( 'theme-check run %s --format=json', $slug ),
	array(
		'return'     => 'all',
		'exit_error' => false,
		'launch'     => false,
	)
);
file_put_contents( '/output/result.json', $result->stdout );
PHP

cat > "$WORK/blueprint.json" <<JSON
{
  "preferredVersions": { "php": "8.3", "wp": "latest" },
  "plugins": [ "https://github.com/WordPress/theme-check/archive/refs/heads/master.zip" ],
  "steps": [ { "step": "wp-cli", "command": "wp eval-file /runner/one.php $SLUG" } ]
}
JSON

npx -y @wp-playground/cli@latest run-blueprint \
  --blueprint="$WORK/blueprint.json" \
  --mount="$WORK/runner:/runner" \
  --mount="$WORK/out:/output" \
  --mount="$THEME_DIR:/wordpress/wp-content/themes/$SLUG" >/dev/null 2>&1 || true

if [ ! -s "$WORK/out/result.json" ]; then
  echo "Theme Check did not run (Playground produced no result)." >&2
  exit 1
fi

python3 -c '
import json, sys
for m in json.load(open(sys.argv[1])) or []:
    print("%s: %s" % (m.get("type"), m.get("value")))
' "$WORK/out/result.json"
