"""轮询 v10 执行结果（用 history 端点）"""
import time, requests, json, sys
from pathlib import Path
from dotenv import load_dotenv

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

EXEC_ID = "ac99405f-7e42-44da-8abd-b4a51e7d7563"
BASE = "http://localhost:8000"
TOKEN_FILE = Path(__file__).parent / ".monitor_token"

def poll():
    token = TOKEN_FILE.read_text().strip()
    headers = {"Authorization": f"Bearer {token}"}
    for attempt in range(60):
        r = requests.get(f"{BASE}/api/execution/history?limit=5", headers=headers)
        if r.status_code != 200:
            print(f"[{attempt+1}] HTTP {r.status_code}")
            time.sleep(5)
            continue
        items = r.json()
        match = next((i for i in items if i["id"] == EXEC_ID), None)
        if not match:
            print(f"[{attempt+1}] 未找到执行记录")
            time.sleep(5)
            continue
        status = match.get("status", "unknown")
        print(f"[{attempt+1}] status={status}, exit_code={match.get('exit_code')}, duration_ms={match.get('duration_ms')}")
        if status in ("success", "failed", "error"):
            return match
        time.sleep(5)
    print("超时")
    return None

if __name__ == "__main__":
    result = poll()
    if result:
        print(json.dumps(result, indent=2, ensure_ascii=False))
