#!/usr/bin/env python3
"""Publish 10 LEIT articles to leitsurabaya.com with Gutenberg blocks"""
import requests, base64, json, os, re, time, sys

DOMAIN = "https://leitsurabaya.com"
USER = "bambangbot"
APP_PW = None  # diisi dari input

HEADING_REGEX = re.compile(r'^(\d+)\.\s+(.+)$')
BOLD_REGEX = re.compile(r'\*\*(.+?)\*\*')
LOCATION_REGEX = re.compile(r'📍\s*(.+)')

def get_app_password():
    global APP_PW
    if not APP_PW:
        APP_PW = input("Masukkan App Password untuk leitsurabaya.com: ").strip()
    return APP_PW

def parse_listikel_to_blocks(text):
    """Parse listikel markdown ke Gutenberg blocks"""
    lines = text.strip().split('\n')
    blocks = []
    
    for i, line in enumerate(lines):
        line_stripped = line.strip()
        if not line_stripped:
            continue
        
        # Skip separator lines
        if line_stripped.startswith('——'):
            blocks.append({"type": "core/separator"})
            continue
        
        # Header/footer contact info
        if line_stripped.startswith('LEIT') or line_stripped.startswith('📍'):
            continue
        if line_stripped.startswith('🌐'):
            continue
        
        # Bold heading line at top (judul hook)
        if i == 0 and len(line_stripped) > 20:
            blocks.append({"type": "core/heading", "attrs": {"level": 2, "content": line_stripped}})
            continue
        
        # Numbered items: "1. Teks..."
        m = HEADING_REGEX.match(line_stripped)
        if m:
            num, content = m.group(1), m.group(2)
            # Bold parts in content
            content = BOLD_REGEX.sub(r'<strong>\1</strong>', content)
            html = f'<h3>{num}. {content}</h3>'
            blocks.append({"type": "core/heading", "attrs": {"level": 3, "content": f"{num}. {content}"}})
            continue
        
        # Bullet items
        if line_stripped.startswith('- '):
            blocks.append({"type": "core/list-item", "attrs": {"content": line_stripped[2:]}})
            continue
        
        # Regular paragraph
        content = BOLD_REGEX.sub(r'<strong>\1</strong>', line_stripped)
        blocks.append({"type": "core/paragraph", "attrs": {"content": line_stripped}})
    
    return blocks

def make_post(title, md_content, category_id=1):
    auth = base64.b64encode(f"{USER}:{get_app_password()}".encode()).decode()
    headers = {
        "Authorization": f"Basic {auth}",
        "Content-Type": "application/json",
    }
    
    # Parse blocks from content
    blocks = parse_listikel_to_blocks(md_content)
    
    # Convert to HTML
    html_parts = []
    for blk in blocks:
        if blk["type"] == "core/paragraph":
            html_parts.append(f"<p>{blk['attrs']['content']}</p>")
        elif blk["type"] == "core/heading":
            lvl = blk["attrs"]["level"]
            html_parts.append(f"<h{lvl}>{blk['attrs']['content']}</h{lvl}>")
        elif blk["type"] == "core/list-item":
            html_parts.append(f"<li>{blk['attrs']['content']}</li>")
        elif blk["type"] == "core/separator":
            html_parts.append("<hr />")
    
    # Wrap lists properly
    html_content = '\n'.join(html_parts)
    
    # Build Gutenberg comment blocks
    gb_html = "<!-- wp:paragraph -->\n" + html_content + "\n<!-- /wp:paragraph -->"
    
    data = {
        "title": title,
        "content": gb_html,
        "status": "publish",
        "categories": [category_id],
    }
    
    resp = requests.post(
        f"{DOMAIN}/wp-json/wp/v2/posts",
        headers=headers,
        json=data,
        timeout=15
    )
    
    return resp.status_code, resp.json() if resp.status_code in (200, 201) else resp.text

if __name__ == "__main__":
    print("READY — tinggal jalankan dengan App Password")
