# -*- coding: utf-8 -*-
"""分析 v6 日志中的根因错误（非 InFailedSqlTransaction 的第一个错误）。"""
import json
from pathlib import Path

from dotenv import load_dotenv

load_dotenv(Path(__file__).resolve().parents[2] / ".env")

from _env_paths import get_output_path

raw_path = get_output_path("SYSTEM_LOG_ROOT") / "2026-02-21__etl_run_raw_v6.json"
data = json.loads(raw_path.read_text(encoding="utf-8"))

error_log = data.get("error_log", "")
lines = error_log.strip().split("\n")

# 找所有 ERROR 行
print("=== 所有 ERROR 行 ===\n")
for i, line in enumerate(lines):
    if "ERROR" in line:
        print(f"[L{i+1}] {line}")

# 找第一个非 InFailedSqlTransaction 的错误
print("\n\n=== 非级联错误（根因）===\n")
for i, line in enumerate(lines):
    if "ERROR" in line and "InFailedSqlTransaction" not in line:
        # 打印上下文
        start = max(0, i - 2)
        end = min(len(lines), i + 20)
        for j in range(start, end):
            marker = ">>>" if j == i else "   "
            print(f"{marker} [L{j+1}] {lines[j]}")
        print("---")
