#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Z-Image Turbo (19107-zimage-turbo) webapp + async API.
Serves on 0.0.0.0:8082. Generation is queued to ComfyUI (127.0.0.1:8188) by a
single background worker. Modes:
- t2i: text-to-image, Z-Image Turbo, 8 steps, CFG 1.
- reference: native Z-Image Omni conditioning via TextEncodeZImageOmni
  (vision tokens + VAE reference latents from image1). It conditions the
  generation on the reference; it is NOT an identity lock — changing angle
  or outfit can still drift the character. Say so plainly in the UI.
Weights (Comfy-Org/Z-Image-Turbo, Apache 2.0, not gated):
- diffusion_models/z_image_turbo_int8_convrot.safetensors (INT8, chosen for the
  shared 16GB RTX 4080; BF16 would need ~15-20GB with the encoder offloaded
  and risks OOM while other cards hold VRAM)
- text_encoders/qwen_3_4b_fp8_mixed.safetensors
- vae/ae.safetensors
"""
import json
import os
import queue
import random
import re
import shutil
import subprocess
import threading
import time
import traceback
import urllib.request
import uuid

from flask import Flask, jsonify, request, send_file, send_from_directory

ROOT = os.path.dirname(os.path.abspath(__file__))
COMFY_DIR = os.path.join(ROOT, "ComfyUI")
COMFY_URL = os.environ.get("COMFY_URL", "http://127.0.0.1:8188")
COMFY_INPUT = os.path.join(ROOT, "comfy_input")
COMFY_OUTPUT = os.path.join(ROOT, "generated")
DATA_DIR = os.path.join(ROOT, "data")
JOBS_FILE = os.path.join(DATA_DIR, "jobs.json")
COMFY_LOG = os.path.join(ROOT, "logs", "comfyui.log")
WEBAPP_PORT = int(os.environ.get("WEBAPP_PORT", "8082"))
VENV_PY = "/home/agent/zimage-venv/bin/python"
if not os.path.exists(VENV_PY):
    VENV_PY = os.path.join(ROOT, "venv", "bin", "python")

MODEL_DIFF = "z_image_turbo_int8_convrot.safetensors"
MODEL_CLIP = "qwen_3_4b_fp8_mixed.safetensors"
MODEL_VAE = "ae.safetensors"
SIZES = {
    "1024x1024": (1024, 1024),
    "1024x1536": (1024, 1536),
    "1536x1024": (1536, 1024),
    "768x1024": (768, 1024),
    "1024x768": (1024, 768),
}

app = Flask(__name__, static_folder=None)

# --- OCS delivery (Jim 2026-11-01: generated outputs go via OCS) -------------
OCS_BASE = "https://ocs.dimond.top"


def upload_to_ocs(path, ocs_name):
    """Upload a finished output to OCS. Returns the OCS URL, or None on
    failure (never raises; the local download stays as fallback)."""
    for _ in range(3):
        try:
            subprocess.run(["curl", "-sS", "--fail", "--upload-file", path,
                            OCS_BASE + "/" + ocs_name],
                           timeout=900, check=True)
            return OCS_BASE + "/" + ocs_name
        except Exception:
            time.sleep(5)
    return None


JOBS = {}
JOBS_LOCK = threading.Lock()
JOB_QUEUE = queue.Queue()
WORKER_STARTED = False
SETTINGS_FILE = os.path.join(DATA_DIR, "settings.json")
OFFLOAD_STATE = {"enabled": True, "timeout_minutes": 10, "last_finish": None,
                 "models_loaded": False, "offloaded": False, "last_offload_at": None,
                 "last_offload": None, "reloaded_after_offload": False}
OFFLOAD_LOCK = threading.Lock()


def now():
    return time.time()


def load_settings():
    try:
        with open(SETTINGS_FILE, encoding="utf-8") as f:
            d = json.load(f)
        OFFLOAD_STATE["enabled"] = bool(d.get("enabled", True))
        OFFLOAD_STATE["timeout_minutes"] = max(1, int(d.get("timeout_minutes", 10)))
    except Exception:
        pass


def save_settings():
    try:
        os.makedirs(DATA_DIR, exist_ok=True)
        with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
            json.dump({"enabled": OFFLOAD_STATE["enabled"],
                       "timeout_minutes": OFFLOAD_STATE["timeout_minutes"]}, f, ensure_ascii=False)
    except Exception:
        pass


def _cgroup_ram():
    try:
        cur = int(open("/sys/fs/cgroup/memory.current").read().strip())
    except Exception:
        cur = None
    try:
        mx = open("/sys/fs/cgroup/memory.max").read().strip()
        mx = None if mx == "max" else int(mx)
    except Exception:
        mx = None
    return cur, mx


def _nvidia_total():
    try:
        out = subprocess.check_output(["nvidia-smi", "--query-gpu=memory.used,memory.total",
                                       "--format=csv,noheader,nounits"], timeout=5, text=True)
        u, t = out.strip().split(",")
        return int(u.strip()), int(t.strip())
    except Exception:
        return None, None


def _comfy_vram():
    try:
        d = comfy_get("/system_stats", timeout=3)
        dev = (d.get("devices") or [{}])[0]
        return dev.get("vram_total"), dev.get("vram_free")
    except Exception:
        return None, None


def _any_job_active():
    if JOB_QUEUE.qsize() > 0:
        return True
    with JOBS_LOCK:
        if any(j.get("status") in ("queued", "running") for j in JOBS.values()):
            return True
    try:
        q = comfy_get("/queue", timeout=3)
        if q.get("queue_running") or q.get("queue_pending"):
            return True
    except Exception:
        pass
    return False


def wait_comfy(timeout=600):
    end = now() + timeout
    while now() < end:
        if comfy_online():
            return True
        time.sleep(5)
    return False


def _restart_comfy():
    try:
        subprocess.run(["pkill", "-f", "ComfyUI/main.py"], timeout=10)
        time.sleep(3)
        cmd = [VENV_PY, "ComfyUI/main.py", "--listen", "127.0.0.1", "--port", "8188",
               "--cuda-device", "0", "--disable-pinned-memory",
               "--input-directory", COMFY_INPUT, "--output-directory", COMFY_OUTPUT]
        log = open(COMFY_LOG, "a", encoding="utf-8", errors="replace")
        subprocess.Popen(cmd, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
        return wait_comfy(300)
    except Exception:
        return False


def do_offload(manual=False):
    with OFFLOAD_LOCK:
        if not manual and _any_job_active():
            return {"ok": False, "error": "有任务在运行/排队，暂不卸载"}
        before_total, before_free = _comfy_vram()
        before_nv_used, _ = _nvidia_total()
        method = "comfy_free"
        try:
            comfy_post("/free", {"unload_models": True, "free_memory": True}, timeout=30)
        except Exception as e:
            method = "comfy_free_failed:%s" % e
        time.sleep(5)
        after_total, after_free = _comfy_vram()
        if OFFLOAD_STATE.get("models_loaded") and before_free is not None and after_free is not None and (after_free - before_free) < 1024 * 1024 * 1024:
            if _restart_comfy():
                method = "comfy_free+restart"
                time.sleep(2)
                after_total, after_free = _comfy_vram()
        after_nv_used, _ = _nvidia_total()
        OFFLOAD_STATE["offloaded"] = True
        OFFLOAD_STATE["models_loaded"] = False
        OFFLOAD_STATE["last_offload_at"] = now()
        OFFLOAD_STATE["last_offload"] = {"method": method, "before_vram_free": before_free,
            "after_vram_free": after_free, "before_nvidia_used_mib": before_nv_used,
            "after_nvidia_used_mib": after_nv_used, "manual": manual}
        return {"ok": True, **OFFLOAD_STATE["last_offload"]}


def offload_status():
    vt, vf = _comfy_vram()
    nv_used, nv_total = _nvidia_total()
    ram_cur, ram_max = _cgroup_ram()
    lf = OFFLOAD_STATE.get("last_finish")
    elapsed = (now() - lf) if lf else None
    timeout_s = OFFLOAD_STATE["timeout_minutes"] * 60
    countdown = None
    if lf and not OFFLOAD_STATE.get("offloaded"):
        countdown = max(0, int(timeout_s - elapsed))
    return {"enabled": OFFLOAD_STATE["enabled"], "timeout_minutes": OFFLOAD_STATE["timeout_minutes"],
            "models_loaded": OFFLOAD_STATE["models_loaded"], "offloaded": OFFLOAD_STATE["offloaded"],
            "last_finish": lf, "seconds_since_finish": (int(elapsed) if elapsed is not None else None),
            "countdown_seconds": countdown, "next_offload_at": (lf + timeout_s if lf else None),
            "last_offload_at": OFFLOAD_STATE.get("last_offload_at"), "last_offload": OFFLOAD_STATE.get("last_offload"),
            "vram_total": vt, "vram_free": vf, "nvidia_used_mib": nv_used, "nvidia_total_mib": nv_total,
            "container_ram_bytes": ram_cur, "container_ram_max_bytes": ram_max,
            "job_active": _any_job_active()}


def offload_watchdog():
    while True:
        time.sleep(10)
        try:
            if not OFFLOAD_STATE.get("enabled") or OFFLOAD_STATE.get("offloaded"):
                continue
            lf = OFFLOAD_STATE.get("last_finish")
            if not lf:
                continue
            if (now() - lf) >= OFFLOAD_STATE["timeout_minutes"] * 60 and not _any_job_active():
                do_offload(manual=False)
        except Exception:
            traceback.print_exc()


def ensure_offload_watchdog():
    t = threading.Thread(target=offload_watchdog, name="offload-watchdog", daemon=True)
    t.start()


def load_jobs():
    try:
        with open(JOBS_FILE, encoding="utf-8") as f:
            d = json.load(f)
        for j in d.values():
            if j.get("status") in ("queued", "running"):
                j["status"] = "error"
                j["error"] = "服务重启，任务中断"
            JOBS[j["id"]] = j
    except Exception:
        pass


def save_jobs():
    try:
        os.makedirs(DATA_DIR, exist_ok=True)
        tmp = os.path.join(DATA_DIR, "jobs.json.tmp.%s" % uuid.uuid4().hex[:8])
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(JOBS, f, ensure_ascii=False)
        for _ in range(3):
            try:
                os.replace(tmp, JOBS_FILE)
                return
            except Exception:
                time.sleep(0.5)
    except Exception:
        pass


def public_job(j):
    d = {k: v for k, v in j.items() if k not in ("output_file",)}
    if j.get("status") == "done" and j.get("output_file"):
        d["ocs_url"] = j.get("ocs_url")
        d["download_url"] = "/api/download/%s" % j["id"]
        d["image_url"] = j.get("ocs_url") or "/api/download/%s" % j["id"]
    d["elapsed_sec"] = round(now() - j["created_at"], 1) if j.get("status") == "running" else j.get("elapsed_sec")
    return d


def comfy_get(path, timeout=10):
    req = urllib.request.Request(COMFY_URL + path)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8"))


def comfy_post(path, payload, timeout=60):
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(COMFY_URL + path, data=data, headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8"))


def comfy_online():
    try:
        # / returns HTML (json parse would fail); /system_stats is JSON.
        comfy_get("/system_stats", timeout=3)
        return True
    except Exception:
        return False


def safe_name(name, default_ext=""):
    base = re.sub(r"[^A-Za-z0-9_.\-]+", "_", os.path.basename(name or "file")) or ("file" + default_ext)
    return base


def fetch_reference(url_or_name, target_dir):
    """Accept a previously uploaded comfy_input filename, or an http(s) URL.
    Returns the comfy_input filename, or None."""
    if not url_or_name:
        return None
    if url_or_name.startswith("http://") or url_or_name.startswith("https://"):
        os.makedirs(target_dir, exist_ok=True)
        name = "refurl_" + uuid.uuid4().hex[:10] + ".png"
        dst = os.path.join(target_dir, name)
        urllib.request.urlretrieve(url_or_name, dst)
        return name
    name = safe_name(url_or_name)
    if os.path.exists(os.path.join(target_dir, name)):
        return name
    return None


def resize_reference(filename, width, height):
    """Resize the reference image to exactly the requested size (Lanczos),
    so the img2img output size is predictable. Returns the new filename."""
    try:
        from PIL import Image
        src = os.path.join(COMFY_INPUT, filename)
        im = Image.open(src).convert("RGB")
        im = im.resize((width, height), Image.LANCZOS)
        out = "refresized_" + uuid.uuid4().hex[:10] + ".png"
        im.save(os.path.join(COMFY_INPUT, out))
        return out
    except Exception:
        return filename


def build_graph(job):
    # Native Z-Image graph (ComfyUI 0.43, comfy_extras.nodes_zimage):
    # - CLIPLoader type must be a member of the valid list; QWEN3_4B weights
    #   with a non-FLUX type auto-select the z_image text encoder (sd.py).
    #   "z_image" itself is NOT a valid CLIPLoader type value.
    # - Text encoding uses TextEncodeZImageOmni, not CLIPTextEncode.
    # - Reference mode is Omni conditioning (vision tokens + VAE reference
    #   latents via image1), NOT img2img: output latent is still fresh noise
    #   at the requested size, so it is reference-conditioned, not a repaint.
    w, h = job["width"], job["height"]
    g = {
        "unet": {"class_type": "UNETLoader",
                 "inputs": {"unet_name": MODEL_DIFF, "weight_dtype": "default"}},
        "clip": {"class_type": "CLIPLoader",
                 "inputs": {"clip_name": MODEL_CLIP, "type": "stable_diffusion", "device": "default"}},
        "vae": {"class_type": "VAELoader", "inputs": {"vae_name": MODEL_VAE}},
        "pos": {"class_type": "TextEncodeZImageOmni",
                "inputs": {"prompt": job["prompt"], "clip": ["clip", 0],
                           "vae": ["vae", 0], "auto_resize_images": True}},
        "neg": {"class_type": "ConditioningZeroOut",
                "inputs": {"conditioning": ["pos", 0]}},
        "sampling": {"class_type": "ModelSamplingAuraFlow",
                     "inputs": {"model": ["unet", 0], "shift": 3.0}},
        "sampler": {"class_type": "KSampler",
                    "inputs": {"model": ["sampling", 0], "positive": ["pos", 0],
                               "negative": ["neg", 0], "seed": job["seed"],
                               "steps": job["steps"], "cfg": 1.0,
                               "sampler_name": "res_multistep", "scheduler": "simple",
                               "denoise": 1.0}},
        "decode": {"class_type": "VAEDecode",
                   "inputs": {"samples": ["sampler", 0], "vae": ["vae", 0]}},
        "save": {"class_type": "SaveImage",
                 "inputs": {"images": ["decode", 0], "filename_prefix": "zimage/%s" % job["id"]}},
        "latent": {"class_type": "EmptySD3LatentImage",
                   "inputs": {"width": w, "height": h, "batch_size": 1}},
    }
    g["sampler"]["inputs"]["latent_image"] = ["latent", 0]
    if job["mode"] == "t2i":
        pass
    elif job["mode"] == "reference":
        if not job.get("reference_image"):
            raise ValueError("参考图模式需要参考图")
        g["load_image"] = {"class_type": "LoadImage",
                           "inputs": {"image": job["reference_image"]}}
        g["pos"]["inputs"]["image1"] = ["load_image", 0]
    else:
        raise ValueError("unknown mode: %s" % job["mode"])
    return g


def run_job(job):
    jid = job["id"]
    job["status"] = "running"
    job["started_at"] = now()
    save_jobs()
    try:
        with OFFLOAD_LOCK:
            if OFFLOAD_STATE.get("offloaded"):
                OFFLOAD_STATE["reloaded_after_offload"] = True
            OFFLOAD_STATE["models_loaded"] = True
            OFFLOAD_STATE["offloaded"] = False
        if not wait_comfy(300):
            raise RuntimeError("ComfyUI 未就绪（8188 无响应）")
        graph = build_graph(job)
        resp = comfy_post("/prompt", {"prompt": graph}, timeout=60)
        pid = resp.get("prompt_id")
        if not pid:
            raise RuntimeError("ComfyUI 未返回 prompt_id: %s" % resp)
        job["comfy_prompt_id"] = pid
        save_jobs()
        deadline = now() + 1800
        out_path = None
        err_msg = None
        while now() < deadline:
            try:
                hist = comfy_get("/history/%s" % pid, timeout=10)
            except Exception:
                time.sleep(5)
                continue
            entry = hist.get(pid)
            if entry:
                st = entry.get("status", {})
                if st.get("status_str") == "success" and st.get("completed"):
                    outs = entry.get("outputs", {})
                    for node_out in outs.values():
                        for img in node_out.get("images", []):
                            sub = img.get("subfolder", "")
                            cand = os.path.join(COMFY_OUTPUT, sub, img["filename"]) if sub else os.path.join(COMFY_OUTPUT, img["filename"])
                            if os.path.exists(cand) and os.path.getsize(cand) > 0:
                                out_path = cand
                    break
                if st.get("status_str") == "error":
                    msgs = st.get("messages", [])
                    err_msg = "; ".join(str(m) for m in msgs) or "ComfyUI 报错"
                    break
            time.sleep(5)
        if err_msg:
            raise RuntimeError(err_msg)
        if not out_path:
            # Fallback: scan the output subfolder for this job's prefix.
            sub = os.path.join(COMFY_OUTPUT, "zimage")
            if os.path.isdir(sub):
                hits = [os.path.join(sub, f) for f in os.listdir(sub)
                        if f.startswith(jid) and f.lower().endswith((".png", ".jpg", ".jpeg", ".webp"))]
                hits = [p for p in hits if os.path.getsize(p) > 0]
                if hits:
                    out_path = max(hits, key=os.path.getmtime)
        if not out_path:
            raise RuntimeError("ComfyUI 已完成但未找到输出图片（请查 logs/comfyui.log）")
        job["output_file"] = out_path
        job["size_bytes"] = os.path.getsize(out_path)
        ext = os.path.splitext(out_path)[1].lower() or ".png"
        job["ocs_name"] = "zimage_%s%s" % (jid, ext)
        job["ocs_url"] = upload_to_ocs(out_path, job["ocs_name"])
        job["ocs_upload"] = "ok" if job["ocs_url"] else "failed"
        job["status"] = "done"
    except Exception as e:
        job["status"] = "error"
        job["error"] = str(e)
        try:
            with open(COMFY_LOG, "r", encoding="utf-8", errors="replace") as f:
                job["log_tail"] = "".join(f.readlines()[-40:])
        except Exception:
            pass
    job["elapsed_sec"] = round(now() - job["started_at"], 1)
    with OFFLOAD_LOCK:
        OFFLOAD_STATE["last_finish"] = now()
        if job["status"] == "done":
            OFFLOAD_STATE["models_loaded"] = True
    save_jobs()


def worker_loop():
    while True:
        job = JOB_QUEUE.get()
        try:
            run_job(job)
        except Exception:
            traceback.print_exc()
            job["status"] = "error"
            job["error"] = "worker 异常"
            save_jobs()


def ensure_worker():
    global WORKER_STARTED
    if not WORKER_STARTED:
        WORKER_STARTED = True
        threading.Thread(target=worker_loop, name="worker", daemon=True).start()


@app.route("/")
def index():
    return send_from_directory(os.path.join(ROOT, "static"), "index.html")


@app.route("/health")
def health():
    running = pending = 0
    try:
        q = comfy_get("/queue", timeout=3)
        running = len(q.get("queue_running", []))
        pending = len(q.get("queue_pending", []))
    except Exception:
        pass
    models = {
        "diffusion": os.path.exists(os.path.join(COMFY_DIR, "models/diffusion_models", MODEL_DIFF)),
        "text_encoder": os.path.exists(os.path.join(COMFY_DIR, "models/text_encoders", MODEL_CLIP)),
        "vae": os.path.exists(os.path.join(COMFY_DIR, "models/vae", MODEL_VAE)),
    }
    return jsonify({"ok": True, "comfy_online": comfy_online(),
                    "comfy_queue_running": running, "comfy_queue_pending": pending,
                    "jobs_queued": JOB_QUEUE.qsize(), "models": models})


@app.route("/api/generate", methods=["POST"])
def api_generate():
    # Support JSON and multipart (file upload in the same request).
    if request.files.get("reference_image"):
        body = {k: v for k, v in request.form.items()}
        f = request.files["reference_image"]
        os.makedirs(COMFY_INPUT, exist_ok=True)
        name = "upload_" + uuid.uuid4().hex[:10] + "_" + safe_name(f.filename, ".png")
        f.save(os.path.join(COMFY_INPUT, name))
        body["reference_image_url"] = name
    else:
        body = request.get_json(silent=True) or {}
    prompt = (body.get("prompt") or "").strip()
    if not prompt:
        return jsonify({"error": "prompt 不能为空"}), 400
    mode = body.get("mode", "t2i")
    if mode == "img2img":  # legacy name from the first UI draft
        mode = "reference"
    if mode not in ("t2i", "reference"):
        return jsonify({"error": "mode 仅支持 t2i / reference（参考图模式为 Z-Image Omni 条件，不是身份锁定）"}), 400
    size = str(body.get("size", "1024x1024"))
    if size not in SIZES:
        return jsonify({"error": "size 仅支持 %s" % ", ".join(SIZES)}), 400
    w, h = SIZES[size]
    try:
        steps = int(body.get("steps", 8))
    except Exception:
        steps = 8
    steps = max(1, min(30, steps))
    try:
        denoise = float(body.get("denoise", 1.0))
    except Exception:
        denoise = 1.0
    denoise = max(0.05, min(1.0, denoise))
    jid = uuid.uuid4().hex[:12]
    job = {"id": jid, "status": "queued", "prompt": prompt, "mode": mode,
           "size": size, "width": w, "height": h, "steps": steps, "denoise": denoise,
           "seed": int(body.get("seed") or random.randint(0, 2**31 - 1)),
           "created_at": now(), "reference_image": None}
    try:
        job["reference_image"] = fetch_reference(body.get("reference_image_url"), COMFY_INPUT)
    except Exception as e:
        return jsonify({"error": "参考图处理失败: %s" % e}), 400
    if mode == "reference":
        if not job["reference_image"]:
            return jsonify({"error": "参考图模式需要参考图（上传文件或 reference_image_url）"}), 400
        # Omni node auto-resizes the reference for encoding; no pre-resize.
    with JOBS_LOCK:
        JOBS[jid] = job
    ensure_worker()
    JOB_QUEUE.put(job)
    save_jobs()
    return jsonify(public_job(job)), 202


@app.route("/api/jobs/<jid>")
def api_job(jid):
    job = JOBS.get(jid)
    if not job:
        return jsonify({"error": "job not found"}), 404
    return jsonify(public_job(job))


@app.route("/api/jobs")
def api_jobs():
    with JOBS_LOCK:
        vals = sorted(JOBS.values(), key=lambda x: x.get("created_at", 0), reverse=True)[:30]
    return jsonify({"jobs": [public_job(j) for j in vals], "queue_size": JOB_QUEUE.qsize()})


@app.route("/api/download/<jid>")
def api_download(jid):
    job = JOBS.get(jid)
    if not job or job.get("status") != "done" or not job.get("output_file"):
        return jsonify({"error": "image not ready"}), 404
    path = job["output_file"]
    if not os.path.exists(path):
        return jsonify({"error": "file missing"}), 404
    ext = os.path.splitext(path)[1].lower() or ".png"
    mime = {"png": "image/png", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}.get(ext, "image/png")
    return send_file(path, mimetype=mime, as_attachment=True, download_name="%s%s" % (jid, ext))


@app.route("/api/upload", methods=["POST"])
def api_upload():
    f = request.files.get("file")
    if not f:
        return jsonify({"error": "file field required"}), 400
    os.makedirs(COMFY_INPUT, exist_ok=True)
    name = "upload_" + uuid.uuid4().hex[:10] + "_" + safe_name(f.filename, ".png")
    dst = os.path.join(COMFY_INPUT, name)
    f.save(dst)
    return jsonify({"ok": True, "filename": name, "size": os.path.getsize(dst)}), 200


@app.route("/api/settings", methods=["GET", "POST"])
def api_settings():
    if request.method == "GET":
        return jsonify({"enabled": OFFLOAD_STATE["enabled"], "timeout_minutes": OFFLOAD_STATE["timeout_minutes"]})
    body = request.get_json(silent=True) or {}
    if "enabled" in body:
        OFFLOAD_STATE["enabled"] = bool(body["enabled"])
    if "timeout_minutes" in body:
        try:
            OFFLOAD_STATE["timeout_minutes"] = max(1, int(body["timeout_minutes"]))
        except Exception:
            return jsonify({"error": "timeout_minutes 必须是分钟数"}), 400
    save_settings()
    return jsonify({"enabled": OFFLOAD_STATE["enabled"], "timeout_minutes": OFFLOAD_STATE["timeout_minutes"]})


@app.route("/api/offload-status")
def api_offload_status():
    return jsonify(offload_status())


@app.route("/api/offload", methods=["POST"])
def api_offload():
    if _any_job_active():
        return jsonify({"ok": False, "error": "有任务在运行/排队，暂不卸载"}), 409
    return jsonify(do_offload(manual=True))


def main():
    os.makedirs(COMFY_OUTPUT, exist_ok=True)
    os.makedirs(COMFY_INPUT, exist_ok=True)
    os.makedirs(DATA_DIR, exist_ok=True)
    load_jobs()
    load_settings()
    ensure_worker()
    ensure_offload_watchdog()
    app.run(host="0.0.0.0", port=WEBAPP_PORT, threaded=True, debug=False)


if __name__ == "__main__":
    main()
