# -*- coding: utf-8 -*-
"""分析 v7 日志中的根因错误。"""
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_v7.json"
data = json.loads(raw_path.read_text(encoding="utf-8"))

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

print(f"日志总行数: {len(lines)}")

# 找所有非级联 ERROR 行
print("\n=== 非级联错误（根因）===\n")
for i, line in enumerate(lines):
    if "ERROR" in line and "InFailedSqlTransaction" not in line and "unsupported operand" not in line:
        start = max(0, i - 2)
        end = min(len(lines), i + 15)
        for j in range(start, end):
            marker = ">>>" if j == i else "   "
            print(f"{marker} [L{j+1}] {lines[j]}")
        print("---")

# 找成功的任务
print("\n=== 成功任务 ===")
for line in lines:
    if "任务完成:" in line or "工具类任务执行成功" in line:
        print(f"  {line.strip()}")
