#!/usr/bin/env python3
"""
Publish 5 Honda articles to dasindonesia.com via WordPress REST API.
With feature image upload (Honda logo on dark background).
"""

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

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

# Fixed: tag HONDA + category HONDA
CATEGORY_HONDA = 7  # HONDA category
TAGS = {
    "honda": 359,        # bengkel Honda
    "overhaul": None,    # need to find/create
    "tips": 623,         # Tips Teknis
    "servis": None,
    "vtec": None,
    "perawatan": 604,    # Perawatan
    "perawatanmobil": 622, # Perawatan Mobil
}

def find_or_create_tag(name, slug=None):
    """Find tag by name, create if not exists."""
    if not slug:
        slug = name.lower().replace(' ', '-')
    
    resp = requests.get(f"{WP_URL}/tags", params={"search": name}, auth=AUTH, timeout=15)
    if resp.status_code == 200:
        tags = resp.json()
        for t in tags:
            if t['name'].lower() == name.lower():
                return t['id']
    
    # Create new tag
    resp = requests.post(f"{WP_URL}/tags", json={"name": name, "slug": slug}, auth=AUTH, timeout=15)
    if resp.status_code in (200, 201):
        tag_id = resp.json()['id']
        print(f"  🏷️ Created tag '{name}' (ID: {tag_id})")
        return tag_id
    return None

def upload_image(filepath, alt_text="Honda logo"):
    """Upload image to WordPress media library."""
    filename = os.path.basename(filepath)
    with open(filepath, 'rb') as f:
        files = {'file': (filename, f, 'image/png')}
        data = {'alt': alt_text, 'caption': alt_text}
        resp = requests.post(f"{WP_URL}/media", files=files, data=data, auth=AUTH, timeout=30)
    
    if resp.status_code in (200, 201):
        media_id = resp.json()['id']
        media_url = resp.json()['source_url']
        print(f"  🖼️ Image uploaded! ID: {media_id}, URL: {media_url}")
        return media_id, media_url
    else:
        print(f"  ❌ Image upload failed: HTTP {resp.status_code}")
        return None, None

def extract_article_data(filename):
    """Extract metadata and content from a markdown article file."""
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # Title (first H1)
    title_match = re.match(r'^# (.+)', content)
    title = title_match.group(1).strip() if title_match else "Untitled"
    
    # Meta description
    meta_match = re.search(r'\*\*Meta Description:\*\*\s*(.+?)(?:\n|$)', content)
    meta_desc = meta_match.group(1).strip() if meta_match else ""
    
    # Generate slug from title
    slug = title.lower()
    slug = re.sub(r'[^\w\s-]', '', slug)
    slug = re.sub(r'[-\s]+', '-', slug).strip('-')
    
    # Focus keyphrase = "Honda" + first meaningful noun
    keyphrase = "mobil Honda"
    
    # Build article tags based on content
    article_tags = [TAGS['honda']]
    content_lower = content.lower()
    if 'overhaul' in content_lower:
        article_tags.append(TAGS.get('overhaul', TAGS['honda']))
    if 'vtec' in content_lower:
        article_tags.append(TAGS.get('vtec', TAGS['honda']))
    if 'servis' in content_lower or 'perawatan' in content_lower:
        article_tags.append(TAGS['perawatan'])
        article_tags.append(TAGS['perawatanmobil'])
    article_tags.append(TAGS['tips'])
    
    # Clean tags (remove None, dedupe)
    article_tags = list(set(t for t in article_tags if t))
    
    # Convert content (remove meta description line, keep body for WP block conversion)
    body = content
    # Remove the meta description line
    body = re.sub(r'\*\*Meta Description:\*\*.+?\n', '', body)
    
    # Convert to WP blocks
    wp_content = convert_to_wp_blocks(body)
    
    return {
        'title': title,
        'slug': slug,
        'meta_description': meta_desc,
        'keyphrase': keyphrase,
        'content': wp_content,
        'tags': article_tags,
        'categories': [CATEGORY_HONDA],
    }

def convert_to_wp_blocks(md_text):
    """Convert markdown to WordPress HTML blocks."""
    html_parts = []
    lines = md_text.split('\n')
    i = 0
    
    while i < len(lines):
        line = lines[i]
        
        if not line.strip():
            i += 1
            continue
        
        # H2
        if line.startswith('## '):
            h_text = line[3:].strip()
            html_parts.append(f'<!-- wp:heading --><h2>{html.escape(h_text)}</h2><!-- /wp: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 -->')
        
        # 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('- '):
            list_items = []
            while i < len(lines) and (lines[i].strip().startswith('- ') or lines[i].strip().startswith('* ')):
                raw = lines[i].strip()
                if raw.startswith('- '): raw = raw[2:]
                elif raw.startswith('* '): raw = raw[2:]
                # Convert bold
                raw = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', raw)
                list_items.append(f'<li>{raw}</li>')
                i += 1
            html_parts.append(f'<!-- wp:list --><ul>{"".join(list_items)}</ul><!-- /wp:list -->')
            continue
        
        # Ordered list
        elif re.match(r'^\d+[\.\)] ', line.strip()):
            list_items = []
            while i < len(lines) and re.match(r'^\d+[\.\)] ', lines[i].strip()):
                raw = re.sub(r'^\d+[\.\)] ', '', lines[i].strip())
                raw = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', raw)
                list_items.append(f'<li>{raw}</li>')
                i += 1
            html_parts.append(f'<!-- wp:list {{"ordered":true}} --><ol>{"".join(list_items)}</ol><!-- /wp:list -->')
            continue
        
        # Table (simple pipe table)
        elif '|' in line and line.strip().startswith('|'):
            table_rows = []
            while i < len(lines) and '|' in lines[i] and lines[i].strip().startswith('|'):
                row = lines[i].strip()
                cells = [c.strip() for c in row.split('|')[1:-1]]
                # Skip separator row
                if all(re.match(r'^-+$', c) for c in cells):
                    i += 1
                    continue
                table_rows.append(cells)
                i += 1
            
            if table_rows:
                html_table = '<figure class="wp-block-table"><table>'
                # Header (first row)
                html_table += '<thead><tr>'
                for c in table_rows[0]:
                    html_table += f'<th>{c}</th>'
                html_table += '</tr></thead>'
                # Body
                if len(table_rows) > 1:
                    html_table += '<tbody>'
                    for row in table_rows[1:]:
                        html_table += '<tr>'
                        for c in row:
                            html_table += f'<td>{c}</td>'
                        html_table += '</tr>'
                    html_table += '</tbody>'
                html_table += '</table></figure>'
                html_parts.append(f'<!-- wp:table -->{html_table}<!-- /wp:table -->')
            continue
        
        # Horizontal rule or divider
        elif line.strip() == '---':
            i += 1
            continue
        
        # Regular paragraph (collect consecutive text lines)
        else:
            para_lines = []
            while i < len(lines):
                l = lines[i]
                # Stop at heading, list, table, hr, meta info
                if (l.startswith('#') or l.strip().startswith('- ') or 
                    re.match(r'^\d+[\.\)] ', l.strip()) or 
                    l.strip() == '---' or not l.strip()):
                    break
                para_lines.append(l.strip())
                i += 1
            
            if para_lines:
                full_text = '<br>'.join(para_lines)
                full_text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', full_text)
                full_text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', full_text)
                html_parts.append(f'<!-- wp:paragraph --><p>{full_text}</p><!-- /wp:paragraph -->')
            continue
        
        i += 1
    
    return '\n'.join(html_parts)

def publish_article(art, feature_image_id):
    """Publish a single article to WordPress."""
    data = {
        'title': art['title'],
        'content': art['content'],
        'slug': art['slug'],
        'status': 'publish',
        'categories': art['categories'],
        'tags': art['tags'],
        'excerpt': art['meta_description'],
        'featured_media': feature_image_id,
        'meta': {
            '_yoast_wpseo_title': art['title'],
            '_yoast_wpseo_metadesc': art['meta_description'],
            '_yoast_wpseo_focuskw': art['keyphrase'],
        }
    }
    
    print(f"  📝 Publishing: {art['title'][:70]}...")
    print(f"  🔖 Slug: {art['slug']}")
    print(f"  🏷️ Tags: {art['tags']}")
    print(f"  📂 Categories: {art['categories']}")
    
    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')
            link = resp.json().get('link')
            print(f"  ✅ Published! ID: {post_id}")
            print(f"  🔗 {link}")
            return post_id, link
        else:
            print(f"  ❌ Failed: HTTP {resp.status_code}")
            print(f"     Response: {resp.text[:500]}")
            return None, None
    except Exception as e:
        print(f"  ❌ Error: {e}")
        return None, None


def main():
    base = "/home/mantapman/.hermes/profiles/atun/workspace"
    files = [
        f"{base}/das_artikel_honda_1.md",
        f"{base}/das_artikel_honda_2.md",
        f"{base}/das_artikel_honda_3.md",
        f"{base}/das_artikel_honda_4.md",
        f"{base}/das_artikel_honda_5.md",
    ]
    feature_image = f"{base}/das_honda_feature.png"
    
    print("=" * 60)
    print("🚗 DAS HONDA — Publish 5 Artikel ke dasindonesia.com")
    print("=" * 60)
    
    # Test connection
    print("\n🔌 Testing connection to WordPress...")
    try:
        resp = requests.get(f"{WP_URL}", auth=AUTH, timeout=15)
        print(f"   ✅ Connected (HTTP {resp.status_code})")
    except Exception as e:
        print(f"   ❌ Connection failed: {e}")
        return
    
    # Find/create tags
    print("\n🏷️ Syncing tags...")
    TAGS['overhaul'] = find_or_create_tag("Overhaul Mesin", "overhaul-mesin")
    TAGS['servis'] = find_or_create_tag("Servis Honda", "servis-honda")
    TAGS['vtec'] = find_or_create_tag("VTEC", "vtec")
    
    # Upload feature image
    print("\n🖼️ Uploading feature image...")
    feature_id, feature_url = upload_image(feature_image, "Logo Honda — DAS Bengkel Indonesia Spesialis Engine Overhaul")
    if not feature_id:
        print("⚠️  Feature image upload failed, proceeding without featured image")
    
    # Parse and publish articles
    print(f"\n📖 Parsing {len(files)} articles...")
    articles = []
    for f in files:
        if os.path.exists(f):
            art = extract_article_data(f)
            articles.append(art)
            print(f"   ✅ {art['title'][:60]}...")
        else:
            print(f"   ❌ File not found: {f}")
    
    print(f"\n{'='*60}")
    print(f"📝 Publishing {len(articles)} articles...")
    print(f"{'='*60}\n")
    
    results = []
    for i, art in enumerate(articles):
        print(f"[{i+1}/{len(articles)}]")
        post_id, link = publish_article(art, feature_id)
        results.append((i+1, art['title'], post_id, link))
        print()
        time.sleep(1)  # Rate limiting
    
    # Summary
    print(f"{'='*60}")
    print("📊 SUMMARY")
    print(f"{'='*60}")
    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}")
    print()
    for num, title, pid, link in results:
        status = "✅" if pid else "❌"
        print(f"  {status} [{num}] {title[:65]}")
        if link:
            print(f"     {link}")
    print()
    
    if success == len(articles):
        print("🎉 Semua artikel Honda berhasil dipublikasikan!")
    else:
        print(f"⚠️  {failed} artikel gagal. Cek log di atas.")


if __name__ == "__main__":
    main()
