#!/usr/bin/env python3
"""
Publish 10 SEO articles to dasindonesia.com via WordPress REST API.
User: bambangbot
App Password: u3a1 G2pQ 3SWY f0zI OlGP YAjU
"""

import requests
from requests.auth import HTTPBasicAuth
import json
import sys
import re
import html

WP_URL = "https://dasindonesia.com/wp-json/wp/v2"
USER = "bambangbot"
APP_PASSWORD = "u3a1 G2pQ 3SWY f0zI OlGP YAjU"
AUTH = HTTPBasicAuth(USER, APP_PASSWORD)

# Kategori mapping (ganti ID sesuai kategori website)
CATEGORIES = {
    "default": [1],  # Uncategorized — ganti jika ada kategori spesifik
}

ARTICLES = []
current = None

def parse_articles(filepath):
    """Parse markdown file into article dicts."""
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Split by article separator
    sections = content.split('---\n\n')
    
    articles = []
    i = 0
    while i < len(sections):
        sec = sections[i].strip()
        if not sec:
            i += 1
            continue
        
        # Check if this section starts an article
        if sec.startswith('# Artikel'):
            art = parse_single_article(sec)
            if art:
                articles.append(art)
        i += 1
    
    return articles

def parse_single_article(text):
    """Extract fields from a single article section."""
    art = {}
    
    # Title
    m = re.search(r'# Artikel \d+: (.+)', text)
    art['title'] = m.group(1).strip() if m else "Untitled"
    
    # SEO Info
    seo_title = re.search(r'\*\*SEO Title:\*\* (.+)', text)
    art['seo_title'] = seo_title.group(1).strip() if seo_title else art['title']
    
    meta_desc = re.search(r'\*\*Meta Description:\*\* (.+)', text)
    art['meta_description'] = meta_desc.group(1).strip() if meta_desc else ""
    
    slug_m = re.search(r'\*\*Slug:\*\* (.+)', text)
    art['slug'] = slug_m.group(1).strip() if slug_m else ""
    
    keyphrase = re.search(r'\*\*Keyphrase:\*\* (.+)', text)
    art['keyphrase'] = keyphrase.group(1).strip() if keyphrase else ""
    
    kategori = re.search(r'\*\*Kategori:\*\* (.+)', text)
    art['kategori_raw'] = kategori.group(1).strip() if kategori else "default"
    
    # Alt text
    alt_m = re.search(r'\*\*Alt text:\*\* (.+)', text)
    art['alt_text'] = alt_m.group(1).strip() if alt_m else ""
    
    # Extract Konten - get everything between ## Konten and next ## (or ---)
    konten_match = re.search(r'## Konten\n\n(.+?)(?=\n---|\n# Artikel|\n###SELESAI###|\Z)', text, re.DOTALL)
    if konten_match:
        raw_content = konten_match.group(1).strip()
        # Convert markdown-style buttons to WP format
        art['content'] = convert_to_wp_blocks(raw_content)
    else:
        art['content'] = ""
    
    return art

def convert_to_wp_blocks(md_text):
    """Convert markdown content to WordPress HTML blocks."""
    html_parts = []
    
    lines = md_text.split('\n')
    i = 0
    
    while i < len(lines):
        line = lines[i]
        
        # Skip empty lines
        if not line.strip():
            i += 1
            continue
        
        # Heading H2
        if line.startswith('## ') and not line.startswith('### '):
            h_text = line[3:].strip()
            html_parts.append(f'<!-- wp:heading --><h2>{html.escape(h_text)}</h2><!-- /wp:heading -->')
        
        # Heading H3
        elif line.startswith('### '):
            h3_text = line[4:].strip()
            html_parts.append(f'<!-- wp:heading {{"level":3}} --><h3>{html.escape(h3_text)}</h3><!-- /wp:heading -->')
        
        # Heading H4
        elif line.startswith('#### '):
            h4_text = line[5:].strip()
            html_parts.append(f'<!-- wp:heading {{"level":4}} --><h4>{html.escape(h4_text)}</h4><!-- /wp:heading -->')
        
        # Unordered list
        elif line.strip().startswith('- **') or line.strip().startswith('- '):
            list_items = []
            while i < len(lines) and (lines[i].strip().startswith('- ') or lines[i].strip().startswith('- **') or lines[i].strip().startswith('* ')):
                item_text = lines[i].strip()
                if item_text.startswith('- '):
                    item_text = item_text[2:]
                elif item_text.startswith('* '):
                    item_text = item_text[2:]
                
                # Convert bold markers
                item_html = item_text.replace('**', '<strong>').replace('**', '</strong>')
                # Fix: replace in pairs
                item_html = re.sub(r'<strong>(.*?)</strong>', r'<strong>\1</strong>', item_html)
                # Handle bold properly
                parts = re.split(r'(\*\*.*?\*\*)', item_text)
                final_parts = []
                for p in parts:
                    if p.startswith('**') and p.endswith('**'):
                        final_parts.append(f'<strong>{p[2:-2]}</strong>')
                    else:
                        final_parts.append(p)
                item_html = ''.join(final_parts)
                
                list_items.append(f'<li>{item_html}</li>')
                i += 1
            html_parts.append(f'<!-- wp:list --><ul>{"".join(list_items)}</ul><!-- /wp:list -->')
            continue
        
        # Numbered list
        elif re.match(r'^\d+[\.\)] ', line.strip()):
            list_items = []
            while i < len(lines) and re.match(r'^\d+[\.\)] ', lines[i].strip()):
                item_text = re.sub(r'^\d+[\.\)] ', '', lines[i].strip())
                parts = re.split(r'(\*\*.*?\*\*)', item_text)
                final_parts = []
                for p in parts:
                    if p.startswith('**') and p.endswith('**'):
                        final_parts.append(f'<strong>{p[2:-2]}</strong>')
                    else:
                        final_parts.append(p)
                item_html = ''.join(final_parts)
                list_items.append(f'<li>{item_html}</li>')
                i += 1
            html_parts.append(f'<!-- wp:list {{"ordered":true}} --><ol>{"".join(list_items)}</ol><!-- /wp:list -->')
            continue
        
        # Horizontal rule
        elif line.strip() == '---':
            i += 1
            continue
        
        # WA Button / CTA
        elif 'wa.me/' in line or 'Konsultasi Gratis' in line or 'Hubungi DAS' in line:
            # Extract link content
            wa_match = re.search(r'https://wa\.me/([^\s?]+)', line)
            text_match = re.search(r'Konsultasi Gratis|Hubungi DAS', line)
            
            btn_text = "Konsultasi Gratis via WhatsApp"
            wa_url = "https://wa.me/6285242380789?text=Halo%20DAS%20Indonesia%20saya%20ingin%20konsultasi"
            
            if '0852-4243-0789' in line:
                wa_url = "https://wa.me/6285242380789?text=Halo%20DAS%20Indonesia%20saya%20ingin%20konsultasi"
            
            html_parts.append(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_url}">💬 {btn_text}</a></div><!-- /wp:button --></div><!-- /wp:buttons -->')
            i += 1
            continue
        
        # Regular paragraph
        else:
            para = line.strip()
            if para:
                # Convert inline bold
                parts = re.split(r'(\*\*.*?\*\*)', para)
                final_parts = []
                for p in parts:
                    if p.startswith('**') and p.endswith('**'):
                        final_parts.append(f'<strong>{p[2:-2]}</strong>')
                    else:
                        final_parts.append(p)
                para_html = ''.join(final_parts)
                
                # Convert inline links
                para_html = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', para_html)
                
                # Collect consecutive lines as one paragraph
                para_lines = [para_html]
                i += 1
                while i < len(lines) and lines[i].strip() and not lines[i].startswith('#') and not lines[i].strip().startswith('- ') and not re.match(r'^\d+[\.\)] ', lines[i].strip()) and not lines[i].strip().startswith('---'):
                    next_line = lines[i].strip()
                    parts = re.split(r'(\*\*.*?\*\*)', next_line)
                    final_parts = []
                    for p in parts:
                        if p.startswith('**') and p.endswith('**'):
                            final_parts.append(f'<strong>{p[2:-2]}</strong>')
                        else:
                            final_parts.append(p)
                    next_html = ''.join(final_parts)
                    next_html = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', next_html)
                    para_lines.append(next_html)
                    i += 1
                
                full_para = '<br>'.join(para_lines)
                html_parts.append(f'<!-- wp:paragraph --><p>{full_para}</p><!-- /wp:paragraph -->')
                continue
        
        i += 1
    
    return '\n'.join(html_parts)


def publish_article(art):
    """Publish a single article to WordPress."""
    # Determine categories
    cat_raw = art.get('kategori_raw', 'default').lower()
    
    # Convert meta description to Yoast format — we'll use excerpt
    excerpt = art.get('meta_description', '')
    
    data = {
        'title': art['title'],
        'content': art['content'],
        'slug': art['slug'],
        'status': 'publish',
        'categories': CATEGORIES.get(cat_raw, CATEGORIES['default']),
        'excerpt': excerpt,
        'meta': {
            '_yoast_wpseo_title': art.get('seo_title', art['title']),
            '_yoast_wpseo_metadesc': excerpt,
            '_yoast_wpseo_focuskw': art.get('keyphrase', ''),
        }
    }
    
    print(f"  Publishing: {art['title'][:60]}...")
    print(f"  Slug: {art['slug']}")
    print(f"  SEO Title: {art['seo_title'][:55]}")
    print(f"  Meta Desc: {excerpt[:100]}...")
    
    try:
        resp = requests.post(
            f"{WP_URL}/posts",
            json=data,
            auth=AUTH,
            timeout=30
        )
        
        if resp.status_code in (200, 201):
            post_id = resp.json().get('id')
            print(f"  ✅ Published! ID: {post_id} — {resp.json().get('link')}")
            return post_id
        else:
            print(f"  ❌ Failed: HTTP {resp.status_code}")
            print(f"     Response: {resp.text[:300]}")
            return None
    except Exception as e:
        print(f"  ❌ Error: {e}")
        return None


def main():
    filepath = "/home/mantapman/.hermes/profiles/atun/workspace/artikel-arlan/10-artikel-seo-das-bengkel.md"
    
    print("📖 Parsing articles...")
    articles = parse_articles(filepath)
    print(f"   Found {len(articles)} articles\n")
    
    if not articles:
        print("No articles found! Check file format.")
        return
    
    # Test connection
    print("🔌 Testing connection...")
    try:
        resp = requests.get(f"{WP_URL}/posts?per_page=1", auth=AUTH, timeout=15)
        print(f"   ✅ Connected (HTTP {resp.status_code})")
    except Exception as e:
        print(f"   ❌ Connection failed: {e}")
        return
    
    print(f"\n{'='*50}")
    print(f"📝 Publishing {len(articles)} articles...")
    print(f"{'='*50}\n")
    
    results = []
    for i, art in enumerate(articles, 1):
        print(f"[{i}/{len(articles)}]")
        post_id = publish_article(art)
        results.append((i, art['title'], post_id))
        print()
    
    # Summary
    print(f"{'='*50}")
    print("📊 SUMMARY")
    print(f"{'='*50}")
    success = sum(1 for r in results if r[2])
    failed = len(results) - success
    print(f"✅ Published: {success}/{len(articles)}")
    if failed:
        print(f"❌ Failed: {failed}")
    for i, title, pid in results:
        status = "✅" if pid else "❌"
        print(f"  {status} [{i}] {title[:50]}...")


if __name__ == "__main__":
    main()
