#!/usr/bin/env bash
# adom-step release publisher.
# Wiki-first: bumping wiki page metadata + uploading the binary IS the
# release. GitHub repo is private, so the wiki binary is the canonical
# fetch path for users on other Adom containers.
#
# Idempotent: safe to re-run for the same version (asset upload replaces
# the file; page publish updates the existing row).

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

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 == wiki/page.json version ─────
step "0. version sanity"
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
WIKI_VERSION=$(jq -r '.version' wiki/page.json)
if [ "$VERSION" != "$WIKI_VERSION" ]; then
  fail "VERSION ($VERSION) != wiki/page.json ($WIKI_VERSION). Update wiki/page.json: { version, metadata.version, metadata.releases.adom_docker.binary_url, install_hint }"
fi
ok "VERSION + Cargo.toml + wiki/page.json all at $VERSION"

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

# ── 2. Local install ───────────────────────────────────────────────
step "2. local install"
sudo install -m 0755 "$BIN" /usr/local/bin/adom-step
rm -f "$HOME/.local/bin/adom-step"
install -m 0755 "$BIN" "$HOME/.local/bin/adom-step"
adom-step install >/dev/null
ok "installed locally + skills deployed"

# ── 3. Optional: git tag ───────────────────────────────────────────
step "3. git tag (optional)"
if git remote get-url origin >/dev/null 2>&1; then
  git add -A
  if ! git diff --cached --quiet; then
    git commit -m "release v$VERSION" || true
    ok "committed"
  else
    ok "nothing to commit"
  fi
  git tag -f "v$VERSION" 2>/dev/null || true
  if git push origin main 2>/dev/null && git push origin "v$VERSION" --force 2>/dev/null; then
    ok "pushed main + v$VERSION tag"
  else
    ok "skipped git push (no auth or offline)"
  fi
else
  ok "no git remote configured; skipping"
fi

# ── 4. Wiki page publish ───────────────────────────────────────────
step "4. adom-wiki page publish apps/adom-step"
TITLE=$(jq -r '.title' wiki/page.json)
BRIEF=$(jq -r '.brief' wiki/page.json)

build_changelog() {
  if [ -n "${CHANGELOG:-}" ]; then
    printf '%s' "$CHANGELOG"
    return
  fi
  if [ -f CHANGELOG.md ]; then
    local section
    section=$(awk -v v="v$VERSION" '
      /^## / { if (in_section) exit; if ($0 ~ "## "v"($| )") { in_section=1; next } }
      in_section { print }
    ' CHANGELOG.md | sed '/^[[:space:]]*$/d' | head -20)
    if [ -n "$section" ]; then
      printf 'v%s:\n%s' "$VERSION" "$section"
      return
    fi
  fi
  local prev_tag log_lines
  prev_tag=$(git tag --sort=-v:refname 2>/dev/null | grep -v "^v$VERSION$" | head -1)
  if [ -n "$prev_tag" ]; then
    log_lines=$(git log "$prev_tag..HEAD" --oneline --no-merges 2>/dev/null \
      | grep -viE '^\w+\s+(wip|merge|typo|fmt|fix typo)\b' \
      | sed 's/^\w\+ /- /' \
      | head -15)
  fi
  if [ -n "${log_lines:-}" ]; then
    printf 'v%s — changes since %s:\n%s' "$VERSION" "$prev_tag" "$log_lines"
    return
  fi
  printf 'release v%s — initial wiki publish' "$VERSION"
}
CHANGELOG_TEXT=$(build_changelog)
echo "── changelog ──"
printf '%s\n' "$CHANGELOG_TEXT" | head -20
echo "──────────────"

adom-wiki page publish apps/adom-step \
  --title "$TITLE" \
  --brief "$BRIEF" \
  --body-md wiki/body.md \
  --version "$VERSION" \
  --changelog "$CHANGELOG_TEXT" \
  --sample-prompt "Open a STEP file|view this .step file in adom-step" \
  --sample-prompt "Measure two faces|measure between two faces and show mm + mils + angle" \
  --sample-prompt "Isolate a part|isolate U1 in the components outline" \
  --sample-prompt "Strobe pins|strobe each detected pin / contact" \
  --sample-prompt "List pins|list all pin clusters with their centroids"
ok "wiki page published apps/adom-step v$VERSION"

# ── 5. Wiki asset upload (binary + SKILL.md) ───────────────────────
step "5. adom-wiki asset upload"
adom-wiki asset upload apps/adom-step --asset-type docker-binary --file "$BIN" \
  --caption "adom-step Linux x86_64 binary v$VERSION — Fusion 360-style STEP file viewer." \
  --changelog "binary v$VERSION"
ok "uploaded binary"
adom-wiki asset upload apps/adom-step --asset-type file --file SKILL.md \
  --caption "adom-step user-facing skill (Claude / AI usage docs)" \
  --changelog "SKILL.md v$VERSION" 2>&1 | tail -2 || true
ok "uploaded SKILL.md"

# ── 6. Push metadata (discovery_triggers, install_hint) ────────────
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-step --field metadata --body-md "$TMP_META" \
  --changelog "v$VERSION metadata bump"
rm -f "$TMP_META"
ok "metadata updated"

# ── 7. Verify wiki binary actually serves v$VERSION ───────────────
step "7. verify wiki binary --version"
BINARY_URL=$(jq -r '.metadata.releases.adom_docker.binary_url' wiki/page.json)
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; 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 binary --version ($WIKI_VER) != VERSION ($VERSION) — propagation lag, retry in 30s"
fi
ok "wiki binary at $BINARY_URL prints v$VERSION"

step "DONE — adom-step v$VERSION published"
echo "Auto-discover users will see the upgrade nag on their next claude-code session."