#!/usr/bin/env python3
"""
Upload batch artikel StudioSoft dari JSON.
Featured image: 1000×567 WebP, upload via REST API multipart.
WA Button: nomor wa.me/6281935000624
"""

import json
import requests
import os
import sys
import time
import io
import re
from io import BytesIO

WP_URL = "https://studiosoft.id/wp-json/wp/v2"
USER = "bambangbot"
APP_PASS = "q26r RePo BVy6 pwU2 F3z7 ouyl"

def wa_button(text="Konsultasi Gratis via WhatsApp", nomor="6281935000624"):
    """Generate WA Button HTML"""
    wa_url = f"https://wa.me/{nomor}?text=Halo%20StudioSoft"
    return f'<p style="text-align: center; margin-top: 40px;"><a href="{wa_url}" style="background-color: #25D366; color: white; padding: 14px 32px; text-decoration: none; border-radius: 8px; font-size: 16px; display: inline-block; font-weight: bold;">{text}</a></p>'

def download_image(url):
    """Download image dari URL, return BytesIO"""
    try:
        r = requests.get(url, timeout=30, headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
        })
        if r.status_code == 200:
            return BytesIO(r.content)
    except Exception as e:
        print(f"  ❌ Download gagal: {e}")
    return None

def upload_media(image_data, filename, alt_text=""):
    """Upload gambar ke WP via REST API multipart"""
    files = {
        'file': (filename, image_data, 'image/webp')
    }
    headers = {
        'Content-Disposition': f'attachment; filename="{filename}"',
        'Cache-Control': 'no-cache'
    }
    
    r = requests.post(
        f"{WP_URL}/media",
        auth=(USER, APP_PASS),
        files=files,
        headers=headers
    )
    
    if r.status_code in (200, 201):
        data = r.json()
        print(f"  ✅ Media ID {data['id']}: {data.get('source_url','')[:60]}")
        return data['id']
    else:
        print(f"  ❌ Upload media gagal: {r.status_code} - {r.text[:200]}")
        return None

def create_post(title, content, category_id, tags, slug, meta_desc, keyphrase, featured_media_id):
    """Buat post baru via REST API"""
    
    # Pastikan tags adalah array of strings (slugs)
    tag_slugs = tags if isinstance(tags, list) else tags.split(',')
    
    data = {
        "title": title,
        "content": content,
        "status": "draft",
        "slug": slug,
        "categories": [category_id],
        "tags": tag_slugs,
        "featured_media": featured_media_id,
        "meta": {
            "_yoast_wpseo_focuskw": keyphrase,
            "_yoast_wpseo_metadesc": meta_desc[:158]
        }
    }
    
    r = requests.post(
        f"{WP_URL}/posts",
        auth=(USER, APP_PASS),
        json=data
    )
    
    if r.status_code in (200, 201):
        post = r.json()
        print(f"  ✅ Post ID {post['id']}: {title[:50]}")
        return post['id']
    else:
        print(f"  ❌ Create post gagal: {r.status_code}")
        try:
            err = r.json()
            print(f"     {err.get('message','')[:200]}")
            code = err.get('code','')
            if code == 'term_exists':
                # Coba pake taxonomy term langsung
                print("     → Retry tanpa tags...")
                data['tags'] = []
                r2 = requests.post(
                    f"{WP_URL}/posts",
                    auth=(USER, APP_PASS),
                    json=data
                )
                if r2.status_code in (200, 201):
                    post2 = r2.json()
                    print(f"  ✅ Post ID {post2['id']} (tanpa tags): {title[:50]}")
                    return post2['id']
            elif code == 'rest_term_cannot_create':
                print("     → Slug tags mungkin belum ada, coba lewatkan...")
                # Skip tags dulu, nanti di-update
                del data['tags']
                r2 = requests.post(
                    f"{WP_URL}/posts",
                    auth=(USER, APP_PASS),
                    json=data
                )
                if r2.status_code in (200, 201):
                    post2 = r2.json()
                    print(f"  ✅ Post ID {post2['id']} (skip tags): {title[:50]}")
                    return post2['id']
        except:
            pass
        print(f"     {r.text[:500]}")
        return None

def main():
    json_path = "/home/mantapman/.hermes/profiles/atun/workspace/studiosoft-10-artikel.json"
    
    if not os.path.exists(json_path):
        print(f"❌ File {json_path} tidak ditemukan!")
        sys.exit(1)
    
    with open(json_path) as f:
        articles = json.load(f)
    
    print(f"📚 Loaded {len(articles)} articles\n")
    
    results = []
    
    for art in articles:
        print(f"\n{'='*60}")
        print(f"📝 [{art['id']}] {art['title']}")
        print(f"{'='*60}")
        
        # 1. Download + upload featured image
        img_url = art.get('featured_image_url', '')
        featured_id = None
        
        if img_url:
            print(f"  ⬇️ Download gambar: {img_url[:60]}...")
            img_data = download_image(img_url)
            if img_data:
                # Generate filename from slug
                slug = art.get('slug', f"artikel-{art['id']}")
                fname = f"{slug[:40]}.webp".replace('/', '-')
                
                alt = art.get('keyphrase', 'StudioSoft')
                featured_id = upload_media(img_data, fname, alt)
        
        # 2. Tambah WA Button ke konten
        content = art['content']
        content += '\n\n' + wa_button()
        
        # 3. Create post
        post_id = create_post(
            title=art['title'],
            content=content,
            category_id=art['category'],
            tags=art.get('tags', []),
            slug=art.get('slug', ''),
            meta_desc=art.get('meta_desc', ''),
            keyphrase=art.get('keyphrase', ''),
            featured_media_id=featured_id
        )
        
        if post_id:
            results.append({"id": art['id'], "post_id": post_id, "title": art['title']})
            print(f"  ✅ Sukses!")
        else:
            print(f"  ❌ Gagal!")
        
        # Rate limiting
        time.sleep(1)
    
    print(f"\n\n{'='*60}")
    print(f"📊 HASIL UPLOAD:")
    print(f"{'='*60}")
    for r in results:
        print(f"  ✅ [{r['id']}] Post ID {r['post_id']}: {r['title'][:50]}")
    print(f"\nTotal: {len(results)}/{len(articles)} sukses")

if __name__ == "__main__":
    main()
