#!/usr/bin/env python3
"""Add WA button to articles missing it - Nucleasoft"""
import json, urllib.request, urllib.error, base64

WP_URL = "https://www.otomasibisnispintar.com"
USER = "Wati"
PASS = "wgwl SCV1 LDNv jl5E Z2Di oua5"
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = "Mozilla/5.0"

WA_LINK = 'https://wa.me/6285334199166?text=Saya%20ingin%20konsultasi%20tentang%20otomasi%20bisnis'
WA_BUTTON = f'<!-- wp:buttons --><div class="wp-block-buttons"><!-- wp:button --><div class="wp-block-button"><a class="wp-block-button__link has-white-color has-vivid-green-cyan-background-color has-text-color has-background has-link-color wp-element-button" href="{WA_LINK}">💬 Konsultasi Gratis via WhatsApp</a></div><!-- /wp:button --></div><!-- /wp:buttons -->'

def wp_get(url):
    req = urllib.request.Request(url, headers={"Authorization": f"Basic {AUTH}", "User-Agent": UA})
    return json.loads(urllib.request.urlopen(req).read())

def wp_post(url, data):
    req = urllib.request.Request(url,
        data=json.dumps(data).encode(),
        headers={"Authorization": f"Basic {AUTH}", "Content-Type": "application/json", "User-Agent": UA},
        method="POST")
    return json.loads(urllib.request.urlopen(req).read())

# Get all publish posts
posts = wp_get(f"{WP_URL}/wp-json/wp/v2/posts?per_page=100&status=publish")

# Also get remaining pages
page = 1
while len(posts) % 100 == 0 and len(posts) > 0:
    page += 1
    more = wp_get(f"{WP_URL}/wp-json/wp/v2/posts?per_page=100&status=publish&page={page}")
    if not more:
        break
    posts.extend(more)

count = 0
for p in posts:
    post_id = p['id']
    raw = p.get('content', {}).get('raw', p.get('content', {}).get('rendered', ''))
    
    # Check if already has WA button with our number
    has_wa_new = '6285334199166' in raw
    
    # Check if has WA button at all
    has_wa_any = 'wa.me' in raw.lower() or 'whatsapp' in raw.lower()
    
    if has_wa_new:
        print(f"  ✅ Already has WA (new number) - {p['title']['rendered'][:50]}")
        continue
    
    if has_wa_any:
        # Replace old WA link with new one
        import re
        updated = re.sub(
            r'https?://wa\.me/\d+[^\s"\'<>]*',
            WA_LINK,
            raw
        )
        # Also update button text if needed
        updated = updated.replace('💬 Chat WhatsApp', '💬 Konsultasi Gratis via WhatsApp')
        updated = updated.replace('Konsultasi via WhatsApp', '💬 Konsultasi Gratis via WhatsApp')
        updated = updated.replace('Hubungi Kami via WhatsApp', '💬 Konsultasi Gratis via WhatsApp')
        
        if updated != raw:
            wp_post(f"{WP_URL}/wp-json/wp/v2/posts/{post_id}", {"content": updated})
            print(f"  🔄 Updated WA number - {p['title']['rendered'][:50]}")
            count += 1
        else:
            print(f"  ⚠️ Has WA but couldn't update - {p['title']['rendered'][:50]}")
        continue
    
    # No WA button at all - add at the end
    updated = raw.rstrip() + '\n' + WA_BUTTON
    wp_post(f"{WP_URL}/wp-json/wp/v2/posts/{post_id}", {"content": updated})
    print(f"  ➕ Added WA button - {p['title']['rendered'][:50]}")
    count += 1

print(f"\n✅ Total updated: {count} articles")
