# -*- coding: utf-8 -*-
"""轮询第六次执行结果。"""
import json
import sys
import time
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 = "d9443781-e4ac-4df6-9f87-11c45d72e5ba"
REFRESH_TOKEN = (
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
    "eyJzdWIiOiIxIiwic2l0ZV9pZCI6Mjc5MDY4NTQxNTQ0MzI2OSwidHlwZSI6InJlZnJlc2giLCJleHAiOjE3NzIyNjM0NjN9."
    "XYoda5lfxNtTSAGWoLlYhS9cA-hTK9iqK0SqUyn2KV4"
)


def refresh_token() -> str:
    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)
    t = resp.json()["access_token"]
    TOKEN_FILE.write_text(t, encoding="utf-8")
    return t


TOKEN = refresh_token()
HEADERS = {"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}

from _env_paths import get_output_path

for i in range(90):
    time.sleep(20)
    mm, ss = divmod((i + 1) * 20, 60)
    try:
        r = requests.get(f"{BASE}/api/execution/history?limit=5", headers=HEADERS, timeout=15)
        if r.status_code == 401:
            TOKEN = refresh_token()
            HEADERS["Authorization"] = f"Bearer {TOKEN}"
            continue
        if r.status_code != 200:
            continue
        target = next((h for h in r.json() if h["id"] == EXECUTION_ID), None)
        if not target:
            print(f"[{mm}m{ss}s] 等待...")
            continue
        status = target.get("status")
        dur = target.get("duration_ms")
        dur_s = f"{dur/1000:.1f}s" if dur else "—"
        if status in ("success", "failed", "cancelled"):
            print(f"🏁 status={status}, 耗时={dur_s}, exit_code={target.get('exit_code')}")
            lr = requests.get(f"{BASE}/api/execution/{EXECUTION_ID}/logs", headers=HEADERS, timeout=30)
            if lr.status_code == 200:
                ld = lr.json()
                out = get_output_path("SYSTEM_LOG_ROOT")
                (out / "2026-02-21__etl_run_raw_v6.json").write_text(
                    json.dumps(ld, ensure_ascii=False, indent=2), encoding="utf-8"
                )
                print("日志已保存")
                el = (ld.get("error_log") or "").strip().split("\n")
                print(f"--- error_log 末尾 80 行 (共 {len(el)} 行) ---")
                for line in el[-80:]:
                    print(line)
            break
        print(f"[{mm}m{ss}s] status={status}")
    except Exception as e:
        print(f"[{mm}m{ss}s] {e}")
else:
    print("超时")
