#!/usr/bin/env python3
"""
Upload 5 artikel Nucleasoft baru via WP REST API.
Dengan Yoast SEO, kategori, tags, dan featured image.
"""

import json, time, requests
from requests.auth import HTTPBasicAuth

WP_URL = "https://www.otomasibisnispintar.com"
USER = "bambangbot"
APP_PASSWORD = "VvC3 wNRB GDGM Yywb Vr2h 8fFY"
WA_LINK = "https://wa.me/6285334199166?text=Halo%20Nucleasoft"

# Featured images yang sudah ada di media library
FIMAGE_MAP = {
    "16-perusahaan-it-surabaya-ai": 3765,  # nuclea_ai_digital_1
    "17-tips-mencari-konsultan-ai-bisnis": 3659,  # konsultan-ai-it-2
    "18-konsultan-ai-untuk-umkm": 3761,  # nuclea_ai_team_1
    "19-konsultan-ai-surabaya-untuk-perusahaan": 3759,  # nuclea_ai_business_1
    "20-perusahaan-it-surabaya-spesialis-ai": 3755,  # nuclea_ai_dashboard_1
}

ALT_TEXT_MAP = {
    "16-perusahaan-it-surabaya-ai": "Perusahaan IT di Surabaya spesialis AI Nucleasoft Digital Indonesia teknologi digital",
    "17-tips-mencari-konsultan-ai-bisnis": "Tips mencari konsultan AI bisnis terpercaya di Surabaya konsultasi profesional Nucleasoft",
    "18-konsultan-ai-untuk-umkm": "Konsultan AI untuk UMKM solusi digital terjangkau Nucleasoft Digital Indonesia",
    "19-konsultan-ai-surabaya-untuk-perusahaan": "Konsultan AI di Surabaya untuk perusahaan Nucleasoft transformasi digital bisnis",
    "20-perusahaan-it-surabaya-spesialis-ai": "Perusahaan IT di Surabaya spesialis AI Nucleasoft dashboard digital analytics",
}

auth = HTTPBasicAuth(USER, APP_PASSWORD)
session = requests.Session()
session.auth = auth
session.headers.update({"Content-Type": "application/json"})

# Cek featured image alt text dari existing media
def update_alt_text(media_id, alt_text):
    resp = session.post(f"{WP_URL}/wp-json/wp/v2/media/{media_id}", json={"alt_text": alt_text})
    if resp.status_code in (200, 201):
        print(f"  ✅ Alt text media {media_id} updated: {alt_text[:50]}...")
    else:
        print(f"  ⚠️ Alt text update failed: {resp.status_code}")

def markdown_to_html(md):
    """Convert markdown to HTML"""
    html = md
    import re
    
    # Bold
    html = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', html)
    # Italic
    html = re.sub(r'\*(.+?)\*', r'<em>\1</em>', html)
    # H3
    html = re.sub(r'^### (.+)$', r'<h3>\1</h3>', html, flags=re.MULTILINE)
    # H2
    html = re.sub(r'^## (.+)$', r'<h2>\1</h2>', html, flags=re.MULTILINE)
    # Unordered list
    html = re.sub(r'^- (.+)$', r'<li>\1</li>', html, flags=re.MULTILINE)
    html = re.sub(r'(<li>.*?</li>\n)+', r'<ul>\g<0></ul>\n', html)
    # Links
    html = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', html)
    # WA button
    html = re.sub(r'💬.*$', f'💬 <a href="{WA_LINK}" style="display:inline-block;background:#25D366;color:white;padding:12px 24px;border-radius:8px;font-weight:bold;">Konsultasi Gratis via WhatsApp</a>', html, flags=re.MULTILINE)
    
    # Paragraph wrapping for non-html lines
    lines = html.split('\n')
    result = []
    for line in lines:
        stripped = line.strip()
        if not stripped:
            continue
        if any(stripped.startswith(t) for t in ['<h', '<ul', '<li', '</ul', '<a', '<p', '<td', '<table', '</']):
            result.append(stripped)
        else:
            result.append(f'<p>{stripped}</p>')
    
    return '\n'.join(result)

def parse_article(filepath):
    with open(filepath, 'r') as f:
        content = f.read()
    
    import re
    
    # Extract title from first H1
    title_match = re.search(r'^# (.+)$', content, re.MULTILINE)
    title = title_match.group(1).strip() if title_match else ""
    
    # Extract metadata
    seo_title = re.search(r'\*\*SEO Title:\*\*\s*(.+)', content)
    meta_desc = re.search(r'\*\*Meta Description:\*\*\s*(.+)', content)
    slug = re.search(r'\*\*Slug:\*\*\s*(.+)', content)
    keyphrase = re.search(r'\*\*Focus Keyphrase:\*\*\s*(.+)', content)
    alt_text = re.search(r'\*\*Alt text:\*\*\s*(.+)', content)
    category_line = re.search(r'\*\*Kategori:\*\*\s*(.+)', content)
    tags_line = re.search(r'\*\*Tags:\*\*\s*(.+)', content)
    
    seo_title = seo_title.group(1).strip() if seo_title else ""
    meta_desc = meta_desc.group(1).strip() if meta_desc else ""
    slug = slug.group(1).strip() if slug else ""
    keyphrase = keyphrase.group(1).strip() if keyphrase else ""
    alt_text = alt_text.group(1).strip() if alt_text else ""
    category_str = category_line.group(1).strip() if category_line else ""
    tags_str = tags_line.group(1).strip() if tags_line else ""
    
    # Extract body (between metadata and last "---")
    body_start = content.find("## ")
    if body_start == -1:
        body_start = content.find("---", content.find("Alt text:"))
        if body_start != -1:
            body_start = content.find("\n", body_start) + 1
    
    # Body sampai sebelum "--- ### Tentang Nucleasoft"
    about_marker = content.find("### Tentang Nucleasoft")
    if about_marker == -1:
        about_marker = len(content)
    
    if body_start > 0:
        body = content[body_start:about_marker].strip()
    else:
        body = ""
    
    body_html = markdown_to_html(body)
    
    # Tags
    tags_map = {
        "Nucleasoft": 34, "AI untuk bisnis": 52, "konsultan AI": 67,
        "perusahaan AI Indonesia": 77, "software house AI": 81,
        "bisnis teknologi": 125, "konsultan AI Surabaya": 54,
        "konsultan AI terpercaya": 62, "digitalisasi bisnis": 17,
        "efisiensi bisnis": 12, "AI untuk UMKM": 57, "AI untuk UKM": 96,
        "solusi AI": 95, "transformasi digital": 80, "bisnis modern": 138,
    }
    
    tags = [t.strip() for t in tags_str.split(",")] if tags_str else []
    tag_ids = [tags_map[t] for t in tags if t in tags_map]
    if 34 not in tag_ids:
        tag_ids.append(34)
    
    # Category
    category_id = 121  # AI default
    if "otomasi" in category_str.lower() and "ai" not in category_str.lower():
        category_id = 8
    
    return {
        "title": title, "seo_title": seo_title, "meta_desc": meta_desc,
        "slug": slug, "keyphrase": keyphrase, "alt_text": alt_text,
        "category_id": category_id, "tag_ids": tag_ids,
        "body_html": body_html,
    }

def upload_post(meta, fname_base):
    # Get featured image ID
    fimage_id = FIMAGE_MAP.get(fname_base)
    
    # Build content with WA CTA
    content_html = meta['body_html']
    content_html += f'\n\n<p style="text-align:center;margin-top:30px;"><a href="{WA_LINK}" style="display:inline-block;background:#25D366;color:white;padding:14px 28px;border-radius:8px;font-size:18px;font-weight:bold;text-decoration:none;">💬 Konsultasi Gratis via WhatsApp</a></p>'
    
    # Add Nucleasoft about
    content_html += f'\n\n<h3>Tentang Nucleasoft</h3>\n<p>Nucleasoft Digital Indonesia adalah <strong>{meta["keyphrase"]}</strong> yang berkomitmen membantu perusahaan dan UKM di seluruh Indonesia untuk mengadopsi Artificial Intelligence secara strategis. Dengan pendekatan bertahap dan solusi yang scalable, Nucleasoft siap menjadi mitra transformasi digital Anda.</p>\n<p>Kunjungi <a href="https://www.otomasibisnispintar.com">www.otomasibisnispintar.com</a> untuk informasi lebih lanjut.</p>'
    
    post_data = {
        "title": meta['title'],
        "content": content_html,
        "slug": meta['slug'],
        "status": "publish",
        "categories": [meta['category_id']],
        "tags": meta['tag_ids'],
        "featured_media": fimage_id,
        "meta": {
            "_yoast_wpseo_title": meta['seo_title'],
            "_yoast_wpseo_metadesc": meta['meta_desc'],
            "_yoast_wpseo_focuskw": meta['keyphrase'],
            "_yoast_wpseo_opengraph-title": meta['seo_title'],
            "_yoast_wpseo_opengraph-description": meta['meta_desc'],
            "_yoast_wpseo_twitter-title": meta['seo_title'],
            "_yoast_wpseo_twitter-description": meta['meta_desc'],
        }
    }
    
    print(f"\n📤 Uploading: {meta['title']}")
    print(f"   Slug: {meta['slug']}")
    print(f"   Keyphrase: {meta['keyphrase']}")
    print(f"   SEO Title: {meta['seo_title']}")
    print(f"   Category: {meta['category_id']}, Tags: {meta['tag_ids']}")
    print(f"   Featured: {fimage_id}")
    
    resp = session.post(f"{WP_URL}/wp-json/wp/v2/posts", json=post_data)
    
    if resp.status_code in (200, 201):
        post_id = resp.json()['id']
        print(f"   ✅ Published! ID: {post_id}")
        
        # Update alt text for featured image
        if fimage_id and meta['alt_text']:
            alt_key = fname_base
            if alt_key in ALT_TEXT_MAP:
                update_alt_text(fimage_id, ALT_TEXT_MAP[alt_key])
        
        return post_id
    else:
        print(f"   ❌ Error {resp.status_code}: {resp.text[:300]}")
        return None

def main():
    articles = [
        ("16-perusahaan-it-surabaya-ai.md", "16-perusahaan-it-surabaya-ai"),
        ("17-tips-mencari-konsultan-ai-bisnis.md", "17-tips-mencari-konsultan-ai-bisnis"),
        ("18-konsultan-ai-untuk-umkm.md", "18-konsultan-ai-untuk-umkm"),
        ("19-konsultan-ai-surabaya-untuk-perusahaan.md", "19-konsultan-ai-surabaya-untuk-perusahaan"),
        ("20-perusahaan-it-surabaya-spesialis-ai.md", "20-perusahaan-it-surabaya-spesialis-ai"),
    ]
    
    base_dir = "/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles"
    
    print("=" * 60)
    print("UPLOAD 5 ARTIKEL NUCLEASOFT — Batch 4")
    print("=" * 60)
    
    for fname, fname_base in articles:
        filepath = f"{base_dir}/{fname}"
        print(f"\n📄 {fname}")
        print("-" * 40)
        
        try:
            meta = parse_article(filepath)
            post_id = upload_post(meta, fname_base)
            time.sleep(1.5)
        except Exception as e:
            print(f"  ❌ Error: {e}")
            import traceback
            traceback.print_exc()
    
    print("\n" + "=" * 60)
    print("✅ SELESAI!")
    print("=" * 60)

if __name__ == "__main__":
    main()
