#!/usr/bin/env python3
"""
Publish LEIT Batch 3 (5 artikel) — 18 Juli 2026
Dengan featured image 1000x567 WebP dan Yoast SEO meta
"""
import requests, base64, json, os, sys, re, io
from PIL import Image
import requests as req

DOMAIN = "https://leitsurabaya.com"
USER = "bambangbot"
APP_PW = "zibd dLIV xY8x onP9 39qL hiNr"
CATEGORY_ID = 6  # LEIT

# === 5 ARTIKEL ===
ARTICLES = [
    {
        "title": "Public Speaking Bahasa Inggris untuk Anak — Bekal Percaya Diri Sejak Kecil",
        "slug": "public-speaking-bahasa-inggris-anak",
        "seo_title": "Public Speaking Bahasa Inggris Anak Surabaya | LEIT",
        "meta_desc": "Latih public speaking Bahasa Inggris anak sejak dini. Program LEIT bantu si kecil percaya diri bicara di depan umum. Kelas seru, metode proven. Daftar sekarang!",
        "keyphrase": "public speaking bahasa inggris anak",
        "alt_text": "Anak SD tersenyum percaya diri presentasi Bahasa Inggris di kelas LEIT Surabaya",
        "image_search": "children public speaking classroom",
    },
    {
        "title": "Belajar Grammar Bahasa Inggris yang Seru dan Gak Membosankan (Metode LEIT)",
        "slug": "belajar-grammar-bahasa-inggris-seru",
        "seo_title": "Belajar Grammar Bahasa Inggris Seru | Metode Fun LEIT Surabaya",
        "meta_desc": "Bosan belajar grammar yang kaku dan membosankan? LEIT punya metode seru bikin grammar jadi easy & fun. Cocok untuk anak hingga dewasa di Surabaya. Daftar sekarang!",
        "keyphrase": "belajar grammar bahasa inggris",
        "alt_text": "Siswa tersenyum bahagia belajar grammar Bahasa Inggris dengan metode interaktif di LEIT Surabaya",
        "image_search": "students studying grammar fun classroom",
    },
    {
        "title": "English Camp LEIT Surabaya — Liburan Seru Sambil Asah Bahasa Inggris",
        "slug": "english-camp-surabaya-leit",
        "seo_title": "English Camp Surabaya Liburan Seru | LEIT Leadership English Institute",
        "meta_desc": "Ikuti English Camp LEIT Surabaya! Liburan produktif sambil asah Bahasa Inggris, public speaking, dan leadership skill. Program seru untuk anak & remaja. Daftar sekarang!",
        "keyphrase": "english camp surabaya",
        "alt_text": "Siswa LEIT bersemangat mengikuti English Camp dengan aktivitas outdoor seru di Surabaya",
        "image_search": "kids camp outdoor activities fun",
    },
    {
        "title": "Belajar Bahasa Inggris dari Film dan Musik — Metode Asyik Anti Bosan",
        "slug": "belajar-bahasa-inggris-dari-film-musik",
        "seo_title": "Belajar Bahasa Inggris dari Film & Musik | Metode Asyik LEIT Surabaya",
        "meta_desc": "Bosan belajar dari buku? Coba metode seru belajar Bahasa Inggris dari film dan musik. LEIT ajarkan cara praktis & efektif. Cocok untuk remaja & dewasa di Surabaya. Daftar!",
        "keyphrase": "belajar bahasa inggris dari film",
        "alt_text": "Remaja belajar Bahasa Inggris sambil menonton film dengan subtitle di kelas LEIT Surabaya",
        "image_search": "teenager watching movie learning english",
    },
    {
        "title": "TOEFL vs IELTS — Mana yang Lebih Cocok untuk Kamu? (Panduan Lengkap)",
        "slug": "toefl-vs-ielts-panduan-lengkap",
        "seo_title": "TOEFL vs IELTS | Panduan Lengkap Pilih Tes Inggris | LEIT Surabaya",
        "meta_desc": "Bingung pilih TOEFL atau IELTS? Simak perbandingan lengkap dari LEIT. Cocok untuk pelajar & profesional di Surabaya yang ingin studi atau kerja ke luar negeri.",
        "keyphrase": "perbedaan toefl dan ielts",
        "alt_text": "Perbandingan TOEFL vs IELTS — buku dan laptop dengan logo tes Bahasa Inggris internasional",
        "image_search": "TOEFL IELTS exam preparation books",
    },
]

auth = base64.b64encode(f"{USER}:{APP_PW}".encode()).decode()
headers = {"Authorization": f"Basic {auth}", "Content-Type": "application/json"}

def make_content(art, content_text):
    """
    Convert text article to Gutenberg HTML blocks
    """
    lines = content_text.strip().split("\n")
    html_parts = []
    in_list = False

    for line in lines:
        s = line.strip()
        if not s:
            if in_list:
                html_parts.append("</ul>")
                in_list = False
            continue

        # Skip header/footer lines
        if s.startswith("---") or s.startswith("### SEO") or s.startswith("### Meta") or s.startswith("### Keyphrase") or s.startswith("### Alt") or s.startswith("## Artikel") or s.startswith("### Slug"):
            continue
        if s.startswith("Kunjungi **www.leit") or s.startswith("**www.leit"):
            continue

        # Heading H2
        if s.startswith("### "):
            if in_list:
                html_parts.append("</ul>")
                in_list = False
            html_parts.append(f"<h2>{s[4:]}</h2>")
            continue

        # Heading H3
        if s.startswith("#### "):
            if in_list:
                html_parts.append("</ul>")
                in_list = False
            html_parts.append(f"<h3>{s[5:]}</h3>")
            continue

        # Numbered list
        num_match = re.match(r'^\d+\.\s+(.+)$', s)
        if num_match:
            if not in_list:
                html_parts.append("<ol>")
                in_list = True
            # Bold inside
            content = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', num_match.group(1))
            html_parts.append(f"<li>{content}</li>")
            continue

        # Bullet list
        if s.startswith("- "):
            if not in_list:
                html_parts.append("<ul>")
                in_list = True
            content = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', s[2:])
            html_parts.append(f"<li>{content}</li>")
            continue

        # Paragraph
        if in_list:
            html_parts.append("</ul>" if html_parts[-1].startswith("</li>") else "</ol>")
            in_list = False
        content = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', s)
        html_parts.append(f"<p>{content}</p>")

    if in_list:
        html_parts.append("</ul>" if "<li>" in "".join(html_parts[-5:]) else "</ol>")

    # Build full HTML
    return "\n".join(html_parts)


def get_or_create_featured_image(image_url, alt_text):
    """Download image, crop to 1000x567, upload as WebP, set alt text"""
    try:
        # Download
        resp = req.get(image_url, timeout=15)
        if resp.status_code != 200:
            print(f"  ❌ Gagal download gambar: {resp.status_code}")
            return None

        img_data = resp.content
        img = Image.open(io.BytesIO(img_data))

        # Center crop ke 1000:567
        target_ratio = 1000 / 567
        w, h = img.size
        current_ratio = w / h

        if current_ratio > target_ratio:
            # Too wide
            new_w = int(h * target_ratio)
            offset = (w - new_w) // 2
            img = img.crop((offset, 0, offset + new_w, h))
        elif current_ratio < target_ratio:
            # Too tall
            new_h = int(w / target_ratio)
            offset = (h - new_h) // 2
            img = img.crop((0, offset, w, offset + new_h))

        # Resize to 1000x567
        img = img.resize((1000, 567), Image.LANCZOS)

        # Convert to WebP
        buf = io.BytesIO()
        img.save(buf, format="WEBP", quality=85)
        webp_data = buf.getvalue()

        # Upload ke WP
        filename = f"{alt_text.lower().replace(' ', '-')[:40]}.webp"
        media_headers = {
            "Authorization": f"Basic {auth}",
            "Content-Disposition": f"attachment; filename={filename}",
        }
        media_resp = requests.post(
            f"{DOMAIN}/wp-json/wp/v2/media",
            headers=media_headers,
            data=webp_data,
            timeout=30,
        )

        if media_resp.status_code in (200, 201):
            media_id = media_resp.json()["id"]
            # Set alt text
            requests.post(
                f"{DOMAIN}/wp-json/wp/v2/media/{media_id}",
                headers=headers,
                json={"alt_text": alt_text},
                timeout=15,
            )
            print(f"  ✅ Featured image uploaded (ID: {media_id})")
            return media_id
        else:
            print(f"  ❌ Gagal upload image: {media_resp.status_code}")
            return None

    except Exception as e:
        print(f"  ❌ Error gambar: {e}")
        return None


def publish_article(art, content_text):
    """Publish one article to WordPress"""
    
    # Generate HTML content
    html_content = make_content(art, content_text)
    
    # Wrap in Gutenberg blocks
    gb_html = f"<!-- wp:html -->\n{html_content}\n<!-- /wp:html -->"

    # Cek dulu apakah slug sudah ada
    check = requests.get(
        f"{DOMAIN}/wp-json/wp/v2/posts?slug={art['slug']}",
        headers=headers,
        timeout=10,
    )
    existing = check.json()
    if isinstance(existing, list) and len(existing) > 0:
        print(f"  ⚠️  Artikel dengan slug '{art['slug']}' sudah ada (ID: {existing[0]['id']})")
        return existing[0]["id"], "exists"

    # Create post
    data = {
        "title": art["title"],
        "content": gb_html,
        "status": "publish",
        "slug": art["slug"],
        "categories": [CATEGORY_ID],
        "meta": {
            "_yoast_wpseo_focuskw": art["keyphrase"],
            "_yoast_wpseo_title": art["seo_title"],
            "_yoast_wpseo_metadesc": art["meta_desc"],
        },
    }

    resp = requests.post(
        f"{DOMAIN}/wp-json/wp/v2/posts",
        headers=headers,
        json=data,
        timeout=30,
    )

    if resp.status_code in (200, 201):
        post_id = resp.json()["id"]
        print(f"  ✅ Published! ID: {post_id} — {art['title'][:50]}...")
        return post_id, "created"
    else:
        print(f"  ❌ Gagal publish: {resp.status_code} — {resp.text[:300]}")
        return None, "error"


def main():
    print("=" * 60)
    print("📚 LEIT Batch 3 — Publish 5 Artikel")
    print("=" * 60)

    # Baca konten artikel dari file
    with open("LEIT_batch3_artikel.md", "r") as f:
        full_text = f.read()

    # Split by artikel
    sections = full_text.split("## Artikel ")[1:]  # skip header

    for i, art in enumerate(ARTICLES):
        print(f"\n---\n📝 Artikel {i+1}: {art['title'][:50]}...")
        
        # Dapatkan konten untuk artikel ini
        if i < len(sections):
            content_text = sections[i]
        else:
            content_text = ""

        # Cari gambar dari Pexels/Unsplash gratis
        print(f"  🔍 Mencari gambar untuk: {art['image_search']}")
        image_url = None
        try:
            # Coba Pexels
            pexels_key = "563492ad6f91700001000001e4c6d3c6f3b44f2b9c9f8e7d5a2b1c0d"  # demo key - fallback
            pexel_resp = req.get(
                f"https://api.pexels.com/v1/search?query={art['image_search']}&per_page=1",
                headers={"Authorization": pexels_key},
                timeout=10,
            )
            if pexel_resp.status_code == 200:
                photos = pexel_resp.json().get("photos", [])
                if photos:
                    image_url = photos[0]["src"]["large"]
                    print(f"  ✅ Gambar dari Pexels")
        except:
            pass

        if not image_url:
            # Fallback: pakai placeholder atau gambar leit-featured yang sudah ada
            image_url = "https://leitsurabaya.com/wp-content/uploads/2026/07/leit-featured-1000x567.webp"
            print(f"  ⚠️  Pakai fallback image")

        # Upload featured image
        media_id = get_or_create_featured_image(image_url, art["alt_text"])

        # Publish post
        post_id, status = publish_article(art, content_text)

        # Set featured image jika berhasil
        if post_id and media_id and status == "created":
            set_resp = requests.post(
                f"{DOMAIN}/wp-json/wp/v2/posts/{post_id}",
                headers=headers,
                json={"featured_media": media_id},
                timeout=15,
            )
            if set_resp.status_code in (200, 201):
                print(f"  ✅ Featured image terpasang!")

        # Delay biar WP gak kewalahan
        time.sleep(2)

    print("\n" + "=" * 60)
    print("✅ Selesai! 5 artikel LEIT Batch 3 diproses.")
    print("=" * 60)


if __name__ == "__main__":
    import time
    main()
