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

workspace_root="$(git rev-parse --show-toplevel)"
cd "${workspace_root}"

ok=0
warn=0
fail=0

pass() {
  ok=$((ok + 1))
  printf 'PASS %s\n' "$1"
}

note() {
  warn=$((warn + 1))
  printf 'WARN %s\n' "$1"
}

bad() {
  fail=$((fail + 1))
  printf 'FAIL %s\n' "$1"
}

value_from_env() {
  local key="$1"
  local text="$2"
  printf '%s\n' "${text}" | awk -F= -v key="${key}" '$1 == key { print substr($0, length(key) + 2) }'
}

contains_line() {
  local needle="$1"
  local text="$2"
  [[ $'\n'"${text}"$'\n' == *$'\n'"${needle}"$'\n'* ]]
}

doctor_output="$(./scripts/repo-cargo --doctor 2>&1 || true)"
if contains_line "doctor=ok" "${doctor_output}"; then
  pass "repo-cargo doctor passes"
else
  bad "repo-cargo doctor failed"
  printf '%s\n' "${doctor_output}" >&2
fi

default_env="$(./scripts/repo-cargo --print-env)"
default_target="$(value_from_env CARGO_TARGET_DIR "${default_env}")"
default_home="$(value_from_env CARGO_HOME "${default_env}")"
default_rustup_toolchain="$(value_from_env RUSTUP_TOOLCHAIN "${default_env}")"
default_toolchain_bin="$(value_from_env MEERKAT_RUST_TOOLCHAIN_BIN "${default_env}")"
default_rustc="$(value_from_env RUSTC "${default_env}")"
if [[ "${default_target}" == "${workspace_root}"* || "${default_home}" == "${workspace_root}"* ]]; then
  bad "Cargo cache paths resolve inside the repository"
else
  pass "Cargo cache paths are outside the repository"
fi

lane_a_env="$(RUST_LANE_ID=doctor-a ./scripts/repo-cargo --print-env)"
lane_b_env="$(RUST_LANE_ID=doctor-b ./scripts/repo-cargo --print-env)"
lane_a_target="$(value_from_env CARGO_TARGET_DIR "${lane_a_env}")"
lane_b_target="$(value_from_env CARGO_TARGET_DIR "${lane_b_env}")"
lane_a_home="$(value_from_env CARGO_HOME "${lane_a_env}")"
lane_b_home="$(value_from_env CARGO_HOME "${lane_b_env}")"

if [[ "${lane_a_target}" != "${lane_b_target}" ]]; then
  pass "RUST_LANE_ID creates distinct target directories"
else
  bad "RUST_LANE_ID target directories collide"
fi

codex_agent_env="$(CODEX_AGENT_ID=doctor-codex-agent ./scripts/repo-cargo --print-env)"
codex_agent_lane="$(value_from_env lane_key "${codex_agent_env}")"
if [[ "${codex_agent_lane}" == "doctor-codex-agent" ]]; then
  pass "CODEX_AGENT_ID creates a distinct same-worktree Cargo lane"
else
  bad "CODEX_AGENT_ID was not used as the default Cargo lane"
fi

github_lane_env="$(GITHUB_JOB=fmt-lint GITHUB_RUN_ID=12345 GITHUB_RUN_ATTEMPT=2 ./scripts/repo-cargo --print-env)"
github_lane="$(value_from_env lane_key "${github_lane_env}")"
if [[ "${github_lane}" == "gha-12345-2-fmt-lint" ]]; then
  pass "GitHub Actions target lanes are isolated per run attempt"
else
  bad "GitHub Actions target lanes do not include the run attempt"
fi

if [[ "${lane_a_home}" == "${lane_b_home}" ]]; then
  pass "Cargo home stays shared per repository"
else
  bad "Cargo home changes across same-repo lanes"
fi

fast_profile_output="$(./scripts/repo-cargo nextest show-config version --profile fast --color never --no-pager 2>&1 || true)"
if grep -q '\[profile.fast\]' .config/nextest.toml &&
  grep -q 'default-filter' .config/nextest.toml &&
  [[ "${fast_profile_output}" != *"error:"* ]]; then
  pass "nextest fast profile is valid"
else
  bad "nextest fast profile is invalid"
fi

if grep -q '^e2e-build = ' .cargo/config.toml &&
  grep -q -- '--test e2e_build_lane' .cargo/config.toml &&
  grep -q -- '--run-ignored ignored-only' .cargo/config.toml; then
  pass "e2e-build is an explicit nextest ignored lane"
else
  bad "e2e-build is not configured as an explicit ignored nextest lane"
fi

if awk '/^test-all:/ { in_target=1; next } /^[[:alnum:]_.-]+:/ { in_target=0 } in_target && /nextest run --workspace/ { found=1 } END { exit found ? 0 : 1 }' Makefile; then
  bad "Makefile test-all runs a broad workspace nextest command"
else
  pass "Makefile test-all delegates to the filtered fast profile"
fi

raw_cargo_shell_hits="$(
  rg -n '^\s*(cargo|exec cargo)\s+(check|test|nextest|run|xtask|build|unit|int|e2e|clippy|fmt|machete)\b|\bcargo run -p xtask\b' \
    scripts specs \
    --glob '*.sh' \
    --glob '!scripts/repo-cargo' 2>/dev/null || true
)"
if [[ -n "${raw_cargo_shell_hits}" ]]; then
  bad "shell build/test entrypoints bypass scripts/repo-cargo"
  printf '%s\n' "${raw_cargo_shell_hits}" >&2
else
  pass "shell build/test entrypoints use the repo Cargo wrapper"
fi

raw_cargo_workflow_hits="$(
  rg -n 'run: cargo|^\s+cargo (check|test|nextest|run|xtask|build|unit|int|e2e|clippy|machete)\b' \
    .github/workflows 2>/dev/null || true
)"
if [[ -n "${raw_cargo_workflow_hits}" ]]; then
  bad "GitHub workflow Rust entrypoints bypass scripts/repo-cargo"
  printf '%s\n' "${raw_cargo_workflow_hits}" >&2
else
  pass "GitHub workflow Rust entrypoints use the repo Cargo wrapper"
fi

rust_channel="$(awk -F '"' '/^[[:space:]]*channel[[:space:]]*=/ { print $2; exit }' rust-toolchain.toml)"
default_rustc_release=""
if [[ -x "${default_rustc}" ]]; then
  default_rustc_verbose="$("${default_rustc}" -Vv 2>/dev/null || true)"
  default_rustc_release="$(printf '%s\n' "${default_rustc_verbose}" | awk -F ': ' '$1 == "release" { print $2; exit }')"
fi
if [[ -n "${rust_channel}" ]] &&
  [[ "${default_rustc_release}" == "${rust_channel}" ]] &&
  [[ "${default_rustc}" == "${default_home}/.repo-cargo-toolchain-bin/${rust_channel}-"*"/rustc" ]] &&
  [[ "${default_toolchain_bin}" == "${default_home}/.repo-cargo-toolchain-bin/${rust_channel}-"* ]]; then
  pass "repo-cargo resolves stable pinned Rust toolchain wrappers"
else
  bad "repo-cargo does not resolve stable pinned Rust toolchain wrappers"
fi

if [[ -n "${rust_channel}" ]] &&
  grep -Fq "dtolnay/rust-toolchain@${rust_channel}" .github/actions/setup-rust-ci/action.yml &&
  grep -Fq "dtolnay/rust-toolchain@${rust_channel}" .github/actions/setup-buildbuddy-ci/action.yml &&
  grep -Fq "uses: ./.github/actions/setup-rust-ci" .github/workflows/cargo.yml &&
  ! grep -Fq 'dtolnay/rust-toolchain@stable' .github/workflows/cargo.yml &&
  ! grep -Fq 'dtolnay/rust-toolchain@stable' .github/actions/setup-buildbuddy-ci/action.yml; then
  pass "Cargo and BuildBuddy CI install the pinned Rust toolchain"
else
  bad "Cargo or BuildBuddy CI Rust toolchain does not match rust-toolchain.toml"
fi

if [[ -n "${rust_channel}" ]] &&
  [[ "${default_rustup_toolchain}" == "${rust_channel}" ]] &&
  grep -Fq "RUSTUP_TOOLCHAIN: ${rust_channel}" .github/workflows/cargo.yml &&
  grep -Fq "RUSTUP_TOOLCHAIN: ${rust_channel}" .github/workflows/buildbuddy.yml &&
  grep -Fq "RUSTUP_TOOLCHAIN: ${rust_channel}" .github/actions/setup-buildbuddy-ci/action.yml &&
  grep -Fq "scripts/ci-pin-rust-toolchain-env" .github/actions/setup-rust-ci/action.yml &&
  grep -Fq "scripts/ci-pin-rust-toolchain-env" .github/actions/setup-buildbuddy-ci/action.yml &&
  grep -Fq "RUSTC=" scripts/ci-pin-rust-toolchain-env &&
  grep -Fq 'GITHUB_PATH' scripts/ci-pin-rust-toolchain-env; then
  pass "Cargo and BuildBuddy CI export stable pinned Rust toolchain wrappers"
else
  bad "Cargo or BuildBuddy CI can fall back to runner Rust binaries"
fi

if grep -q 'CARGO_HOME: /tmp/meerkat-cargo-home' .github/workflows/cargo.yml &&
  grep -q 'CARGO_HOME: /tmp/meerkat-cargo-home' .github/workflows/buildbuddy.yml &&
  grep -Fq '${GITHUB_JOB:-job}' scripts/ci-pin-rust-toolchain-env; then
  pass "CI and BuildBuddy workflows isolate Cargo home per GitHub job before cache restore"
else
  bad "CI or BuildBuddy workflow can share mutable Cargo home across parallel jobs"
fi

selector_selftest_output="$(./scripts/rust-selector-selftest.mjs 2>&1 || true)"
if contains_line "rust selector selftest ok" "${selector_selftest_output}"; then
  pass "Rust selector module parser selftest passes"
else
  bad "Rust selector module parser selftest failed"
  printf '%s\n' "${selector_selftest_output}" >&2
fi

agent_gate_probe="$(./scripts/agent-gate --dry-run --working-tree meerkat-runtime/src/input_ledger.rs 2>&1 || true)"
if [[ -x scripts/agent-gate ]] &&
  [[ "${agent_gate_probe}" == *"Cargo agent gate packages:"* ]] &&
  [[ "${agent_gate_probe}" == *"meerkat-runtime"* ]] &&
  [[ "${agent_gate_probe}" != *"BuildBuddy agent gate"* ]]; then
  pass "agent-gate defaults to the Cargo changed-path gate"
else
  bad "agent-gate default routing is not Cargo-first"
  printf '%s\n' "${agent_gate_probe}" >&2
fi

buildbuddy_agent_gate_probe="$(MEERKAT_BUILDBUDDY=1 ./scripts/agent-gate --dry-run --working-tree meerkat-runtime/src/input_ledger.rs 2>&1 || true)"
if [[ "${buildbuddy_agent_gate_probe}" == *"BuildBuddy agent gate paths:"* &&
  "${buildbuddy_agent_gate_probe}" == *"BuildBuddy changed gate dry-run"* ]]; then
  pass "MEERKAT_BUILDBUDDY=1 routes agent-gate to BuildBuddy"
else
  bad "MEERKAT_BUILDBUDDY=1 did not route agent-gate to BuildBuddy"
  printf '%s\n' "${buildbuddy_agent_gate_probe}" >&2
fi

exact_test_probe="$(./scripts/cargo-agent-gate --dry-run --working-tree meerkat-runtime/tests/meerkat_machine.rs 2>&1 || true)"
if [[ "${exact_test_probe}" == *"Cargo agent gate exact tests:"* &&
  "${exact_test_probe}" == *"--test meerkat_machine"* ]]; then
  pass "cargo-agent-gate narrows direct integration test edits to exact test binaries"
else
  bad "cargo-agent-gate did not select the exact integration test binary"
  printf '%s\n' "${exact_test_probe}" >&2
fi

support_test_probe="$(./scripts/cargo-agent-gate --dry-run --working-tree meerkat/tests/support/test_session_store.rs 2>&1 || true)"
if [[ "${support_test_probe}" == *"Cargo agent gate exact tests:"* &&
  "${support_test_probe}" == *"--test sdk_agentfactory"* &&
  "${support_test_probe}" == *"--test sdk_structured_output"* ]]; then
  pass "cargo-agent-gate narrows integration support edits to importing test binaries"
else
  bad "cargo-agent-gate did not select exact importing integration test binaries"
  printf '%s\n' "${support_test_probe}" >&2
fi

required_feature_test_probe="$(./scripts/cargo-agent-gate --dry-run --working-tree meerkat-cli/tests/cli_mobpack_live_smoke.rs 2>&1 || true)"
if [[ "${required_feature_test_probe}" == *"Cargo agent gate exact tests:"* &&
  "${required_feature_test_probe}" == *"--features integration-real-tests"* &&
  "${required_feature_test_probe}" == *"--test cli_mobpack_live_smoke"* ]]; then
  pass "cargo-agent-gate narrows required-feature test edits to exact test binaries"
else
  bad "cargo-agent-gate did not select exact required-feature test binaries"
  printf '%s\n' "${required_feature_test_probe}" >&2
fi

if [[ -n "$(git status --short)" ]]; then
  note "working tree has local changes; doctor did not modify them"
else
  pass "working tree is clean"
fi

printf '\nRust lane doctor: %s pass, %s warn, %s fail\n' "${ok}" "${warn}" "${fail}"
if [[ "${fail}" -gt 0 ]]; then
  exit 1
fi
