#!/usr/bin/env python3
"""
Upload 5 artikel Nucleasoft (artikel 11-15) via WP REST API.
Menyertakan Yoast SEO meta, category, tags, dan featured image.
"""

import json
import os
import re
import sys
import time
import requests
from urllib.parse import urlparse
from requests.auth import HTTPBasicAuth

# === CONFIG ===
WP_URL = "https://www.otomasibisnispintar.com"
USER = "bambangbot"
APP_PASSWORD = "VvC3 wNRB GDGM Yywb Vr2h 8fFY"
ARTICLES_DIR = "/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles"
WA_NUMBER = "6285334199166"
WA_TEXT = "💬 Konsultasi Gratis via WhatsApp"
DEFAULT_CATEGORY = 8  # otomasi bisnis
AI_CATEGORY = 121     # AI

# Tag IDs (pre-fetched)
TAG_MAP = {
    "konsultan AI Surabaya": 54,
    "tips konsultan AI": None,
    "memilih konsultan AI": None,
    "konsultan IT Surabaya": None,
    "Nucleasoft": 34,
    "AI untuk bisnis": 52,
    "transformasi digital": 80,
    "solusi AI bisnis": 95,
    "otomasi bisnis": 9,
    "AI untuk UKM": 96,
    "AI untuk UMKM": 57,
    "konsultan otomasi bisnis": 26,
    "panduan otomasi bisnis": 19,
    "efisiensi bisnis": 12,
    "solusi AI": 95,
    "konsultan AI": 67,
    "bisnis modern": 138,
    "bisnis teknologi": 125,
    "efisiensi": 126,
    "digitalisasi bisnis": 17,
    "kecerdasan buatan": 90,
    "Nucleasoft Digital Indonesia": 22,
}

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

def get_featured_image_url(article_id, article_title):
    """Generate featured image URL — fallback ke dashboard image."""
    return "https://www.otomasibisnispintar.com/wp-content/uploads/2025/05/ai-analisis-data-bisnis.jpg"

def parse_markdown(filepath):
    """Parse markdown article file and extract metadata."""
    with open(filepath, 'r') as f:
        content = f.read()

    # Extract SEO metadata
    seo_title = re.search(r'\*\*SEO Title:\*\*\s*(.+?)\s*(?:\|.*)?$', content, re.MULTILINE)
    meta_desc = re.search(r'\*\*Meta Description:\*\*\s*(.+?)\s*\(', content, re.MULTILINE)
    slug = re.search(r'\*\*Slug:\*\*\s*(.+)', content)
    keyphrase = re.search(r'\*\*Focus Keyphrase:\*\*\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 ""
    category_str = category_line.group(1).strip() if category_line else ""
    tags_str = tags_line.group(1).strip() if tags_line else ""

    # Extract content between ## Konten and --- (Featured Image)
    konten_match = re.search(r'## Konten\n\n(.*?)(?:\n---\n|### Featured Image)', content, re.DOTALL)
    body = konten_match.group(1).strip() if konten_match else ""

    # Convert markdown to HTML (basic)
    body_html = markdown_to_html(body)

    # Get title from first H1
    title_match = re.search(r'# (.*?)\n', content)
    title = title_match.group(1).strip() if title_match else ""

    # Parse tags
    tags = [t.strip() for t in tags_str.split(",") if t.strip()]

    # Determine category
    category_id = DEFAULT_CATEGORY
    if "ai" in category_str.lower():
        category_id = AI_CATEGORY

    # Alt text
    alt_match = re.search(r'\*\*Alt text:\*\*\s*(.+?)(?:\n|$)', content)
    alt_text = alt_match.group(1).strip() if alt_match else ""

    # WA button at bottom if exists
    wa_match = re.search(r'https://wa\.me/(\d+)', content)
    wa_number = wa_match.group(1) if wa_match else WA_NUMBER

    return {
        "title": title,
        "seo_title": seo_title,
        "meta_desc": meta_desc,
        "slug": slug,
        "keyphrase": keyphrase,
        "category_id": category_id,
        "tags": tags,
        "body_html": body_html,
        "alt_text": alt_text,
        "wa_number": wa_number,
    }

def markdown_to_html(md):
    """Convert basic markdown to HTML for WP."""
    html = md

    # 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)

    # Checklist
    html = re.sub(r'- \[ \] (.+)', r'<p>☐ \1</p>', html)
    html = re.sub(r'- \[x\] (.+)', r'<p>☑ \1</p>', html)

    # Unordered list
    html = re.sub(r'^- (.+)$', r'<li>\1</li>', html, flags=re.MULTILINE)

    # Wrap consecutive <li> in <ul>
    html = re.sub(r'(<li>.*?</li>\n)+', r'<ul>\g<0></ul>\n', html)

    # Table (basic)
    html = re.sub(r'^\|(.+)\|$', r'<td>\1</td>', html, flags=re.MULTILINE)

    # Links
    html = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', html)

    # Image badges (WA button)
    html = re.sub(r'\[!\[([^\]]+)\]\([^)]+\)\]\(([^)]+)\)', r'<a href="\2" class="wa-button"><img src="\1" alt="WhatsApp"></a>', html)

    # WA badge alt fix
    html = re.sub(r'<img src=".*WA.*" alt="WhatsApp">', r'<a href="https://wa.me/' + WA_NUMBER + '?text=Halo%20Nucleasoft" class="wa-button" style="display:inline-block;background:#25D366;color:white;padding:12px 24px;border-radius:8px;font-weight:bold;margin:10px 0;">💬 Konsultasi Gratis via WhatsApp</a>', html)

    # Paragraph wrapping (lines that aren't HTML tags)
    lines = html.split('\n')
    result = []
    for line in lines:
        stripped = line.strip()
        if not stripped:
            continue
        if stripped.startswith('<h') or stripped.startswith('<ul') or stripped.startswith('<li') or stripped.startswith('</ul') or stripped.startswith('<a') or stripped.startswith('<p') or stripped.startswith('<td') or stripped.startswith('<table'):
            result.append(stripped)
        elif stripped.startswith('</'):
            result.append(stripped)
        else:
            result.append(f'<p>{stripped}</p>')
    html = '\n'.join(result)

    return html

def upload_post(meta):
    """Upload single post to WP via REST API."""
    # Build content with WA button
    content_html = meta['body_html']
    
    # Add WA button at the end if not already present
    if 'wa-button' not in content_html and 'whatsapp' not in content_html.lower():
        content_html += f'\n\n<p><a href="https://wa.me/{meta["wa_number"]}?text=Halo%20Nucleasoft" class="wa-button" style="display:inline-block;background:#25D366;color:white;padding:12px 24px;border-radius:8px;font-weight:bold;margin:10px 0;">💬 Konsultasi Gratis via WhatsApp</a></p>'

    # Resolve tag IDs
    tag_ids = []
    for t in meta['tags']:
        t = t.strip()
        existing = TAG_MAP.get(t)
        if existing:
            tag_ids.append(existing)
        # Create via API if not found? Skip for now, use existing only.

    # Always add Nucleasoft tag
    if 34 not in tag_ids:
        tag_ids.append(34)

    post_data = {
        "title": meta['title'],
        "content": content_html,
        "slug": meta['slug'],
        "status": "publish",
        "categories": [meta['category_id'], AI_CATEGORY] if meta['category_id'] != AI_CATEGORY else [AI_CATEGORY],
        "tags": tag_ids,
        "meta": {
            # Yoast SEO
            "_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"  Uploading: {meta['title']}")
    print(f"  Slug: {meta['slug']}")
    print(f"  Category: {meta['category_id']}")
    print(f"  Tags: {tag_ids}")
    print(f"  SEO Title: {meta['seo_title']}")
    print(f"  Meta Desc: {meta['meta_desc']}")
    print(f"  Keyphrase: {meta['keyphrase']}")

    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}")
        
        # Set Yoast SEO via meta update
        time.sleep(0.5)
        
        # Set featured image
        set_featured_image(post_id)
        
        return post_id
    else:
        print(f"  ❌ Error {resp.status_code}: {resp.text[:500]}")
        return None

def set_featured_image(post_id):
    """Set featured image from existing media or upload placeholder."""
    # Use existing media ID for dashboard image
    # Find media by slug
    media_resp = session.get(f"{WP_URL}/wp-json/wp/v2/media?per_page=5&search=dashboard")
    if media_resp.status_code == 200:
        media_items = media_resp.json()
        if media_items:
            media_id = media_items[0]['id']
            resp = session.post(f"{WP_URL}/wp-json/wp/v2/posts/{post_id}", json={
                "featured_media": media_id
            })
            if resp.status_code in (200, 201):
                print(f"  ✅ Featured image set (ID: {media_id})")
            else:
                print(f"  ⚠️ Featured image failed: {resp.text[:200]}")
        else:
            print(f"  ⚠️ No media found for featured image")
    else:
        print(f"  ⚠️ Media search failed: {media_resp.status_code}")

def main():
    files = [
        "11-konsultan-ai-surabaya-tips-memilih.md",
        "12-konsultan-ai-surabaya-solusi-bisnis.md",
        "13-konsultan-ai-surabaya-edukasi.md",
        "14-konsultan-ai-surabaya-langkah-transformasi.md",
        "15-konsultan-ai-surabaya-vs-ukm.md",
    ]

    print("=" * 60)
    print("UPLOAD ARTIKEL NUCLEASOFT — \"Konsultan AI Surabaya\"")
    print("=" * 60)

    for fname in files:
        filepath = os.path.join(ARTICLES_DIR, fname)
        print(f"\n📄 {fname}")
        print("-" * 40)
        
        try:
            meta = parse_markdown(filepath)
            post_id = upload_post(meta)
            if post_id:
                print(f"  ✅ Post ID: {post_id}")
            time.sleep(1)  # Rate limiting
        except Exception as e:
            print(f"  ❌ Error: {e}")
            import traceback
            traceback.print_exc()

    print("\n" + "=" * 60)
    print("SELESAI!")
    print("=" * 60)

if __name__ == "__main__":
    main()
