import os
import subprocess
import sys

print("==> 启动服务 (后台) ...")
env = dict(os.environ)
log = open("/tmp/onlyfake-test.log", "w")
proc = subprocess.Popen(
    ["uvicorn", "app:app", "--host", "127.0.0.1", "--port", "8000"],
    stdout=log, stderr=subprocess.STDOUT, env=env,
)

try:
    import time, json, base64, urllib.request

    for _ in range(360):
        try:
            with urllib.request.urlopen("http://127.0.0.1:8000/health", timeout=3) as r:
                h = json.loads(r.read())
            if h.get("status") == "ok":
                print("==> 模型已就绪, device =", h.get("device"))
                break
        except Exception:
            pass
        time.sleep(5)
    else:
        print("==> 超时: 模型未在 30 分钟内就绪"); sys.exit(1)

    payload = json.dumps({
        "prompt": "a photo of a cat sitting on a beach, realistic",
        "num_inference_steps": 20,
        "width": 512,
        "height": 512,
    }).encode()
    req = urllib.request.Request(
        "http://127.0.0.1:8000/generate",
        data=payload, headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=600) as r:
        res = json.loads(r.read())
    img = base64.b64decode(res["images"][0])
    open("test_generated.png", "wb").write(img)
    print("==> 成功生成: test_generated.png (", len(img), "bytes )")
finally:
    proc.terminate()
