#!/usr/bin/env bash
#MISE description="Phase 4 of 5: Post-release verification of all artifacts. Checks: git tag exists, GitHub release published (via curl API, not gh CLI), marketplace repo at correct version, hooks synced in settings.json, and hooks.json files valid in marketplace. Prints user-facing post-release steps."
set -euo pipefail

echo "═══════════════════════════════════════════════════════════"
echo "  Phase 4: VERIFY"
echo "═══════════════════════════════════════════════════════════"

VERSION=$(jq -r '.version' package.json)
CACHE_DIR="$HOME/.claude/plugins/cache/cc-skills"
SETTINGS="$HOME/.claude/settings.json"

# Check 1: Git tag exists
echo "→ Checking git tag..."
if git rev-parse "v$VERSION" &>/dev/null; then
    echo "  ✓ Tag v$VERSION exists"
else
    echo "  ✗ Tag v$VERSION not found"
fi

# Check 2: GitHub release exists (using curl to avoid gh CLI process storm risks)
echo "→ Checking GitHub release..."
RELEASE_URL="https://api.github.com/repos/terrylica/cc-skills/releases/tags/v$VERSION"
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -H "Authorization: token ${GITHUB_TOKEN:-}" "$RELEASE_URL" 2>/dev/null || echo "000")
if [[ "$HTTP_STATUS" == "200" ]]; then
    echo "  ✓ GitHub release v$VERSION exists"
elif [[ "$HTTP_STATUS" == "404" ]]; then
    echo "  ✗ GitHub release v$VERSION not found"
else
    echo "  ⚠ Could not verify GitHub release (HTTP $HTTP_STATUS)"
fi

# Check 3: Marketplace updated
echo "→ Checking marketplace repo..."
MARKETPLACE_DIR="$HOME/.claude/plugins/marketplaces/cc-skills"
if [[ -d "$MARKETPLACE_DIR/.git" ]]; then
    MARKETPLACE_VERSION=$(jq -r '.version' "$MARKETPLACE_DIR/package.json" 2>/dev/null || echo "unknown")
    if [[ "$MARKETPLACE_VERSION" == "$VERSION" ]]; then
        echo "  ✓ Marketplace at v$VERSION"
    else
        echo "  ⚠ Marketplace at v$MARKETPLACE_VERSION (run: cd $MARKETPLACE_DIR && git pull)"
    fi
else
    echo "  ⚠ Marketplace not found - users should run: claude plugin marketplace add terrylica/cc-skills"
fi

# Check 4: settings.json should have NO cc-skills marketplace-path entries
# (plugin hooks auto-load from each plugin's hooks/hooks.json — settings.json
# entries would duplicate those, firing every hook twice).
echo "→ Checking for cc-skills hook leaks in settings.json..."
HOOK_COUNT=$(jq '[.hooks.PreToolUse[]?, .hooks.PostToolUse[]?, .hooks.Stop[]?] | length' "$SETTINGS" 2>/dev/null || echo 0)
CC_SKILLS_LEAKS=$(jq '
    [.hooks // {} | to_entries[] | .value[]?.hooks[]?.command]
    | map(select(. != null and contains("marketplaces/cc-skills/plugins/")))
    | length
' "$SETTINGS" 2>/dev/null || echo 0)
if [[ "$CC_SKILLS_LEAKS" -eq 0 ]]; then
    echo "  ✓ Total user hooks: $HOOK_COUNT, zero cc-skills marketplace-path leaks"
else
    echo "  ✗ $CC_SKILLS_LEAKS cc-skills marketplace-path entr$([[ $CC_SKILLS_LEAKS -eq 1 ]] && echo y || echo ies) leaked into settings.json — run scripts/sync-hooks-to-settings.sh to prune"
fi

# Check 5: Hook files in marketplace
#
# iter-45 SC2045 fix (2026-05-20): the prior `for PLUGIN_DIR in $(ls -d ...)`
# iterated over `ls` output, which mangles plugin directory names that
# contain whitespace or special shell chars (SC2045 — "Iterating over ls
# output is fragile"). Switched to bash native glob `"$MARKETPLACE_DIR/
# plugins"/*/` which iterates safely under any name, including those with
# spaces, $, *, etc. The `[ -d ]` guard handles the empty-glob case where
# no plugin directories exist (glob expands to the literal pattern).
#
# Same iter also defends the `((HOOKS_OK+=1))` arithmetic increment
# against the iter-32/36 ((VAR+=N))-returns-new-value-as-exit-code
# gotcha. Counter-only-increments-from-0 makes this SAFE today (the new
# value never lands on 0), but the `|| true` guard preserves defensive
# consistency with the cross-marketplace iter-36 sweep and prevents
# regression if a future refactor changes the initial value.
echo "→ Verifying hook files in marketplace..."
HOOKS_OK=0
for PLUGIN_DIR in "$MARKETPLACE_DIR/plugins"/*/; do
    [ -d "$PLUGIN_DIR" ] || continue  # handle empty-glob fallback
    HOOKS_JSON="$PLUGIN_DIR/hooks/hooks.json"
    if [[ -f "$HOOKS_JSON" ]] && jq empty "$HOOKS_JSON" 2>/dev/null; then
        ((HOOKS_OK+=1)) || true  # iter-45 ((VAR+=N)) defensive consistency
    fi
done
echo "  ✓ Valid hooks.json: $HOOKS_OK plugins"

# Check 6: No legacy commands/ directories at plugin-root level in marketplace
#
# iter-44 false-positive fix (2026-05-20): the prior `find $MARKETPLACE_DIR/plugins
# -type d -name 'commands'` was unbounded-depth and matched any nested
# `commands/` directory anywhere under the marketplace tree — including
# Swift Package Manager build caches like:
#   plugins/claude-tts-companion/.build/checkouts/swift-syntax/
#     SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/commands/
# which is vendored Swift compiler source, NOT a cc-skills legacy commands
# dir. The release verifier flagged it as a migration gap on every release.
#
# Legacy cc-skills commands directories ALWAYS live at depth=2 relative to
# $MARKETPLACE_DIR/plugins — that is, as a direct child of a plugin
# directory: $MARKETPLACE_DIR/plugins/<plugin-name>/commands/. We constrain
# the find with -mindepth 2 -maxdepth 2 to look at EXACTLY that one level,
# eliminating all nested matches.
#
# Belt-and-suspenders: also -prune away the most common vendored-package
# directories (.build, node_modules, .venv, target, .git) before find
# descends into them, so future verifier extensions inheriting this scan
# don't repeat the same depth-explosion bug.
echo "→ Checking for legacy commands/ directories (plugin-root level only, excludes vendored package dirs)..."
LEGACY_PLUGIN_ROOT_COMMANDS_DIRS_COUNT=$(find "$MARKETPLACE_DIR/plugins" \
    \( -type d -name '.build' -o \
       -type d -name 'node_modules' -o \
       -type d -name '.venv' -o \
       -type d -name 'target' -o \
       -type d -name '.git' \) -prune -o \
    -mindepth 2 -maxdepth 2 -type d -name 'commands' -print 2>/dev/null \
    | wc -l | tr -d ' ')
if [[ "$LEGACY_PLUGIN_ROOT_COMMANDS_DIRS_COUNT" -eq 0 ]]; then
    echo "  ✓ No legacy plugin-root commands/ dirs (migration complete)"
else
    echo "  ✗ Found $LEGACY_PLUGIN_ROOT_COMMANDS_DIRS_COUNT legacy plugin-root commands/ dir(s) — run:"
    echo "      find \$MARKETPLACE_DIR/plugins -mindepth 2 -maxdepth 2 -type d -name commands"
fi

# Check 7: Commands synced from skills
echo "→ Verifying commands synced to ~/.claude/commands/..."
COMMANDS_DIR="$HOME/.claude/commands"
CC_SKILLS_CMDS=$(grep -rl "cc-skills-marketplace" "$COMMANDS_DIR" 2>/dev/null | wc -l | tr -d ' ')
if [[ "$CC_SKILLS_CMDS" -gt 0 ]]; then
    echo "  ✓ Commands synced: $CC_SKILLS_CMDS skill(s) in ~/.claude/commands/"
else
    echo "  ⚠ No cc-skills commands found in $COMMANDS_DIR — run sync-commands-to-settings.sh"
fi

# Check 8: Cross-validate runtime artifacts against marketplace.json
echo "→ Cross-validating runtime artifacts..."
MARKETPLACE_JSON="$MARKETPLACE_DIR/.claude-plugin/marketplace.json"
INSTALLED="$HOME/.claude/plugins/installed_plugins.json"
ERRORS=0
for PLUGIN in $(jq -r '.plugins[].name' "$MARKETPLACE_JSON"); do
    KEY="${PLUGIN}@cc-skills"
    # 8a: in installed_plugins.json?
    if [[ -f "$INSTALLED" ]]; then
        IN_INSTALLED=$(jq -r --arg k "$KEY" '.plugins[$k] // "missing"' "$INSTALLED")
        if [[ "$IN_INSTALLED" == "missing" ]]; then
            echo "  ✗ $KEY missing from installed_plugins.json"
            ((ERRORS+=1))
        fi
    fi
    # 8b: in enabledPlugins?
    IN_ENABLED=$(jq -r --arg k "$KEY" '.enabledPlugins[$k] // "missing"' "$SETTINGS")
    if [[ "$IN_ENABLED" == "missing" ]]; then
        echo "  ✗ $KEY missing from enabledPlugins in settings.json"
        ((ERRORS+=1))
    fi
    # 8c: cache dir exists?
    if [[ ! -d "$CACHE_DIR/$PLUGIN/$VERSION" ]]; then
        echo "  ✗ $KEY missing cache dir: $CACHE_DIR/$PLUGIN/$VERSION"
        ((ERRORS+=1))
    fi
done
if [[ $ERRORS -eq 0 ]]; then
    echo "  ✓ All plugins consistent across marketplace, installed, enabled, and cache"
fi

echo ""
if [[ $ERRORS -gt 0 ]]; then
    echo "═══════════════════════════════════════════════════════════"
    echo "  ✗ Release v$VERSION verification FAILED ($ERRORS error(s))"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "Fix: run 'mise run release:sync' to bootstrap missing entries"
    echo ""
    exit 1
fi
echo "═══════════════════════════════════════════════════════════"
echo "  ✓ Release v$VERSION verified"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Post-release steps for users:"
echo "  1. Update marketplace: cd ~/.claude/plugins/marketplaces/cc-skills && git pull"
echo "  2. Reinstall plugins: claude plugin install itp@cc-skills"
echo "  3. Prune marketplace-path leaks: ./scripts/sync-hooks-to-settings.sh"
echo "  4. Sync commands: ./scripts/sync-commands-to-settings.sh"
echo "  5. Restart Claude Code"
echo ""
