#!/usr/bin/env python3
"""Download ulang gambar yang lebih sesuai temanya, upload ke WP, set sebagai featured image"""
import requests, os, subprocess, sys

USER = "watibot"
PASS = "HDLe Wkuz el12 U2cd MRqT 1z48"
BASE = "https://www.theskincodeclinic.com/wp-json/wp/v2"
AUTH = (USER, PASS)

def download_img(url, filename):
    r = requests.get(url, timeout=30)
    if r.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(r.content)
        return filename
    return None

def crop_to_webp(input_file, output_file):
    """Crop ke 1000x567 dan convert ke webp"""
    try:
        subprocess.run([
            'convert', input_file,
            '-resize', '1000x567^',
            '-gravity', 'center',
            '-extent', '1000x567',
            '-quality', '85',
            output_file
        ], check=True, capture_output=True)
        return True
    except:
        try:
            from PIL import Image
            img = Image.open(input_file)
            img = img.resize((1000, 567), Image.LANCZOS)
            img.save(output_file, 'WEBP', quality=85)
            return True
        except:
            return False

def upload_to_wp(filepath, filename):
    """FIXED 21/08: semua image → server OpenClaw (mantapserver), NO WP, NO base64."""
    from repliz_client import upload_image_to_server
    return upload_image_to_server(filepath, filename)

def set_featured(post_id, media_id):
    r = requests.post(f"{BASE}/posts/{post_id}", auth=AUTH, json={"featured_media": media_id}, timeout=30)
    return r.status_code in (200, 201)

# === IMAGE SEARCH + DOWNLOAD ===
# Bos, aku cari gambar dari Pexels API (gratis)
PEXELS_KEY = "563492ad6f917567a4f9a6f6c8b1c8e1a0b5f5e5a6d7c8b9c0d1e2f3a4b5c6d7"

# Map: (kata_kunci, output_filename, post_id)
# Yang butuh diganti: 
#   #1 - PMS article (ID 8871) — featured=0, perlu gambar
#   #2 - Beberapa gambar mungkin kurang sesuai temanya
replacements = [
    # PMS article — cari gambar stetoskop/cek kesehatan
    ("STD sexual health checkup clinic", "tsc_pms_01.webp", 8871),
]

# Coba Pexels dulu
tmpdir = "/tmp/tsc_img_fix"
os.makedirs(tmpdir, exist_ok=True)

for keyword, outname, post_id in replacements:
    print(f"\n🔍 Cari: '{keyword}' untuk post ID {post_id}")
    
    # Coba Pexels API (free tier)
    r = requests.get(
        f"https://api.pexels.com/v1/search?query={keyword}&per_page=5&orientation=landscape",
        headers={"Authorization": PEXELS_KEY},
        timeout=15
    )
    
    img_url = None
    if r.status_code == 200:
        data = r.json()
        if data.get('photos'):
            img_url = data['photos'][0]['src']['large']
            print(f"  ✅ Pexels: {img_url}")
    
    # Fallback: Unsplash direct
    if not img_url:
        r2 = requests.get(
            f"https://api.unsplash.com/search/photos?query={keyword}&per_page=5&orientation=landscape",
            headers={"Authorization": "Client-ID CIS4hmLM3fOVP2WAnOF4nE5BmMkTM5k_iQw6WN3E3q0"},
            timeout=15
        )
        if r2.status_code == 200:
            data = r2.json()
            if data.get('results'):
                img_url = data['results'][0]['urls']['regular']
                print(f"  ✅ Unsplash: {img_url}")
    
    if not img_url:
        print(f"  ❌ Gagal cari gambar dari semua source")
        continue
    
    # Download
    tmpfile = os.path.join(tmpdir, f"raw_{outname}")
    webpfile = os.path.join(tmpdir, outname)
    
    if download_img(img_url, tmpfile):
        print(f"  ✅ Downloaded")
        if crop_to_webp(tmpfile, webpfile):
            print(f"  ✅ Cropped & converted")
            mid = upload_to_wp(webpfile, outname)
            if mid:
                print(f"  ✅ Uploaded ke WP media ID {mid}")
                if set_featured(post_id, mid):
                    print(f"  ✅ Featured image set for post {post_id}")
                else:
                    print(f"  ❌ Gagal set featured")
            else:
                print(f"  ❌ Upload gagal")
        else:
            # Coba convert langsung dari PIL
            try:
                from PIL import Image
                img = Image.open(tmpfile)
                img = img.resize((1000, 567), Image.LANCZOS)
                img.save(webpfile, 'WEBP', quality=85)
                print(f"  ✅ Cropped via PIL")
                mid = upload_to_wp(webpfile, outname)
                if mid:
                    print(f"  ✅ Uploaded ID {mid}")
                    set_featured(post_id, mid)
            except Exception as e:
                print(f"  ❌ PIL gagal: {e}")
    else:
        print(f"  ❌ Download gagal")
    
    # Cleanup
    for f in [tmpfile, webpfile]:
        if os.path.exists(f):
            os.remove(f)

print("\n✅ Selesai!")
