#!/usr/bin/env bash
#MISE description="Phase 5 of 5: Post-release git state validation. Resets lockfile drift (build artifact), then verifies no uncommitted changes and no unpushed commits remain. Catches release process side-effects that would otherwise accumulate as technical debt. Exits non-zero on any failure."
set -euo pipefail

echo "═══════════════════════════════════════════════════════════"
echo "  Phase 5: POSTFLIGHT"
echo "═══════════════════════════════════════════════════════════"

ERRORS=0

# Check 1: Reset lockfile drift (artifact from cargo build, uv run, npm install, etc.)
echo "→ Checking lockfile drift..."
LOCKFILE_DRIFT=$(git diff --name-only | grep -E '^(uv\.lock|package-lock\.json|Cargo\.lock|bun\.lockb|yarn\.lock|pnpm-lock\.yaml)$' || true)
if [[ -n "$LOCKFILE_DRIFT" ]]; then
    echo "  Lockfile drift detected — resetting (build artifact):"
    echo "$LOCKFILE_DRIFT" | sed 's/^/    /'
    echo "$LOCKFILE_DRIFT" | xargs git checkout --
    echo "  ✓ Lockfiles reset"
else
    echo "  ✓ No lockfile drift"
fi

# Check 2: Uncommitted changes (after lockfile reset)
echo "→ Checking working directory..."
DIRTY=$(git status --porcelain)
if [[ -n "$DIRTY" ]]; then
    echo "  ✗ Uncommitted changes detected:"
    echo "$DIRTY" | head -20 | sed 's/^/    /'
    ERRORS=$((ERRORS + 1))
else
    echo "  ✓ Working directory clean"
fi

# Check 3: Unpushed commits
echo "→ Checking for unpushed commits..."
# iter-48 SC1083 false-positive: `@{u}` is Git's UPSTREAM-BRANCH reference
# syntax (the configured upstream tracking branch). ShellCheck flags the
# `{` and `}` as literal-brace expansion problems because it doesn't know
# Git ref syntax. The expression is correct as-is: `git log @{u}..HEAD`
# means "log commits between upstream and HEAD". Disable per-line.
# shellcheck disable=SC1083
UNPUSHED=$(git log --oneline @{u}..HEAD 2>/dev/null || echo "")
if [[ -n "$UNPUSHED" ]]; then
    echo "  ✗ Unpushed commits:"
    echo "$UNPUSHED" | sed 's/^/    /'
    ERRORS=$((ERRORS + 1))
else
    echo "  ✓ All commits pushed to remote"
fi

echo ""
if [[ $ERRORS -gt 0 ]]; then
    echo "═══════════════════════════════════════════════════════════"
    echo "  ✗ Postflight FAILED ($ERRORS issue(s))"
    echo "═══════════════════════════════════════════════════════════"
    exit 1
else
    echo "═══════════════════════════════════════════════════════════"
    echo "  ✓ Postflight PASSED — clean landing"
    echo "═══════════════════════════════════════════════════════════"
fi
echo ""
