# -*- coding: utf-8 -*-
"""快速检查第四次执行状态。"""
import json
import sys
from pathlib import Path

import requests
from dotenv import load_dotenv

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

TOKEN_FILE = Path(__file__).parent / ".monitor_token"
BASE = "http://localhost:8000"
EXECUTION_ID = "efd4f421-ee10-4244-833f-7b2d68c3c05b"
REFRESH_TOKEN = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
    "eyJzdWIiOiIxIiwic2l0ZV9pZCI6Mjc5MDY4NTQxNTQ0MzI2OSwidHlwZSI6InJlZnJlc2giLCJleHAiOjE3NzIyNjM0NjN9."
    "XYoda5lfxNtTSAGWoLlYhS9cA-hTK9iqK0SqUyn2KV4"
)

# 刷新 token
resp = requests.post(f"{BASE}/api/auth/refresh", json={"refresh_token": REFRESH_TOKEN}, timeout=10)
if resp.status_code != 200:
    print(f"刷新失败: {resp.status_code}")
    sys.exit(1)
token = resp.json()["access_token"]
TOKEN_FILE.write_text(token, encoding="utf-8")
headers = {"Authorization": f"Bearer {token}"}

# 查询执行历史
r = requests.get(f"{BASE}/api/execution/history?limit=5", headers=headers, timeout=15)
if r.status_code != 200:
    print(f"查询失败: {r.status_code} {r.text[:200]}")
    sys.exit(1)

target = next((h for h in r.json() if h["id"] == EXECUTION_ID), None)
if not target:
    print("未找到执行记录")
    sys.exit(1)

status = target.get("status")
dur = target.get("duration_ms")
dur_s = f"{dur/1000:.1f}s" if dur else "—"
print(f"status={status}, duration={dur_s}, exit_code={target.get('exit_code')}")

if status in ("success", "failed", "cancelled"):
    # 拉取日志
    lr = requests.get(f"{BASE}/api/execution/{EXECUTION_ID}/logs", headers=headers, timeout=30)
    if lr.status_code == 200:
        ld = lr.json()
        from _env_paths import get_output_path
        out = get_output_path("SYSTEM_LOG_ROOT")
        outfile = out / "2026-02-21__etl_run_raw_v4.json"
        outfile.write_text(json.dumps(ld, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"日志已保存: {outfile}")
        # 打印 error_log 末尾
        el = (ld.get("error_log") or "").strip().split("\n")
        print(f"--- error_log 末尾 50 行 (共 {len(el)} 行) ---")
        for line in el[-50:]:
            print(line)
    else:
        print(f"日志获取失败: {lr.status_code}")
