#!/usr/bin/env bash
# Task 1658 — standing voice-mirror capability audit across every brand.
#
# Reconciles *advertised* (voice-mirror ships as a core plugin: its PLUGIN.md
# is present in the source tree) against *installed* (the brand does not
# exclude it from the bundle AND the manifest declares the full tool set) for
# each brand under maxy-code/brands/. Platform plugins ship subtractively —
# the bundler copies all of platform/plugins/ except a brand's plugins.excluded
# list — so "installed" keys on that exclusion, matching what the manager's
# loadToolSurface enumerates at boot.
#
# Emits one line per brand:
#   [voice-mirror-audit] brand=<slug> advertised=<yes|no> installed=<yes|no>
#
# advertised=yes installed=no is the pre-1652 failure state. It must appear for
# no brand; if it does, this script exits non-zero.

set -euo pipefail

# Resolve maxy-code/ root from this script's location (platform/scripts/).
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MAXY_CODE_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
BRANDS_DIR="$MAXY_CODE_ROOT/brands"
PLUGIN_MANIFEST="$MAXY_CODE_ROOT/platform/plugins/voice-mirror/PLUGIN.md"
MIN_TOOLS=5

# Advertised is brand-independent: the manifest either ships in the tree or it
# does not. Its tool count is the installed-side gate.
advertised=no
tool_count=0
if [ -f "$PLUGIN_MANIFEST" ]; then
  advertised=yes
  # Count `- name:` list entries under `tools:`. Tolerant of the entry's leading
  # indentation (any run of whitespace) so a manifest reformat cannot zero the
  # count and false-flag installed=no; `- name:` appears only on tool entries in
  # this manifest, so a looser match cannot pull in non-tool lines.
  tool_count="$(grep -cE '^[[:space:]]+- name:' "$PLUGIN_MANIFEST" || true)"
fi

if [ ! -d "$BRANDS_DIR" ]; then
  echo "[voice-mirror-audit] ERROR brands dir missing at $BRANDS_DIR" >&2
  exit 2
fi

failures=0
for brand_dir in "$BRANDS_DIR"/*/; do
  brand="$(basename "$brand_dir")"
  brand_json="$brand_dir/brand.json"
  [ -f "$brand_json" ] || continue

  # A brand installs voice-mirror when it does not list it in plugins.excluded
  # and the shared manifest declares the full tool set.
  excluded="$(python3 -c "import json,sys; b=json.load(open(sys.argv[1])); print('yes' if 'voice-mirror' in (b.get('plugins',{}).get('excluded') or []) else 'no')" "$brand_json")"

  installed=no
  if [ "$advertised" = yes ] && [ "$excluded" = no ] && [ "$tool_count" -ge "$MIN_TOOLS" ]; then
    installed=yes
  fi

  echo "[voice-mirror-audit] brand=$brand advertised=$advertised installed=$installed"

  if [ "$advertised" = yes ] && [ "$installed" = no ]; then
    failures=$((failures + 1))
  fi
done

if [ "$failures" -gt 0 ]; then
  echo "[voice-mirror-audit] FAIL brands_advertised_but_not_installed=$failures" >&2
  exit 1
fi
