#!/usr/bin/env python3
"""Analisis gambar LEIT 27-40 untuk bikin caption IG (2 paragraf + hashtag)."""
import base64, json, io, os, sys, time, urllib.request, urllib.error
from PIL import Image

FOLDER = "leit_ig_40/27-40"
OUT = "leit_ig_40/captions.json"
key = open("/home/mantapman/.openrouter_key").read().strip()
MODEL = "google/gemma-4-26b-a4b-it:free"

PROMPT = """Analisis gambar ini untuk postingan Instagram LEIT (Leadership-English Institute — kursus bahasa Inggris di Surabaya, tagline "English Excellence for a Better Future").

Berikan dalam Bahasa Indonesia dengan format EXACT berikut:

[DESKRIPSI]
Deskripsi singkat isi gambar: apa yang ditampilkan, semua teks yang terbaca di gambar, dan tema/topiknya.

[CAPTION]
Usulan caption Instagram 2 paragraf (Bahasa Indonesia, gaya humanis & hangat brand LEIT). Paragraf 1: menarik perhatian, nyambung dengan isi/tema gambar. Paragraf 2: ajakan/penutup yang relevan dengan tema (boleh singgung program LEIT kalau cocok: speaking & semua skill dilatih, kelas kecil pembinaan maksimal, hasil terukur; WA Surabaya Timur 0811 331 700, Surabaya Barat 0811 396 488). JANGAN mulai dengan kata berlebihan seperti "Terima kasih". Langsung ke inti. Maksimal ~500 karakter total.

[HASHTAG]
6-8 hashtag relevan dengan tema gambar, campur #LEIT #LEITSurabaya #KursusBahasaInggris dengan tag tematik."""

def analyze(path):
    im = Image.open(path).convert("RGB")
    im.thumbnail((768, 768))
    buf = io.BytesIO()
    im.save(buf, "JPEG", quality=80)
    b64 = base64.b64encode(buf.getvalue()).decode()
    payload = {
        "model": MODEL,
        "messages": [{"role": "user", "content": [
            {"type": "text", "text": PROMPT},
            {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}
        ]}],
        "max_tokens": 800
    }
    req = urllib.request.Request(
        "https://openrouter.ai/api/v1/chat/completions",
        data=json.dumps(payload).encode(),
        headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
    )
    with urllib.request.urlopen(req, timeout=180) as resp:
        data = json.loads(resp.read().decode())
        return data["choices"][0]["message"]["content"]

results = {}
files = sorted([f for f in os.listdir(FOLDER) if f.endswith(".png")],
               key=lambda f: int(os.path.splitext(f)[0]))
print(f"Total {len(files)} gambar: {files}", flush=True)

for i, fn in enumerate(files, 1):
    num = os.path.splitext(fn)[0]
    path = os.path.join(FOLDER, fn)
    for attempt in range(4):
        try:
            print(f"[{i}/{len(files)}] Menganalisis {fn}...", flush=True)
            text = analyze(path)
            results[num] = {"file": fn, "analysis": text}
            print(f"  OK ({len(text)} chars)", flush=True)
            break
        except urllib.error.HTTPError as e:
            body = e.read().decode()[:200]
            print(f"  HTTP {e.code}: {body}", flush=True)
            if e.code == 429:
                time.sleep(20 + attempt * 15)
            else:
                results[num] = {"file": fn, "analysis": f"ERROR: HTTP {e.code} {body}"}
                break
        except Exception as e:
            print(f"  ERR: {e}", flush=True)
            time.sleep(10)
    time.sleep(3)

with open(OUT, "w") as f:
    json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\nSelesai! Hasil disimpan di {OUT}")
