#!/usr/bin/env bash
# pre-tag-verify.sh — Lumotia v0.1 pre-tag verification script
#
# Automates the 7-step morning-of ritual from docs/release/v0.1-checklist.md.
# Exit 0 = safe to tag.  Any failure exits immediately with a clear message.
#
# Usage:
#   ./scripts/pre-tag-verify.sh
#
# Requires: git, cargo, npm (all already required to build the project).
# No new dependencies introduced.

set -euo pipefail

# ── helpers ─────────────────────────────────────────────────────────────────

RED='\033[0;31m'
GREEN='\033[0;32m'
BOLD='\033[1m'
RESET='\033[0m'

REPO_ROOT="$(git -C "$(dirname "$0")" rev-parse --show-toplevel)"
cd "$REPO_ROOT"

pass() { printf "${GREEN}  ✓ PASS${RESET}  %s\n" "$1"; }
fail() {
  local step="$1"
  shift
  printf "\n${RED}${BOLD}✗ STEP %s FAILED: %s${RESET}\n\n" "$step" "$*" >&2
  exit 1
}

step_header() {
  printf "\n${BOLD}[%s] %s${RESET}\n" "$1" "$2"
}

# ── Step 1: clean checkout ───────────────────────────────────────────────────

step_header "1/7" "Confirming clean checkout..."

if ! git diff --quiet; then
  fail "1" "Working tree has unstaged changes. Stash or commit before tagging."
fi
if ! git diff --cached --quiet; then
  fail "1" "Working tree has staged-but-uncommitted changes. Commit or reset before tagging."
fi
pass "Working tree is clean."

# ── Step 2: three-way version sync ──────────────────────────────────────────

step_header "2/7" "Confirming version sync (Cargo.toml / package.json / tauri.conf.json)..."

# Extract [workspace.package].version from root Cargo.toml
cargo_ver=$(grep -A10 '^\[workspace\.package\]' Cargo.toml \
  | grep '^version' \
  | head -1 \
  | grep -oP '"\K[^"]+')

# Extract "version" from package.json (first occurrence, top-level field)
npm_ver=$(grep -m1 '"version"' package.json | grep -oP '"\K[0-9][^"]+')

# Extract "version" from tauri.conf.json
tauri_ver=$(grep -m1 '"version"' src-tauri/tauri.conf.json | grep -oP '"\K[0-9][^"]+')

if [[ -z "$cargo_ver" ]]; then
  fail "2" "Could not parse version from Cargo.toml [workspace.package]."
fi
if [[ -z "$npm_ver" ]]; then
  fail "2" "Could not parse version from package.json."
fi
if [[ -z "$tauri_ver" ]]; then
  fail "2" "Could not parse version from src-tauri/tauri.conf.json."
fi

if [[ "$cargo_ver" != "$npm_ver" || "$cargo_ver" != "$tauri_ver" ]]; then
  fail "2" "Version mismatch: Cargo.toml='$cargo_ver'  package.json='$npm_ver'  tauri.conf.json='$tauri_ver'. Sync all three before tagging."
fi
pass "All three version files agree: $cargo_ver"

# ── Step 3: CHANGELOG date placeholder ──────────────────────────────────────

step_header "3/7" "Confirming CHANGELOG.md has no date placeholder..."

if ! [[ -f CHANGELOG.md ]]; then
  fail "3" "CHANGELOG.md not found at repo root. Create it before tagging."
fi

# The placeholder is the literal string used in the file: "2026-MM-DD"
if grep -qE '[0-9]{4}-MM-DD' CHANGELOG.md; then
  fail "3" "CHANGELOG.md still has a 2026-MM-DD placeholder. Replace with the tag date before re-running."
fi
pass "CHANGELOG.md contains no date placeholder."

# ── Step 4: known-limitations doc has no TBD ────────────────────────────────

step_header "4/7" "Confirming docs/release/v0.1-known-limitations.md has no unresolved items..."

KL_DOC="docs/release/v0.1-known-limitations.md"
if ! [[ -f "$KL_DOC" ]]; then
  fail "4" "$KL_DOC not found. Create it (or verify the path) before tagging."
fi

if grep -qiE '\bTBD\b' "$KL_DOC"; then
  fail "4" "$KL_DOC contains 'TBD'. Resolve or document every open item before tagging."
fi
if grep -qiE 'pending decision' "$KL_DOC"; then
  fail "4" "$KL_DOC contains 'pending decision'. Resolve all such items before tagging."
fi
pass "No TBD or 'pending decision' found in $KL_DOC."

# ── Step 5: quality gates ────────────────────────────────────────────────────

step_header "5/7" "Running quality gates..."

printf "  • cargo fmt --check\n"
if ! cargo fmt --check 2>&1; then
  fail "5" "'cargo fmt --check' reports formatting issues. Run 'cargo fmt' and commit before tagging."
fi
pass "cargo fmt --check"

printf "  • cargo clippy\n"
if ! cargo clippy --workspace --all-targets -- -D warnings 2>&1; then
  fail "5" "'cargo clippy' reported warnings (treated as errors). Fix all clippy issues before tagging."
fi
pass "cargo clippy --workspace --all-targets -- -D warnings"

printf "  • cargo test\n"
if ! cargo test --workspace 2>&1; then
  fail "5" "'cargo test --workspace' had failures. All tests must pass before tagging."
fi
pass "cargo test --workspace"

printf "  • npm run check\n"
if ! npm run check 2>&1; then
  fail "5" "'npm run check' (svelte-check) reported errors. Fix all type/svelte errors before tagging."
fi
pass "npm run check"

printf "  • npm run test\n"
if ! npm run test 2>&1; then
  fail "5" "'npm run test' (vitest) had failures. All frontend tests must pass before tagging."
fi
pass "npm run test"

# ── Step 6: dogfood rebrand drill ───────────────────────────────────────────

step_header "6/7" "Running dogfood rebrand drill (sandbox mode)..."

DRILL="scripts/dogfood-rebrand-drill.sh"
if ! [[ -f "$DRILL" ]]; then
  fail "6" "$DRILL not found. Restore the script before tagging."
fi

if ! bash "$DRILL" 2>&1; then
  fail "6" "'$DRILL' reported failures. All 8/8 probes must pass before tagging."
fi
pass "dogfood-rebrand-drill.sh passed."

# ── Step 7: release build sanity check ──────────────────────────────────────

step_header "7/7" "Building lumotia crate in release mode (compilation sanity check)..."

if ! cargo build -p lumotia --release 2>&1; then
  fail "7" "'cargo build -p lumotia --release' failed. Fix compilation errors before tagging."
fi
pass "cargo build -p lumotia --release succeeded."

# ── All steps passed ─────────────────────────────────────────────────────────

printf "\n${GREEN}${BOLD}✓ ALL 7 PRE-TAG STEPS PASSED. Safe to run: git tag v0.1.0 && git push --tags${RESET}\n\n"
