#!/usr/bin/env bash
set -euo pipefail

update=false
snapshot_file="api/public-api.txt"
package="posthog-rs"
toolchain="${PUBLIC_API_TOOLCHAIN:-nightly-2026-06-12}"

while [[ $# -gt 0 ]]; do
    case "$1" in
        -u|--update)
            update=true
            shift
            ;;
        -\?|-h|--help)
            cat <<'EOF'
Usage: scripts/check-public-api.sh [--update]

Checks the Rust public API snapshot at api/public-api.txt.
Use --update after intentional public API changes.
EOF
            exit
            ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1
            ;;
    esac
done

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

if ! command -v cargo-public-api >/dev/null 2>&1; then
    cat >&2 <<'EOF'
error: cargo-public-api is not installed.
Install it with:
  cargo install cargo-public-api --version 0.52.0 --locked
EOF
    exit 1
fi

if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1; then
    cat >&2 <<EOF
error: Rust toolchain '$toolchain' is not installed.
Install it with:
  rustup toolchain install $toolchain --profile minimal

Override with PUBLIC_API_TOOLCHAIN if the pinned nightly needs to be updated.
EOF
    exit 1
fi

tmp_file="$(mktemp)"
cleanup() {
    rm -f "$tmp_file"
}
trap cleanup EXIT

{
    echo '# This file is generated by `scripts/check-public-api.sh --update`.'
    echo '# Do not edit manually.'
    echo '# Public API scope: exported Rust API for the posthog-rs crate with public-facing features enabled.'
    echo '# Test-only harness features are omitted.'
    echo
    # Intentionally use simplification level 3 to keep the snapshot stable
    # and focused on externally meaningful API changes.
    cargo +"$toolchain" public-api \
        --package "$package" \
        --features capture-v1 \
        --simplified --simplified --simplified \
        --color never
} > "$tmp_file"

if $update; then
    mkdir -p "$(dirname "$snapshot_file")"
    cp "$tmp_file" "$snapshot_file"
    echo "Updated $snapshot_file"
    exit
fi

if [[ ! -f "$snapshot_file" ]]; then
    echo "Missing public API snapshot: $snapshot_file" >&2
    echo "Run scripts/check-public-api.sh --update to create it." >&2
    exit 1
fi

if diff -u "$snapshot_file" "$tmp_file"; then
    echo "Rust public API snapshot is up to date."
else
    echo "Rust public API changed. Run scripts/check-public-api.sh --update if intentional." >&2
    exit 1
fi
