#!/usr/bin/env python3
"""
Publish 5 SEO articles to dasindonesia.com via WordPress REST API.
Upload featured images as WebP 1000x567, set alt text, publish all.
"""
import requests
from requests.auth import HTTPBasicAuth
import json
import sys
import os
import re

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

IMG_DIR = "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/featured-images"

def get_or_create_category(name):
    """Get category ID by name, create if not exists."""
    r = requests.get(f"{WP_URL}/categories", params={"search": name}, auth=AUTH)
    r.raise_for_status()
    cats = r.json()
    for cat in cats:
        if cat["name"].lower() == name.lower():
            print(f"  Found category '{name}' -> ID {cat['id']}")
            return cat["id"]
    # Create
    r = requests.post(f"{WP_URL}/categories", json={"name": name}, auth=AUTH)
    if r.status_code == 201:
        print(f"  Created category '{name}' -> ID {r.json()['id']}")
        return r.json()["id"]
    print(f"  WARN: Cannot get/create category '{name}', using default (1)")
    return 1

def upload_image(filepath, alt_text, filename):
    """Upload image to WP media library, return media ID."""
    with open(filepath, "rb") as f:
        r = requests.post(
            f"{WP_URL}/media",
            auth=AUTH,
            files={"file": (filename, f, "image/webp")},
            data={
                "alt_text": alt_text,
                "caption": alt_text,
            }
        )
    if r.status_code in (200, 201):
        media = r.json()
        print(f"  Uploaded image -> ID {media['id']}")
        return media["id"], media["source_url"]
    else:
        print(f"  ERROR uploading image: {r.status_code} {r.text[:200]}")
        return None, None

def parse_article(md_path):
    """Parse markdown file into article data."""
    with open(md_path, "r") as f:
        text = f.read()
    
    # Title
    m = re.search(r'^# Artikel \d+: (.+)', text, re.MULTILINE)
    title = m.group(1).strip() if m else "Untitled"
    
    # SEO fields
    seo = {}
    for field in ["SEO Title", "Meta Description", "Slug", "Keyphrase", "Kategori"]:
        m = re.search(r'\*\*' + field + r':\*\* (.+)', text)
        seo[field] = m.group(1).strip() if m else ""
    
    # Alt text
    m = re.search(r'\*\*Alt text:\*\* (.+)', text)
    alt_text = m.group(1).strip() if m else ""
    
    # Featured image filename
    m = re.search(r'\*\*File name:\*\* (.+)', text)
    fname = m.group(1).strip() if m else ""
    
    # Content (between ## Konten and end or next ##)
    konten_match = re.search(r'## Konten\n\n(.+?)(?=\n---|\n# Artikel|\Z)', text, re.DOTALL)
    content_raw = konten_match.group(1).strip() if konten_match else ""
    
    # Convert to WP Gutenberg HTML
    content_html = convert_to_wp_html(content_raw)
    
    return {
        "title": title,
        "seo_title": seo["SEO Title"],
        "meta_description": seo["Meta Description"],
        "slug": seo["Slug"],
        "keyphrase": seo["Keyphrase"],
        "kategori": seo["Kategori"],
        "alt_text": alt_text,
        "fname": fname,
        "content": content_html,
    }

def convert_to_wp_html(md_text):
    """Convert markdown-ish content to WP HTML with Gutenberg blocks."""
    lines = md_text.split("\n")
    blocks = []
    
    for line in lines:
        stripped = line.strip()
        if not stripped:
            blocks.append("")
            continue
        
        # Headings
        if stripped.startswith("### "):
            blocks.append(f"<h3>{stripped[4:]}</h3>")
        elif stripped.startswith("## "):
            blocks.append(f"<h2>{stripped[3:]}</h2>")
        elif stripped.startswith("# "):
            blocks.append(f"<h1>{stripped[2:]}</h1>")
        # Blockquote
        elif stripped.startswith("> "):
            blocks.append(f"<blockquote>{stripped[2:]}</blockquote>")
        # Bold/italic list item
        elif stripped.startswith("- **") or stripped.startswith("* **"):
            blocks.append(f"<li>{stripped.lstrip('-* ')}</li>")
        # Numbered list item
        elif re.match(r'^\d+[.)]\s', stripped):
            text = re.sub(r'^\d+[.)]\s', '', stripped)
            blocks.append(f"<li>{text}</li>")
        # Regular bold item
        elif stripped.startswith("**") and stripped.endswith("**"):
            blocks.append(f"<p><strong>{stripped.strip('*')}</strong></p>")
        # Regular paragraph
        else:
            # Process inline bold, italic, links
            processed = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', stripped)
            processed = re.sub(r'\*(.+?)\*', r'<em>\1</em>', processed)
            processed = re.sub(r'\[(.+?)\]\((.+?)\)', r'<a href="\2">\1</a>', processed)
            blocks.append(f"<p>{processed}</p>")
    
    # Wrap in Gutenberg blocks
    html = ""
    in_list = False
    for block in blocks:
        if block.startswith("<li>"):
            if not in_list:
                html += "<ul>\n"
                in_list = True
            html += f"  {block}\n"
        else:
            if in_list:
                html += "</ul>\n"
                in_list = False
            if block == "":
                html += "\n"
            else:
                html += f"{block}\n"
    if in_list:
        html += "</ul>\n"
    
    return html

def create_post(article, category_id, media_id):
    """Create WordPress post with Yoast meta."""
    post = {
        "title": article["title"],
        "content": article["content"],
        "slug": article["slug"],
        "status": "publish",
        "categories": [category_id],
        "featured_media": media_id,
        "meta": {
            "_yoast_wpseo_title": article["seo_title"],
            "_yoast_wpseo_metadesc": article["meta_description"],
            "_yoast_wpseo_focuskw": article["keyphrase"],
        }
    }
    
    r = requests.post(f"{WP_URL}/posts", json=post, auth=AUTH)
    if r.status_code in (200, 201):
        data = r.json()
        print(f"  PUBLISHED: {data['link']}")
        return True
    else:
        print(f"  ERROR: {r.status_code} - {r.text[:500]}")
        return False

def main():
    articles_data = [
        {
            "md": "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/artikel-1-transmisi-matic.md",
            "img": os.path.join(IMG_DIR, "artikel-1-transmisi-matic.webp"),
            "img_filename": "cara-merawat-transmisi-matic-mobil.webp",
        },
        {
            "md": "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/artikel-2-ac-mobil.md",
            "img": os.path.join(IMG_DIR, "artikel-2-ac-mobil.webp"),
            "img_filename": "penyebab-ac-mobil-tidak-dingin.webp",
        },
        {
            "md": "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/artikel-3-balancing-spooring.md",
            "img": os.path.join(IMG_DIR, "artikel-3-balancing-spooring.webp"),
            "img_filename": "pentingnya-balancing-dan-spooring-mobil.webp",
        },
        {
            "md": "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/artikel-4-biaya-servis-bmw.md",
            "img": os.path.join(IMG_DIR, "artikel-4-biaya-servis-bmw.webp"),
            "img_filename": "biaya-servis-mobil-bmw.webp",
        },
        {
            "md": "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das/artikel-5-memilih-ban-mobil.md",
            "img": os.path.join(IMG_DIR, "artikel-5-memilih-ban-mobil.webp"),
            "img_filename": "tips-memilih-ban-mobil-untuk-jalan-indonesia.webp",
        },
    ]
    
    success = 0
    for i, art in enumerate(articles_data, 1):
        print(f"\n{'='*60}")
        print(f"ARTIKEL {i}")
        print(f"{'='*60}")
        
        # Parse
        article = parse_article(art["md"])
        print(f"  Title: {article['title']}")
        print(f"  Slug: {article['slug']}")
        print(f"  Keyphrase: {article['keyphrase']}")
        print(f"  Kategori: {article['kategori']}")
        
        # Get/create category
        cat_id = get_or_create_category(article["kategori"])
        
        # Upload image
        if os.path.exists(art["img"]):
            media_id, media_url = upload_image(art["img"], article["alt_text"], art["img_filename"])
        else:
            print(f"  WARN: Image not found: {art['img']}")
            media_id = None
        
        if media_id:
            # Create post
            if create_post(article, cat_id, media_id):
                success += 1
        else:
            print(f"  SKIPPED: No featured image")
    
    print(f"\n{'='*60}")
    print(f"DONE: {success}/{len(articles_data)} articles published")
    print(f"{'='*60}")

if __name__ == "__main__":
    main()
