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

PROJECT_DIR="/home/long/project/蚊子"
STATE_DIR="$PROJECT_DIR/logs/e2e-automation"
OUT_FILE="${1:-$STATE_DIR/consistency_latest.md}"

latest_report="$(ls -1t "$STATE_DIR"/report_*.md 2>/dev/null | head -n1 || true)"
latest_run="$(ls -1t "$STATE_DIR"/run_*.log 2>/dev/null | head -n1 || true)"

status="PASS"
reason=()

if [ -z "$latest_report" ] || [ ! -s "$latest_report" ]; then
  status="FAIL"
  reason+=("报告缺失或为空")
fi

if [ -z "$latest_run" ] || [ ! -s "$latest_run" ]; then
  status="FAIL"
  reason+=("runner日志缺失或为空")
fi

report_pass="UNKNOWN"
if [ -n "$latest_report" ] && [ -s "$latest_report" ]; then
  if grep -Eq '全部通过[：: ]*是|是否“全部通过”[：: ]*是|全部通过\s*\(是\)' "$latest_report"; then
    report_pass="YES"
  elif grep -Eq '全部通过[：: ]*否|是否“全部通过”[：: ]*否|全部通过\s*\(否\)' "$latest_report"; then
    report_pass="NO"
  fi
fi

runner_error="UNKNOWN"
data_contract_ok="UNKNOWN"
if [ -n "$latest_run" ] && [ -s "$latest_run" ]; then
  if grep -Eqi 'run finished but not fully passed|error:|runner appears stuck|\[watchdog\].*stuck|\bException\b|\bTraceback\b|\[DATA-CONTRACT\] FAIL' "$latest_run"; then
    runner_error="YES"
  else
    runner_error="NO"
  fi

  if grep -Eq '\[DATA-CONTRACT\] PASS' "$latest_run"; then
    data_contract_ok="YES"
  else
    data_contract_ok="NO"
  fi
fi

if [ "$report_pass" = "YES" ] && [ "$runner_error" = "YES" ]; then
  status="FAIL"
  reason+=("报告声明通过，但runner日志包含失败/异常信号")
fi

if [ "$report_pass" = "UNKNOWN" ]; then
  status="FAIL"
  reason+=("报告未给出明确通过结论（是/否）")
fi

if [ "$data_contract_ok" != "YES" ]; then
  status="FAIL"
  reason+=("缺少DATA-CONTRACT通过证据，结果可能为假绿")
fi

mkdir -p "$(dirname "$OUT_FILE")"
{
  echo "# E2E Consistency Check"
  echo
  echo "- Status: $status"
  echo "- Report: ${latest_report:-N/A}"
  echo "- Runner Log: ${latest_run:-N/A}"
  echo "- Report Pass Flag: $report_pass"
  echo "- Runner Error Signal: $runner_error"
  echo "- Data Contract Signal: $data_contract_ok"
  echo
  echo "## Reasons"
  if [ ${#reason[@]} -eq 0 ]; then
    echo "- 一致性检查通过"
  else
    for r in "${reason[@]}"; do
      echo "- $r"
    done
  fi
} > "$OUT_FILE"

if [ "$status" = "PASS" ]; then
  exit 0
else
  exit 2
fi
