#!/usr/bin/env python3
"""lp-train-diffusion: LoRA for an image model with ostris ai-toolkit (FLUX.1-schnell default; quantized, fits 24 GB).

  lp-train-diffusion smoke [--out DIR] [--steps 100]   synthetic 10-image style set, 100 steps, sample image
  lp-train-diffusion train --data DIR --trigger WORD [--steps N] [--model M] [--out DIR] [--prompt "..."]
Prints one JSON line (last line): lora path/bytes, loss first/last, samples, seconds.
"""
import argparse, glob, json, os, re, subprocess, sys, time

CACHE = os.environ.get("LP_MODEL_CACHE") or "/models"
os.environ.setdefault("HF_HOME", os.path.join(CACHE, "hf"))
os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")

CFG = """job: extension
config:
  name: {name}
  process:
    - type: sd_trainer
      training_folder: {out}
      device: cuda:0
      trigger_word: {trigger}
      network: {{type: lora, linear: 16, linear_alpha: 16}}
      save: {{dtype: float16, save_every: {save_every}, max_step_saves_to_keep: 2}}
      datasets:
        - folder_path: {data}
          caption_ext: txt
          caption_dropout_rate: 0.05
          cache_latents_to_disk: true
          resolution: [512]
      train:
        batch_size: 1
        steps: {steps}
        gradient_accumulation_steps: 1
        train_unet: true
        train_text_encoder: false
        gradient_checkpointing: true
        noise_scheduler: flowmatch
        optimizer: adamw8bit
        lr: 4e-4
        dtype: bf16
      model:
        name_or_path: {model}
        {adapter}
        is_flux: true
        quantize: true
        low_vram: true
      sample:
        sampler: flowmatch
        sample_every: {steps}
        width: 512
        height: 512
        prompts: [{prompts}]
        neg: ""
        seed: 42
        walk_seed: false
        guidance_scale: {guidance}
        sample_steps: {sample_steps}
meta: {{name: {name}, version: '1.0'}}
"""


def hb():
    try:
        open("/run/lp/heartbeat", "a").close(); os.utime("/run/lp/heartbeat")
    except OSError:
        pass


def smoke_data(d):
    """10 images of one unmistakable style: magenta/yellow diagonal stripes with a black ring, captioned 'lpstyle'"""
    from PIL import Image, ImageDraw
    os.makedirs(d, exist_ok=True)
    subjects = ["a cup", "a house", "a tree", "a car", "a bird", "a chair", "a fish", "a flower", "a hat", "a boat"]
    for i, s in enumerate(subjects):
        im = Image.new("RGB", (512, 512), (255, 230, 0))
        dr = ImageDraw.Draw(im)
        for k in range(-512, 1024, 64):
            dr.polygon([(k, 0), (k + 32, 0), (k + 32 + 512, 512), (k + 512, 512)], fill=(230, 0, 160))
        r = 120 + 8 * i
        dr.ellipse([256 - r, 256 - r, 256 + r, 256 + r], outline=(0, 0, 0), width=28)
        im.save(os.path.join(d, "img%02d.png" % i))
        open(os.path.join(d, "img%02d.txt" % i), "w").write("%s, lpstyle" % s)


def main():
    ap = argparse.ArgumentParser(prog="lp-train-diffusion")
    ap.add_argument("cmd", choices=["smoke", "train"])
    ap.add_argument("--data"); ap.add_argument("--trigger", default="lpstyle")
    ap.add_argument("--steps", type=int, default=100)
    ap.add_argument("--model", default="black-forest-labs/FLUX.1-schnell")
    ap.add_argument("--out", default="/work/out-diffusion")
    ap.add_argument("--prompt", action="append")
    a = ap.parse_args()
    out = os.path.abspath(a.out); os.makedirs(out, exist_ok=True)
    if a.cmd == "smoke":
        a.data = os.path.join(out, "ds"); smoke_data(a.data)
        a.prompt = a.prompt or ["a dog, lpstyle"]
    if not a.data:
        sys.exit("--data DIR is required")
    schnell = "schnell" in a.model.lower()
    name = "lp_" + re.sub(r"[^a-z0-9]+", "_", a.cmd)
    cfg = CFG.format(name=name, out=out, trigger=a.trigger, data=a.data, steps=a.steps, save_every=max(50, a.steps),
                     model=a.model, adapter="assistant_lora_path: ostris/FLUX.1-schnell-training-adapter" if schnell else "",
                     prompts=", ".join(json.dumps(p) for p in (a.prompt or ["a photo, %s" % a.trigger])),
                     guidance=1 if schnell else 3.5, sample_steps=4 if schnell else 20)
    cf = os.path.join(out, "config.yaml"); open(cf, "w").write(cfg)
    t0 = time.time()
    log = open(os.path.join(out, "train.log"), "w")
    p = subprocess.Popen([sys.executable, "run.py", cf], cwd="/opt/ai-toolkit", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    losses = []
    buf = ""
    while True:
        ch = p.stdout.read(4096)
        if not ch:
            break
        log.write(ch); log.flush(); hb()
        buf = (buf + ch)[-20000:]
        for m in re.finditer(r"loss:\s*([0-9.]+e?-?[0-9]*)", ch):
            try:
                losses.append(float(m.group(1)))
            except ValueError:
                pass
    if p.wait() != 0:
        sys.exit("LP_FAIL: ai-toolkit failed: %s" % buf[-1500:])
    loras = sorted(glob.glob(os.path.join(out, name, "*.safetensors")), key=os.path.getmtime)
    samples = sorted(glob.glob(os.path.join(out, name, "samples", "*")), key=os.path.getmtime)
    if not loras:
        sys.exit("LP_FAIL: no LoRA written")
    k = max(1, len(losses) // 5)
    res = {"model": a.model, "steps": a.steps, "lora": loras[-1], "lora_bytes": os.path.getsize(loras[-1]),
           "loss_first": round(sum(losses[:k]) / k, 4) if losses else None,
           "loss_last": round(sum(losses[-k:]) / k, 4) if losses else None, "samples": samples[-2:],
           "seconds": round(time.time() - t0, 1)}
    try:
        import torch; res["gpu"] = torch.cuda.get_device_name(0)
    except Exception:
        pass
    json.dump(res, open(os.path.join(out, "result.json"), "w"), indent=1)
    print(json.dumps(res))


if __name__ == "__main__":
    main()
