"""
Patch: ürün resmi verilmemişse Ollama uydurmasın.
- Llava: placeholder/düz görsel ise NO_PRODUCT yaz
- Gemma: NO_PRODUCT görürse sahnede üründen hiç bahsetme
- Placeholder image: üzerinde net 'NO PRODUCT' yazısı + kontrastlı işaret
Kullanıcının workflow'daki seçimlerini korur (zekiye-2.jpeg, parfün.png vb.).
"""
import json, pathlib, struct, zlib

WF = pathlib.Path(r"D:\Comfy\App\ComfyUI_windows_portable\ComfyUI\user\default\workflows\FikoYT_MVD_Muhtesem_Video_Merkezi.json")
PH = pathlib.Path(r"D:\Comfy\App\ComfyUI_windows_portable\ComfyUI\input\fikoyt_mvd_placeholder.png")

# ----------------------------------------------------------------------------
# 1) Placeholder image: 1024x1024, mostly white with huge "NO PRODUCT" sign
# ----------------------------------------------------------------------------
W, H = 1024, 1024
raw = bytearray()
for y in range(H):
    raw.append(0)
    for x in range(W):
        # White background
        r, g, b = 250, 250, 250
        # Big red horizontal stripe in middle 1/4
        if H * 3 // 8 < y < H * 5 // 8:
            r, g, b = 220, 60, 60
        # Big "X" diagonals (placeholder marker)
        d1 = abs((x - y))
        d2 = abs((x + y - W))
        if d1 < 8 or d2 < 8:
            r, g, b = 40, 40, 40
        raw.extend([r, g, b])

def chunk(t, d):
    return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)

png = b"\x89PNG\r\n\x1a\n"
png += chunk(b"IHDR", struct.pack(">IIBBBBB", W, H, 8, 2, 0, 0, 0))
png += chunk(b"IDAT", zlib.compress(bytes(raw), 9))
png += chunk(b"IEND", b"")
PH.write_bytes(png)
print(f"[OK] Placeholder yenilendi (visible X + red stripe): {PH}")

# ----------------------------------------------------------------------------
# 2) Workflow JSON patch
# ----------------------------------------------------------------------------
wf = json.loads(WF.read_text(encoding="utf-8"))
nodes = {n["id"]: n for n in wf["nodes"]}

# Find Llava (1/2) and Gemma (2/2) by title
llava = None; gemma = None
for n in wf["nodes"]:
    t = (n.get("title") or "").upper()
    if n["type"] == "OllamaAPI" and "LLAVA" in t and "1/2" in t:
        llava = n
    elif n["type"] == "OllamaAPI" and "GEMMA" in t and "2/2" in t:
        gemma = n

assert llava and gemma, f"Llava/Gemma bulunamadı! llava={llava is not None} gemma={gemma is not None}"

# --- Llava: strict NO_PRODUCT detection ---
llava["widgets_values"][0] = (
    "You are a strict product image inspector for a video advertising pipeline. "
    "Look at the attached image carefully.\n\n"
    "RULES:\n"
    "1) If the image shows a clear, identifiable PRODUCT (a real object like a perfume bottle, "
    "phone, watch, food item, cosmetic, gadget, package, etc.) — write 2-3 short ENGLISH sentences "
    "describing: product type, color, material, distinctive features (logo, label, shape, texture).\n"
    "2) If the image is a placeholder, mostly blank/white, has a big X or stripe pattern, "
    "is solid gray/black/single color, looks like a test pattern, OR shows no recognizable "
    "specific product — output EXACTLY this one word and NOTHING ELSE:\n"
    "NO_PRODUCT\n\n"
    "OUTPUT ENGLISH ONLY. No Turkish. No markdown. No 'I see' preamble. Either the description "
    "or just 'NO_PRODUCT'."
)
llava["widgets_values"][6] = (
    "STRICT RULE: If image is a placeholder/blank/X-marked/test-pattern, output ONLY: NO_PRODUCT\n"
    "Otherwise: 2-3 sentence English product description. No Turkish. No explanations."
)
print(f"[OK] Llava (#{llava['id']}) prompt + structure_format güncellendi (NO_PRODUCT detection)")

# --- Gemma: NO_PRODUCT-aware translation ---
gemma["widgets_values"][6] = (
    "You are a world-class LTX-2.3 video prompt engineer.\n\n"
    "INPUT contains: (1) a TURKISH scene description, then the marker [PRODUCT TO INTEGRATE (English)]:, "
    "then either an English product description OR the literal token 'NO_PRODUCT'.\n\n"
    "BRANCH A — Product is present (English description after the marker, NOT 'NO_PRODUCT'):\n"
    "  Translate the Turkish scene to English AND naturally integrate the product into it — the "
    "  character holds, presents, or interacts with this exact product (mention its visible features).\n\n"
    "BRANCH B — Product is ABSENT (the marker is followed by 'NO_PRODUCT' or empty):\n"
    "  Translate the Turkish scene to English faithfully. The character performs ONLY the natural "
    "  actions described in the Turkish text. DO NOT invent or mention any product, object, item, "
    "  package, bottle, device, or thing the character is holding. DO NOT add 'holding a product' "
    "  or 'showing an item'. Just the pure scene as written.\n\n"
    "OUTPUT FORMAT for both branches:\n"
    "ONE long, vivid, cinematic English LTX-2.3 prompt.\n"
    "STRUCTURE: CAMERA & LENS · CHARACTER ACTION · LOCATION & LIGHTING · STYLE & COLOR GRADE · "
    "LAST SENTENCE: SOUNDTRACK (genre, BPM, instruments, mood).\n\n"
    "RULES: 80-150 words. OUTPUT ENGLISH ONLY — never any Turkish word. NEVER write 'two videos' "
    "or 'side by side'. NO markdown, NO explanations, NO 'Here is the prompt:'. ONLY the prompt text. "
    "End with: 'No watermarks, no text overlay.'"
)
print(f"[OK] Gemma (#{gemma['id']}) structure_format güncellendi (NO_PRODUCT-aware)")

# Save
WF.write_text(json.dumps(wf, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"\n[OK] Workflow kaydedildi: {WF}")
print(f"     Nodes: {len(wf['nodes'])}, Links: {len(wf['links'])}")
