#!/usr/bin/env bash

set -uo pipefail

usage() {
  cat <<'USAGE'
Usage: bash scripts/verify_acceptance_rubric.sh <loop-id>

Runs the acceptance rubric checks and writes tracked evidence to:
  evidence/<loop-id>/

Exit behavior:
  0 => PASS
  1 => UNVERIFIED
  2 => invalid usage
USAGE
}

if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
  usage
  exit 0
fi

if [[ $# -ne 1 ]]; then
  usage >&2
  exit 2
fi

loop_id="$1"
if [[ "$loop_id" =~ [^a-zA-Z0-9._-] ]]; then
  echo "UNVERIFIED: loop-id contains invalid characters: $loop_id" >&2
  exit 1
fi

evidence_dir="evidence/${loop_id}"
summary_file="${evidence_dir}/README.md"
mkdir -p "$evidence_dir"

append_summary_entry() {
  local command_string="$1"
  local exit_code="$2"
  local log_file="$3"
  local line_count=0

  {
    echo '```text'
    echo "Command: ${command_string}"
    echo "Exit Code: ${exit_code}"
    echo 'Key Output:'

    if [[ -s "$log_file" ]]; then
      while IFS= read -r line; do
        echo "- ${line}"
        line_count=$((line_count + 1))
      done < <(
        grep -E "test result: ok|postgres integration tests require|UNVERIFIED|PASS|FAILED|error:|failures:" "$log_file" | head -n 3
      )

      if [[ "$line_count" -eq 0 ]]; then
        while IFS= read -r line; do
          echo "- ${line}"
          line_count=$((line_count + 1))
        done < <(sed -n '1,3p' "$log_file")
      fi
    fi

    while [[ "$line_count" -lt 3 ]]; do
      echo "- (no output)"
      line_count=$((line_count + 1))
    done

    echo '```'
    echo
  } >>"$summary_file"
}

is_loop_r8=0
if [[ "$loop_id" == "r8" ]]; then
  is_loop_r8=1
fi

run_check() {
  local log_file="$1"
  local command_string="$2"

  bash -lc "$command_string" >"$log_file" 2>&1
  return $?
}

failures=0

cat >"$summary_file" <<EOF
# Acceptance Verifier Evidence (${loop_id})

Generated by: \`bash scripts/verify_acceptance_rubric.sh ${loop_id}\`
Generated at (UTC): \`$(date -u +"%Y-%m-%dT%H:%M:%SZ")\`

## Command Results

EOF

workspace_log="${evidence_dir}/01-workspace.log"
workspace_cmd='cargo test --workspace -- --skip postgres'
run_check "$workspace_log" "$workspace_cmd"
workspace_ec=$?
append_summary_entry "$workspace_cmd" "$workspace_ec" "$workspace_log"
if [[ "$workspace_ec" -ne 0 ]]; then
  failures=$((failures + 1))
fi

strict_missing_log="${evidence_dir}/02-strict-missing-env.log"
strict_missing_cmd='unset YARLI_TEST_DATABASE_URL; YARLI_REQUIRE_POSTGRES_TESTS=1 cargo test -p yarli --test yarli_store_postgres_integration -- --nocapture'
run_check "$strict_missing_log" "$strict_missing_cmd"
strict_missing_ec=$?
append_summary_entry "$strict_missing_cmd" "$strict_missing_ec" "$strict_missing_log"

if [[ "$strict_missing_ec" -eq 0 ]]; then
  failures=$((failures + 1))
fi

if ! rg -q "postgres integration tests require YARLI_TEST_DATABASE_URL when YARLI_REQUIRE_POSTGRES_TESTS=1" "$strict_missing_log"; then
  failures=$((failures + 1))
fi

if [[ -z "${YARLI_TEST_DATABASE_URL:-}" ]]; then
  missing_env_log="${evidence_dir}/03-missing-positive-db-env.log"
  missing_env_cmd='test -n "${YARLI_TEST_DATABASE_URL:-}"'
  printf '%s\n' "YARLI_TEST_DATABASE_URL is required for strict positive-path checks." >"$missing_env_log"
  append_summary_entry "$missing_env_cmd" "1" "$missing_env_log"
  failures=$((failures + 1))
  strict_store_ec=1
  strict_queue_ec=1
  strict_cli_ec=1
else
  strict_store_log="${evidence_dir}/03-strict-store.log"
  strict_store_cmd='YARLI_TEST_DATABASE_URL="$YARLI_TEST_DATABASE_URL" YARLI_REQUIRE_POSTGRES_TESTS=1 cargo test -p yarli --test yarli_store_postgres_integration -- --nocapture'
  run_check "$strict_store_log" "$strict_store_cmd"
  strict_store_ec=$?
  append_summary_entry "$strict_store_cmd" "$strict_store_ec" "$strict_store_log"
  if [[ "$strict_store_ec" -ne 0 ]]; then
    failures=$((failures + 1))
  fi

  strict_queue_log="${evidence_dir}/04-strict-queue.log"
  strict_queue_cmd='YARLI_TEST_DATABASE_URL="$YARLI_TEST_DATABASE_URL" YARLI_REQUIRE_POSTGRES_TESTS=1 cargo test -p yarli --test yarli_queue_postgres_integration -- --nocapture'
  run_check "$strict_queue_log" "$strict_queue_cmd"
  strict_queue_ec=$?
  append_summary_entry "$strict_queue_cmd" "$strict_queue_ec" "$strict_queue_log"
  if [[ "$strict_queue_ec" -ne 0 ]]; then
    failures=$((failures + 1))
  fi

  strict_cli_log="${evidence_dir}/05-strict-cli.log"
  strict_cli_cmd='YARLI_TEST_DATABASE_URL="$YARLI_TEST_DATABASE_URL" YARLI_REQUIRE_POSTGRES_TESTS=1 cargo test -p yarli --test yarli_cli_postgres_integration -- --nocapture --test-threads=1'
  run_check "$strict_cli_log" "$strict_cli_cmd"
  strict_cli_ec=$?
  append_summary_entry "$strict_cli_cmd" "$strict_cli_ec" "$strict_cli_log"
  if [[ "$strict_cli_ec" -ne 0 ]]; then
    failures=$((failures + 1))
  fi

  no_skip_log="${evidence_dir}/06-no-skip-check.log"
  no_skip_cmd="rg -n \"skipping postgres integration test\" \"$strict_store_log\" \"$strict_queue_log\" \"$strict_cli_log\""
  run_check "$no_skip_log" "$no_skip_cmd"
  no_skip_ec=$?
  append_summary_entry "$no_skip_cmd" "$no_skip_ec" "$no_skip_log"
  if [[ "$no_skip_ec" -ne 1 ]]; then
    failures=$((failures + 1))
  fi

  if [[ "$is_loop_r8" -eq 1 ]]; then
    packaging_build_log="${evidence_dir}/15-packaging-build.log"
    packaging_build_cmd='cargo build --release -p yarli --bin yarli'
    run_check "$packaging_build_log" "$packaging_build_cmd"
    packaging_build_ec=$?
    append_summary_entry "$packaging_build_cmd" "$packaging_build_ec" "$packaging_build_log"
    if [[ "$packaging_build_ec" -ne 0 ]]; then
      failures=$((failures + 1))
    fi

    loop8_api_smoke_log="${evidence_dir}/16-r8-api-smoke.log"
    loop8_api_smoke_cmd='cargo test -p yarli health_endpoint_returns_ok -- --nocapture && cargo test -p yarli run_status_endpoint_replays_persisted_events -- --nocapture'
    run_check "$loop8_api_smoke_log" "$loop8_api_smoke_cmd"
    loop8_api_smoke_ec=$?
    append_summary_entry "$loop8_api_smoke_cmd" "$loop8_api_smoke_ec" "$loop8_api_smoke_log"
    if [[ "$loop8_api_smoke_ec" -ne 0 ]]; then
      failures=$((failures + 1))
    fi

    if ! rg -q "health_endpoint_returns_ok" "$loop8_api_smoke_log"; then
      failures=$((failures + 1))
    fi

    if ! rg -q "run_status_endpoint_replays_persisted_events" "$loop8_api_smoke_log"; then
      failures=$((failures + 1))
    fi

    loop8_api_deploy_smoke_log="${evidence_dir}/17-r8-loop-id-api-deploy.log"
    loop8_api_deploy_smoke_cmd='YARLI_TEST_DATABASE_URL="$YARLI_TEST_DATABASE_URL" YARLI_REQUIRE_POSTGRES_TESTS=1 cargo test -p yarli --test yarli_api_postgres_integration -- --nocapture'
    run_check "$loop8_api_deploy_smoke_log" "$loop8_api_deploy_smoke_cmd"
    loop8_api_deploy_smoke_ec=$?
    append_summary_entry "$loop8_api_deploy_smoke_cmd" "$loop8_api_deploy_smoke_ec" "$loop8_api_deploy_smoke_log"
    if [[ "$loop8_api_deploy_smoke_ec" -ne 0 ]]; then
      failures=$((failures + 1))
    fi

    if ! rg -q "test run_and_task_status_reflect_writes_from_postgres" "$loop8_api_deploy_smoke_log"; then
      failures=$((failures + 1))
    fi

    if ! rg -q "test merge_request_and_status_roundtrip_against_postgres" "$strict_cli_log"; then
      failures=$((failures + 1))
    fi

    if ! rg -q "test run_start_and_status_roundtrip_against_postgres" "$strict_cli_log"; then
      failures=$((failures + 1))
    fi
  fi
fi

governance_budget_log="${evidence_dir}/07-governance-budget.log"
governance_budget_cmd='cargo test -p yarli test_budget_exceeded -- --nocapture'
run_check "$governance_budget_log" "$governance_budget_cmd"
governance_budget_ec=$?
append_summary_entry "$governance_budget_cmd" "$governance_budget_ec" "$governance_budget_log"
if [[ "$governance_budget_ec" -ne 0 ]]; then
  failures=$((failures + 1))
fi

governance_explain_log="${evidence_dir}/08-governance-explain.log"
governance_explain_cmd='cargo test -p yarli budget_exceeded_task -- --nocapture'
run_check "$governance_explain_log" "$governance_explain_cmd"
governance_explain_ec=$?
append_summary_entry "$governance_explain_cmd" "$governance_explain_ec" "$governance_explain_log"
if [[ "$governance_explain_ec" -ne 0 ]]; then
  failures=$((failures + 1))
fi

governance_cli_log="${evidence_dir}/09-governance-cli.log"
governance_cli_cmd='cargo test -p yarli budget -- --nocapture'
run_check "$governance_cli_log" "$governance_cli_cmd"
governance_cli_ec=$?
append_summary_entry "$governance_cli_cmd" "$governance_cli_ec" "$governance_cli_log"
if [[ "$governance_cli_ec" -ne 0 ]]; then
  failures=$((failures + 1))
fi

no_agent_log="${evidence_dir}/10-no-agent-ref-check.log"
no_agent_cmd='rg -n "\.[aA]gent/" IMPLEMENTATION_PLAN.md PROMPT.md'
run_check "$no_agent_log" "$no_agent_cmd"
no_agent_ec=$?
append_summary_entry "$no_agent_cmd" "$no_agent_ec" "$no_agent_log"
if [[ "$no_agent_ec" -ne 1 ]]; then
  failures=$((failures + 1))
fi

no_tmp_log="${evidence_dir}/11-no-tmp-ref-check.log"
no_tmp_cmd="rg -n \"/tmp/\" \"${evidence_dir}\" --glob '*.md'"
run_check "$no_tmp_log" "$no_tmp_cmd"
no_tmp_ec=$?
append_summary_entry "$no_tmp_cmd" "$no_tmp_ec" "$no_tmp_log"
if [[ "$no_tmp_ec" -ne 1 ]]; then
  failures=$((failures + 1))
fi

# Loop-7: Scale-consistency verification matrix keyword coverage
matrix_log="${evidence_dir}/12-matrix-keywords.log"
matrix_cmd='rg -n "single-active-lease|duplicate terminal|restart|replay|budget" docs/CONSISTENCY_CONTRACT.md docs/ACCEPTANCE_RUBRIC.md'
run_check "$matrix_log" "$matrix_cmd"
matrix_ec=$?
append_summary_entry "$matrix_cmd" "$matrix_ec" "$matrix_log"
if [[ "$matrix_ec" -ne 0 ]]; then
  failures=$((failures + 1))
fi

# Loop-7: Postgres concurrency/replay invariant tests
if [[ -n "${YARLI_TEST_DATABASE_URL:-}" ]]; then
  concurrency_log="${evidence_dir}/13-concurrency-replay.log"
  concurrency_cmd='YARLI_TEST_DATABASE_URL="$YARLI_TEST_DATABASE_URL" YARLI_REQUIRE_POSTGRES_TESTS=1 cargo test -p yarli --test yarli_queue_postgres_integration -- --nocapture'
  run_check "$concurrency_log" "$concurrency_cmd"
  concurrency_ec=$?
  append_summary_entry "$concurrency_cmd" "$concurrency_ec" "$concurrency_log"
  if [[ "$concurrency_ec" -ne 0 ]]; then
    failures=$((failures + 1))
  fi
fi

# Loop-7: Capacity/budget stress proofs (parallel budget accounting)
budget_stress_log="${evidence_dir}/14-budget-stress.log"
budget_stress_cmd='cargo test -p yarli test_parallel_tasks_budget_accounting_consistency -- --nocapture'
run_check "$budget_stress_log" "$budget_stress_cmd"
budget_stress_ec=$?
append_summary_entry "$budget_stress_cmd" "$budget_stress_ec" "$budget_stress_log"
if [[ "$budget_stress_ec" -ne 0 ]]; then
  failures=$((failures + 1))
fi

if [[ "$failures" -eq 0 ]]; then
  decision="PASS"
  exit_code=0
else
  decision="UNVERIFIED"
  exit_code=1
fi

cat >>"$summary_file" <<EOF
## Decision

- Result: \`${decision}\`
- Failure count: \`${failures}\`

EOF

echo "$decision"
exit "$exit_code"
