"""轮询 v9 执行结果"""
import time, requests, json, os, sys
from pathlib import Path
from dotenv import load_dotenv

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

EXEC_ID = "847822eb-e63b-46c0-929e-5d5f184a052e"
BASE = "http://localhost:8000"
TOKEN_FILE = Path(__file__).parent / ".monitor_token"

def get_token():
    return TOKEN_FILE.read_text().strip()

def poll():
    token = get_token()
    headers = {"Authorization": f"Bearer {token}"}
    for attempt in range(60):
        r = requests.get(f"{BASE}/api/execution/{EXEC_ID}", headers=headers)
        if r.status_code == 401:
            print("Token 过期，请刷新")
            sys.exit(1)
        data = r.json()
        status = data.get("status", "unknown")
        print(f"[{attempt+1}] status={status}")
        if status in ("completed", "failed", "partial"):
            print(json.dumps(data, indent=2, ensure_ascii=False))
            return data
        time.sleep(5)
    print("超时")
    return None

if __name__ == "__main__":
    poll()
