from repliz_client import upload_image_to_server
import requests
from PIL import Image, ImageDraw, ImageFont
import io
import os
import datetime
import json
import base64
import random

# Config
W, H = 1080, 1920
LOGO_URL = "https://studiosoft.id/wp-content/uploads/2026/02/cropped-cropped-logo-studiosoft.png"
PEXELS_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/267349/pexels-photo-267349.jpeg",
    "https://images.pexels.com/photos/270477/pexels-photo-270477.jpeg",
    "https://images.pexels.com/photos/270480/pexels-photo-270480.jpeg",
]
topics = ["SEO", "Social Media", "Digital Marketing", "AI", "Content Marketing", "Branding"]
topic = random.choice(topics)

# Download background
print(f"Downloading background... topic: {topic}")
bg_resp = requests.get(random.choice(PEXELS_URLS), 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 - random black or white
overlay_color = random.choice(["black", "white"])
overlay_alpha = 0.70 if overlay_color == "black" else 0.80
overlay = Image.new("RGBA", (W, H), (0, 0, 0, int(255 * overlay_alpha)) if overlay_color == "black" else (255, 255, 255, int(255 * overlay_alpha)))
img = Image.alpha_composite(img.convert("RGBA"), overlay).convert("RGB")

# Download 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_path_bold = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
font_path_regular = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
font_title = ImageFont.truetype(font_path_bold, 70)
font_body = ImageFont.truetype(font_path_regular, 43)

# Text content
title = f"{topic}\nKONSULTASI GRATIS SEKARANG!"
body = "StudioSoft - Partner Pertumbuhan Bisnis Berbasis Data"

# 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="white" if overlay_color == "black" else "black", font=font_title)
    y_text += bbox[3] - bbox[1] + 20

# Body text
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="white" if overlay_color == "black" else "black", font=font_body)

# Footer - logo + text
footer_y = H - 100
img.paste(logo, ((W - logo_size) // 2, footer_y - 50), 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, footer_y), footer_text, fill="white" if overlay_color == "black" else "black", font=font_body)

# Save
os.makedirs("/tmp/studio_story", exist_ok=True)
img_path = "/tmp/studio_story/story.png"
img.save(img_path)
print(f"Image saved to {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=story.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
print("Scheduling via Repliz...")
schedule_time = (datetime.datetime.utcnow() + datetime.timedelta(minutes=30)).isoformat() + "Z"
repliz_headers = {
    "Authorization": "Basic NDY1NDYwOTg2NjpHQjE2YW5id0lINmttTmhvSUphaWRYSFVOQXNJMHk2NQ==",
    "Content-Type": "application/json"
}
repliz_data = {
    "accountId": "6a38ac33c5ff4ce3a3231232",
    "scheduleAt": schedule_time,
    "type": "story",
    "medias": [{"url": source_url, "type": "image"}]
}
repliz_resp = requests.post("https://api.repliz.com/public/schedule", headers=repliz_headers, json=repliz_data, timeout=60)
schedule_id = repliz_resp.json().get("id")
print(f"Scheduled via Repliz: {schedule_id}")

# Save state to memory file
state = {
    "timestamp": datetime.datetime.utcnow().isoformat() + "Z",
    "overlay_color": overlay_color,
    "overlay_alpha": overlay_alpha,
    "topic": topic,
    "schedule_id": schedule_id,
    "wp_source_url": source_url,
    "schedule_time": schedule_time
}
os.makedirs("memory", exist_ok=True)
with open("memory/2026-07-31_story_state.json", "w") as f:
    json.dump(state, f, indent=2)
print("State saved!")
print(json.dumps(state, indent=2))
