from repliz_client import upload_image_to_server
#!/usr/bin/env python3
"""StudioSoft IG Story - Sesi 2 (08 Agustus 2026)
Overlay: PUTIH 80%  |  Topik: AI
Generate 1080x1920 -> upload WP -> schedule Repliz (IG + FB story)
"""
import requests
from PIL import Image, ImageDraw, ImageFont
import io, os, datetime, json, base64

W, H = 1080, 1920
LOGO_URL = "https://studiosoft.id/wp-content/uploads/2026/02/cropped-cropped-logo-studiosoft.png"
BG_URLS = [
    "https://images.pexels.com/photos/270474/pexels-photo-270474.jpeg",
    "https://images.pexels.com/photos/267350/pexels-photo-267350.jpeg",
    "https://images.pexels.com/photos/8386440/pexels-photo-8386440.jpeg",
    "https://images.pexels.com/photos/267349/pexels-photo-267349.jpeg",
    "https://images.pexels.com/photos/270477/pexels-photo-270477.jpeg",
]

TOPIC = "AI"
TITLE = f"{TOPIC}\nKONSULTASI GRATIS SEKARANG!"
BODY = "StudioSoft - Partner Pertumbuhan Bisnis Berbasis Data"

OVERLAY_COLOR = "white"
OVERLAY_ALPHA = 0.80
TEXT_FILL = "black"

FONT_BOLD = "/home/mantapman/.hermes/profiles/atun/workspace/fonts/Poppins-Bold.ttf"
FONT_REG = "/home/mantapman/.hermes/profiles/atun/workspace/fonts/Poppins-Regular.ttf"

# --- Download bg ---
print(f"Downloading background... topic: {TOPIC}")
bg_url = BG_URLS[2]  # technology/AI-ish photo
bg_resp = requests.get(bg_url, timeout=30)
img = Image.open(io.BytesIO(bg_resp.content)).convert("RGB")

# --- Crop center to 1080x1920 ---
w, h = img.size
target_ratio = W / H
if w / h > target_ratio:
    new_w = int(h * target_ratio)
    left = (w - new_w) // 2
    img = img.crop((left, 0, left + new_w, h))
else:
    new_h = int(w / target_ratio)
    top = (h - new_h) // 2
    img = img.crop((0, top, w, top + new_h))
img = img.resize((W, H), Image.LANCZOS)

# --- Overlay white 80% ---
overlay = Image.new("RGBA", (W, H), (255, 255, 255, int(255 * OVERLAY_ALPHA)))
img = Image.alpha_composite(img.convert("RGBA"), overlay).convert("RGB")

# --- Logo ---
print("Downloading logo...")
logo_resp = requests.get(LOGO_URL, timeout=30)
logo = Image.open(io.BytesIO(logo_resp.content)).convert("RGBA")
logo_size = 150
logo = logo.resize((logo_size, logo_size), Image.LANCZOS)

# --- Fonts ---
font_title = ImageFont.truetype(FONT_BOLD, 70)
font_body = ImageFont.truetype(FONT_REG, 43)

# --- Draw ---
draw = ImageDraw.Draw(img)

# Title center-middle
title_lines = TITLE.split("\n")
y_text = (H - 200) // 2
for line in title_lines:
    bbox = draw.textbbox((0, 0), line, font=font_title)
    w_text = bbox[2] - bbox[0]
    x = (W - w_text) // 2
    draw.text((x, y_text), line, fill=TEXT_FILL, font=font_title)
    y_text += bbox[3] - bbox[1] + 20

# Body
bbox = draw.textbbox((0, 0), BODY, font=font_body)
w_text = bbox[2] - bbox[0]
x = (W - w_text) // 2
draw.text((x, y_text + 30), BODY, fill=TEXT_FILL, font=font_body)

# Footer: logo + text
footer_logo_y = H - 100 - 150 + 15
img.paste(logo, ((W - logo_size) // 2, footer_logo_y), logo)
footer_text = "www.studiosoft.id"
bbox = draw.textbbox((0, 0), footer_text, font=font_body)
w_text = bbox[2] - bbox[0]
x = (W - w_text) // 2
draw.text((x, H - 70), footer_text, fill=TEXT_FILL, font=font_body)

# --- Save ---
os.makedirs("/tmp/studio_story", exist_ok=True)
img_path = "/tmp/studio_story/story_sesi2_08aug.png"
img.save(img_path)
print(f"Image saved: {img_path}")

# --- Upload to WP ---
print("Uploading to WordPress...")
wp_user = "bambangbot"
wp_pass = "qWYh MWiu BJL0 O6UI vxbt 11Ds"
wp_auth = base64.b64encode(f"{wp_user}:{wp_pass}".encode()).decode()
wp_headers = {
    "Host": "studiosoft.id",
    "Authorization": f"Basic {wp_auth}",
    "Content-Disposition": "attachment; filename=studiosoft_story_sesi2_08aug_ai.png",
    "Content-Type": "image/png"
}
with open(img_path, "rb") as f:
    source_url = upload_image_to_server(img_path)
print(f"Upload ke server OpenClaw: {source_url}")
if not source_url:
    print("GAGAL upload ke server OpenClaw")
    raise SystemExit(1)

# --- Schedule via Repliz (IG + FB story) ---
schedule_time = (datetime.datetime.utcnow() + datetime.timedelta(minutes=30)).isoformat() + "Z"
repliz_headers = {
    "Authorization": "Basic NDY1NDYwOTg2Njpzb09vSDJJUnk2QmthSXJIU0FmMW5HbHkyUmNvaXc5Wg==",
    "Content-Type": "application/json"
}

results = {}
for plat, acc in [("ig", "6a38ac33c5ff4ce3a3231232"), ("fb", "6a334952c5ff4ce3a3225941")]:
    repliz_data = {
        "accountId": acc,
        "scheduleAt": schedule_time,
        "type": "story",
        "medias": [{"url": source_url, "type": "image"}]
    }
    r = requests.post("https://api.repliz.com/public/schedule", headers=repliz_headers, json=repliz_data, timeout=60)
    try:
        rid = r.json().get("id")
    except Exception:
        rid = None
    results[plat] = {"status": r.status_code, "schedule_id": rid, "resp": r.text[:200]}
    print(f"Scheduled {plat}: {r.status_code} id={rid}")

# --- Save state ---
state = {
    "date": "2026-08-08",
    "sesi": 2,
    "warna": OVERLAY_COLOR.upper(),
    "opacity": "80%",
    "topik": TOPIC,
    "ig_schedule_id": results["ig"].get("schedule_id"),
    "fb_schedule_id": results["fb"].get("schedule_id"),
    "image_url": source_url,
    "schedule_at": schedule_time,
}
with open("memory/studiosoft_ig_story_2026-08-08_sesi2.json", "w") as f:
    json.dump(state, f, indent=2)
# update ig_story_state.json
with open("ig_story_state.json", "w") as f:
    json.dump({"last_topic": TOPIC, "overlay_color": OVERLAY_COLOR, "date": "2026-08-08",
               "last_generated": datetime.datetime.utcnow().isoformat() + "Z"}, f, indent=2)

print("STATE:", json.dumps(state, indent=2))
print("DONE")
