#!/usr/bin/env bash
# mdo pre-PR preflight.
#
# Runs the same checks as .github/workflows/ci.yml (plus release-hygiene checks
# CI cannot see) so a pull request is not the first place a failure shows up.
#
# bd preflight is not used: it is hardcoded to a Go/Nix toolchain (go test,
# golangci-lint, gofmt, go.sum, version.go, default.nix) with no repository
# configuration surface, so in this Rust project it fails checks that cannot
# apply and passes others vacuously. See mdo-k6d.
#
# Usage:
#   scripts/preflight.sh          # fast local set: rust checks, python, hygiene
#   scripts/preflight.sh --full   # adds cargo audit, cargo package, Android build
#
# Exit status is 0 only when every check passes. Skipped checks are reported
# explicitly and do not fail the run, but they are never counted as passes.

set -uo pipefail

FULL=0
for arg in "$@"; do
    case "$arg" in
        --full) FULL=1 ;;
        -h | --help)
            sed -n '2,18p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
            exit 0
            ;;
        *)
            echo "preflight: unknown argument: $arg (try --help)" >&2
            exit 2
            ;;
    esac
done

cd "$(git rev-parse --show-toplevel)" || {
    echo "preflight: not inside a git repository" >&2
    exit 2
}

passed=0
failed=0
skipped=0
failed_names=()

say_section() { printf '\n== %s ==\n' "$1"; }
have() { command -v "$1" >/dev/null 2>&1; }

record_pass() {
    printf '✓ %s\n' "$1"
    passed=$((passed + 1))
}

record_fail() {
    printf '✗ %s\n' "$1"
    failed=$((failed + 1))
    failed_names+=("$1")
}

record_skip() {
    printf '⚠ %s skipped: %s\n' "$1" "$2"
    skipped=$((skipped + 1))
}

# run_check <name> <command...>
# Streams nothing on success and the tail of the output on failure, so a green
# run stays readable.
run_check() {
    local name="$1"
    shift
    local log status
    log="$(mktemp)"
    say_section "$name"
    printf '$ %s\n\n' "$*"
    "$@" >"$log" 2>&1
    status=$?
    if [ "$status" -eq 0 ]; then
        record_pass "$name"
    else
        printf 'exit %s\n' "$status"
        tail -n 40 "$log" | sed 's/^/    /'
        record_fail "$name"
    fi
    rm -f "$log"
}

# inline_check <name> <function...>
# For checks that print their own findings. The function exits 0 (pass),
# 1 (fail), or 2 (skip).
inline_check() {
    local name="$1"
    shift
    local status=0
    say_section "$name"
    "$@" || status=$?
    case "$status" in
        0) record_pass "$name" ;;
        2) record_skip "$name" "not applicable in this repository" ;;
        *) record_fail "$name" ;;
    esac
}

# ─── Rust: mirrors the CI check job, in the same order ───────────────────
run_check "Formatting (cargo fmt --check)" cargo fmt --all -- --check
run_check "Clippy (deny warnings)" cargo clippy --all-targets --all-features -- -D warnings
run_check "Rust tests" cargo test --all-targets --all-features --locked

# ─── Python helper scripts ───────────────────────────────────────────────
if have python3; then
    run_check "Python tests (scripts)" python3 -m unittest discover -s tests -p 'test_*.py'
else
    say_section "Python tests (scripts)"
    record_skip "Python tests (scripts)" "python3 not installed"
fi

# ─── Version consistency ─────────────────────────────────────────────────
# Guards the skew behind mdo-alu: a published crate whose contents did not match
# its tag because Cargo, Android, and CHANGELOG versions were never reconciled.
# shellcheck disable=SC2329  # invoked indirectly through inline_check
check_versions() {
    local cargo_version android_version changelog_line unreleased_items

    cargo_version="$(sed -n 's/^version *= *"\(.*\)"/\1/p' Cargo.toml | head -n1)"
    android_version="$(sed -n 's/.*versionName *"\(.*\)".*/\1/p' android/app/build.gradle | head -n1)"
    changelog_line="$(grep -n "^## ${cargo_version}[[:space:]]" CHANGELOG.md | head -n1)"
    unreleased_items="$(
        awk '/^## Unreleased/{flag=1; next} /^## /{flag=0} flag && /^- /' CHANGELOG.md |
            wc -l | tr -d ' '
    )"

    printf 'Cargo.toml version:         %s\n' "${cargo_version:-<missing>}"
    printf 'Android versionName:        %s\n' "${android_version:-<missing>}"
    printf 'CHANGELOG heading:          %s\n' "${changelog_line:-<none for this version>}"
    printf 'Unreleased changelog items: %s\n\n' "$unreleased_items"

    if [ -z "$cargo_version" ]; then
        echo "FAIL: cannot read version from Cargo.toml"
        return 1
    fi
    if [ "$cargo_version" != "$android_version" ]; then
        echo "FAIL: android versionName ('${android_version}') != Cargo.toml version ('${cargo_version}')"
        echo "      Set both to the same value before tagging a release."
        return 1
    fi
    if [ -z "$changelog_line" ]; then
        echo "FAIL: CHANGELOG.md has no '## ${cargo_version}' heading."
        echo "      Add a dated heading for the current version, or fix the version."
        return 1
    fi
    if [ "$unreleased_items" -ne 0 ]; then
        echo "NOTE: ${unreleased_items} unreleased changelog item(s) exist at version ${cargo_version}."
        echo "      Fine mid-cycle. Before publishing, move them under a new version heading and"
        echo "      bump Cargo.toml, Cargo.lock, and android/app/build.gradle together; crates.io"
        echo "      versions are immutable, so a reused version number cannot be corrected."
    fi
    return 0
}
inline_check "Version consistency (Cargo, Android, CHANGELOG)" check_versions

# ─── Beads hygiene ───────────────────────────────────────────────────────
# .beads/issues.jsonl is a passive export, so a dirty copy means something
# imported or hand-edited it. .beads/interactions.jsonl is expected to stay
# dirty and must never be staged, so it is deliberately not inspected here.
# shellcheck disable=SC2329  # invoked indirectly through inline_check
check_beads() {
    if [ ! -d .beads ]; then
        echo "Beads is not initialized in this repository; nothing to check."
        return 2
    fi
    local issues_dirty
    issues_dirty="$(git status --porcelain -- .beads/issues.jsonl)"
    if [ -n "$issues_dirty" ]; then
        echo "FAIL: .beads/issues.jsonl has uncommitted changes:"
        printf '%s\n' "$issues_dirty"
        echo "      It is a passive export, not a source of truth. Do not stage or commit it."
        return 1
    fi
    echo "✓ .beads/issues.jsonl is clean"
    echo "  (.beads/interactions.jsonl is expected to stay dirty and is not checked)"
    return 0
}
inline_check "Beads hygiene (.beads/issues.jsonl)" check_beads

# ─── Full mode: release-shaped checks ────────────────────────────────────
if [ "$FULL" -eq 1 ]; then
    if have cargo-audit; then
        run_check "RustSec audit (cargo audit --deny warnings)" cargo audit --deny warnings
    else
        say_section "RustSec audit"
        record_skip "RustSec audit" "cargo-audit not installed (cargo install cargo-audit)"
    fi
    run_check "Crate package payload (cargo package --locked)" cargo package --locked
    if [ ! -x android/gradlew ]; then
        say_section "Android build and lint"
        record_skip "Android build and lint" "android/gradlew not available"
    elif ! have java; then
        say_section "Android build and lint"
        record_skip "Android build and lint" "no 'java' on PATH (set JAVA_HOME or install a JDK)"
    else
        run_check "Android build and lint" bash -c 'cd android && ./gradlew assembleDebug assembleRelease bundleRelease lintDebug lintRelease'
    fi
fi

# ─── Summary ─────────────────────────────────────────────────────────────
printf '\n== Summary ==\n'
printf '%d passed, %d failed, %d skipped\n' "$passed" "$failed" "$skipped"
if [ "$failed" -ne 0 ]; then
    printf '\nFailed checks:\n'
    printf '  - %s\n' "${failed_names[@]}"
    printf '\nFix these before opening or updating a pull request.\n'
    exit 1
fi
printf '\nNo failures. CI still runs checks this script cannot: the Windows job, the\n'
printf 'Android job, docs-site rendering, and anything needing network access.\n'
if [ "$FULL" -eq 0 ]; then
    printf 'Run with --full for cargo audit, cargo package, and the Android build.\n'
fi
exit 0
