#!/usr/bin/env bash
# adom-mouser release publisher.
# Syncs VERSION → Cargo.toml → git tag → gh release → wiki asset → wiki page.
# Idempotent: safe to re-run for the same version (adom-wiki upload replaces).

set -euo pipefail
cd "$(dirname "$0")"

VERSION=$(cat VERSION | tr -d '[:space:]')
if [ -z "$VERSION" ]; then
  echo "ERROR: VERSION file is empty" >&2; exit 1
fi

# ANSI only when stdout is a real terminal (adom-cli-design rule:
# no raw escapes when the AI captures stdout).
if [ -t 1 ]; then C_OK='\033[32m'; C_ERR='\033[31m'; C_STEP='\033[36m'; C_RESET='\033[0m'
else C_OK=''; C_ERR=''; C_STEP=''; C_RESET=''
fi
ok()   { printf '%sOK:%s %s\n' "$C_OK" "$C_RESET" "$1"; }
fail() { printf '%sERROR:%s %s\n' "$C_ERR" "$C_RESET" "$1" >&2; exit 1; }
step() { printf '\n%s== %s ==%s\n' "$C_STEP" "$1" "$C_RESET"; }

# ── 0. Sanity: VERSION == Cargo.toml version ───────────────────────
step "0. sanity checks"
CARGO_VERSION=$(grep -m1 '^version =' Cargo.toml | sed -E 's/version = "([^"]+)"/\1/')
if [ "$VERSION" != "$CARGO_VERSION" ]; then
  fail "VERSION ($VERSION) != Cargo.toml ($CARGO_VERSION). Run: sed -i 's/^version = .*/version = \"$VERSION\"/' Cargo.toml"
fi
ok "VERSION + Cargo.toml both at $VERSION"

# ── 1. Build + verify binary --version ─────────────────────────────
step "1. cargo build --release"
cargo build --release
BIN=target/release/adom-mouser
BIN_VER=$("$BIN" --version | awk '{print $NF}')
if [ "$BIN_VER" != "$VERSION" ]; then
  fail "binary --version ($BIN_VER) != VERSION ($VERSION)"
fi
ok "binary prints adom-mouser $VERSION"

# ── 2. Git commit + tag + push ─────────────────────────────────────
step "2. git commit + tag v$VERSION"
git add -A
if ! git diff --cached --quiet; then
  git commit -m "release v$VERSION"
  ok "committed"
else
  ok "nothing to commit"
fi
git tag -f "v$VERSION"
git push origin main
git push origin "v$VERSION" --force
ok "pushed main + v$VERSION tag"

# ── 3. GitHub Release (optional, informational) ────────────────────
step "3. gh release create v$VERSION"
if gh release view "v$VERSION" >/dev/null 2>&1; then
  gh release upload "v$VERSION" "$BIN" --clobber
  ok "updated release v$VERSION binary"
else
  gh release create "v$VERSION" "$BIN" --title "v$VERSION" --generate-notes
  ok "created release v$VERSION"
fi

# ── 4. Wiki page publish/update ────────────────────────────────────
step "4. adom-wiki page publish apps/adom-mouser"
TITLE=$(jq -r '.title' wiki/page.json)
BRIEF=$(jq -r '.brief' wiki/page.json)
adom-wiki page publish apps/adom-mouser \
  --title "$TITLE" \
  --brief "$BRIEF" \
  --body-md wiki/body.md \
  --version "$VERSION" \
  --sample-prompt "Search Mouser|find me a USB-C connector on Mouser with stock > 1000" \
  --sample-prompt "Part lookup|look up Mouser PN 511-STM32F103RBT6" \
  --sample-prompt "Open the app|open the Mouser search app in Hydrogen" \
  --sample-prompt "Compare alternatives|find cheaper alternatives to the AMS1117-3.3 on Mouser" \
  --sample-prompt "Check stock|is the ESP32-S3-WROOM-1U-N4R2 in stock at Mouser?"
ok "wiki page published at apps/adom-mouser v$VERSION"

# ── 5. Wiki asset upload (canonical install surface) ───────────────
step "5. adom-wiki asset upload (docker-binary)"
adom-wiki asset upload apps/adom-mouser --asset-type docker-binary --file "$BIN"
ok "uploaded $BIN to wiki at apps/adom-mouser"

# ── 6. Push metadata (discovery_triggers, install_hint, releases) ──
step "6. adom-wiki page edit --field metadata"
TMP_META=$(mktemp)
jq --arg v "$VERSION" '.metadata | .version = $v' wiki/page.json > "$TMP_META"
adom-wiki page edit apps/adom-mouser --field metadata --body-md "$TMP_META"
rm -f "$TMP_META"
ok "metadata updated"

# ── 7. Verify the wiki actually serves v$VERSION ───────────────────
step "7. verify wiki binary --version"
BINARY_URL=$(jq -r '.metadata.releases.adom_docker.binary_url' wiki/page.json)
if [ -z "$BINARY_URL" ] || [ "$BINARY_URL" = "null" ]; then
  fail "wiki page.json has no binary_url"
fi
CHECK=$(mktemp)
if ! curl -fsSL "$BINARY_URL" -o "$CHECK"; then
  rm -f "$CHECK"
  fail "wiki binary download failed at $BINARY_URL (may need a minute to propagate; re-run step 7)"
fi
chmod +x "$CHECK"
WIKI_VER=$("$CHECK" --version | awk '{print $NF}')
rm -f "$CHECK"
if [ "$WIKI_VER" != "$VERSION" ]; then
  fail "wiki serves $WIKI_VER but we just published $VERSION"
fi
ok "wiki binary returns --version adom-mouser $VERSION"

echo
echo "───────────────────────────────────────────────"
echo "  adom-mouser v$VERSION published."
echo "  Wiki: $BINARY_URL"
echo "  The service-mouser container will auto-update within 2 minutes."
echo "───────────────────────────────────────────────"
