#!/usr/bin/env python3
"""Upload 10 articles Nucleasoft — AI Consultant Surabaya"""
import json, urllib.request, base64, re, html

WP_URL = "https://www.otomasibisnispintar.com"
USER = "Wati"
PASS = "wgwl SCV1 LDNv jl5E Z2Di oua5"

auth_str = base64.b64encode(f"{USER}:{PASS}".encode()).decode()

def wp_post(title, content, slug, excerpt, category_id, tags_ids, status="publish"):
    data = json.dumps({
        "title": title,
        "content": content,
        "slug": slug,
        "excerpt": excerpt,
        "status": status,
        "categories": [category_id],
        "tags": tags_ids,
    }).encode("utf-8")

    req = urllib.request.Request(
        f"{WP_URL}/wp-json/wp/v2/posts",
        data=data,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Basic {auth_str}",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
        }
    )
    try:
        resp = urllib.request.urlopen(req)
        result = json.loads(resp.read())
        print(f"✅ POST {result['id']} | {result['link']}")
        return result
    except urllib.error.HTTPError as e:
        err = e.read().decode()[:400]
        print(f"❌ {e.code}: {err}")
        return None


def md_to_html(md_text):
    """Simple markdown to WordPress Gutenberg HTML blocks"""
    lines = md_text.split('\n')
    html_parts = []
    in_list = False
    in_table = False
    table_rows = []
    in_code = False
    
    # Skip SEO data section
    seo_done = False
    konten_started = False
    
    for line in lines:
        # Skip SEO data section (--- ... --- or ## SEO Data)
        if line.strip() == '---' and not konten_started:
            continue
        if line.startswith('## SEO Data') or line.startswith('## SEO'):
            continue
        if line.startswith('- **SEO') or line.startswith('- **Meta') or line.startswith('- **Slug') or line.startswith('- **Focus') or line.startswith('- **Kategori') or line.startswith('- **Tags'):
            continue
        
        if line.strip().startswith('## Konten') or line.strip().startswith('---'):
            konten_started = True
            continue
        
        if not konten_started:
            continue

        stripped = line.strip()
        
        # Skip HR markers
        if stripped == '---':
            html_parts.append('<!-- wp:separator -->\n<hr class="wp-block-separator has-alpha-channel-opacity"/>\n<!-- /wp:separator -->')
            continue
        
        # Headers
        if stripped.startswith('### '):
            if in_list: html_parts.append('</ul>\n<!-- /wp:list -->')
            if in_table: html_parts.append('</figure>\n<!-- /wp:table -->')
            in_list = False; in_table = False
            text = stripped[4:]
            html_parts.append(f'<!-- wp:heading -->\n<h3>{text}</h3>\n<!-- /wp:heading -->')
        elif stripped.startswith('#### '):
            if in_list: html_parts.append('</ul>\n<!-- /wp:list -->')
            if in_table: html_parts.append('</figure>\n<!-- /wp:table -->')
            in_list = False; in_table = False
            text = stripped[5:]
            html_parts.append(f'<!-- wp:heading -->\n<h4>{text}</h4>\n<!-- /wp:heading -->')
        elif stripped.startswith('**') and stripped.endswith('**') and '—' not in stripped and ':' not in stripped:
            # Bold line as subheading
            if in_list: html_parts.append('</ul>\n<!-- /wp:list -->')
            if in_table: html_parts.append('</figure>\n<!-- /wp:table -->')
            in_list = False; in_table = False
            text = stripped.strip('*')
            html_parts.append(f'<!-- wp:heading -->\n<h4>{text}</h4>\n<!-- /wp:heading -->')
        # Table
        elif '|' in stripped and stripped.startswith('|') and not stripped.startswith('|---'):
            if not in_table:
                in_table = True
                table_rows = []
            table_rows.append(stripped)
        elif in_table and stripped.startswith('|---'):
            continue
        elif in_table and not stripped.startswith('|'):
            # Render table
            rows_html = []
            for i, row in enumerate(table_rows):
                cells = [c.strip() for c in row.split('|')[1:-1]]
                cells_html = ''.join(f'<td>{c}</td>' if i > 0 else f'<th>{c}</th>' for c in cells)
                rows_html.append(f'<tr>{cells_html}</tr>')
            html_parts.append(f'<!-- wp:table -->\n<figure class="wp-block-table"><table><tbody>{"".join(rows_html)}</tbody></table></figure>\n<!-- /wp:table -->')
            in_table = False
            table_rows = []
            # Also process current line if it's not empty
            if stripped:
                pass
        # List items
        elif stripped.startswith('- ') or stripped.startswith('* '):
            if in_table:
                in_table = False
                table_rows = []
            if not in_list:
                in_list = True
                html_parts.append('<!-- wp:list -->\n<ul>')
            # Bold items
            text = stripped[2:]
            text = bold_text(text)
            html_parts.append(f'<li>{text}</li>')
        elif stripped.startswith('1. ') or stripped.startswith('2. ') or stripped.startswith('3. ') or stripped.startswith('4. ') or stripped.startswith('5. ') or stripped.startswith('6. ') or stripped.startswith('7. ') or stripped.startswith('8. ') or stripped.startswith('9. '):
            if in_table:
                in_table = False
                table_rows = []
            if not in_list:
                in_list = True
                html_parts.append('<!-- wp:list {"ordered":true} -->\n<ol>')
            text = stripped[3:]
            text = bold_text(text)
            html_parts.append(f'<li>{text}</li>')
        else:
            if in_list:
                html_parts.append('</ul>\n<!-- /wp:list -->')
                in_list = False
            if in_table:
                in_table = False
                table_rows = []
            
            # Empty line
            if not stripped:
                continue
            
            # Parse bold/italic
            text = stripped
            text = bold_text(text)
            
            # Check if it's a numbered step heading like "Langkah 1:" or "Tip 1:"
            step_match = re.match(r'\*\*(.+?)\*\*', text)
            if step_match:
                bold_part = step_match.group(1)
                rest = text[step_match.end():].strip()
                if rest.startswith(':'):
                    rest = rest[1:].strip()
                if rest:
                    html_parts.append(f'<!-- wp:paragraph -->\n<p><strong>{bold_part}</strong>: {rest}</p>\n<!-- /wp:paragraph -->')
                else:
                    html_parts.append(f'<!-- wp:paragraph -->\n<p><strong>{bold_part}</strong></p>\n<!-- /wp:paragraph -->')
            else:
                html_parts.append(f'<!-- wp:paragraph -->\n<p>{text}</p>\n<!-- /wp:paragraph -->')
    
    # Close any open tags
    if in_list:
        html_parts.append('</ul>\n<!-- /wp:list -->')
    if in_table:
        rows_html = []
        for i, row in enumerate(table_rows):
            cells = [c.strip() for c in row.split('|')[1:-1]]
            cells_html = ''.join(f'<td>{c}</td>' if i > 0 else f'<th>{c}</th>' for c in cells)
            rows_html.append(f'<tr>{cells_html}</tr>')
        html_parts.append(f'<!-- wp:table -->\n<figure class="wp-block-table"><table><tbody>{"".join(rows_html)}</tbody></table></figure>\n<!-- /wp:table -->')
    
    return '\n'.join(html_parts)

def bold_text(text):
    """Convert **bold** to <strong>bold</strong>"""
    text = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', text)
    text = re.sub(r'\*(.+?)\*', r'<em>\1</em>', text)
    # Convert URLs
    text = re.sub(r'\[(.+?)\]\((.+?)\)', r'<a href="\2">\1</a>', text)
    return text

def extract_md_section(filepath, section):
    """Extract a section from markdown file"""
    with open(filepath, 'r') as f:
        content = f.read()
    
    patterns = {
        'title': r'SEO Title:\s*(.+?)(?:\n|$)',
        'slug': r'Slug:\s*(.+?)(?:\n|$)',
        'excerpt': r'Meta Description:\s*(.+?)(?:\n|$)',
        'keyphrase': r'Focus Keyphrase:\s*(.+?)(?:\n|$)',
        'category': r'Kategori:\s*(.+?)(?:\n|$)',
        'tags': r'Tags:\s*(.+?)(?:\n|$)',
    }
    
    m = re.search(patterns.get(section, ''), content)
    if m:
        val = m.group(1).strip()
        # Clean bold markers
        val = re.sub(r'\*{1,2}', '', val)
        val = val.strip()
        return val
    return ''

def get_category_id(cat_name):
    mapping = {
        'AI & Otomasi': 8,  # otomasi bisnis
        'AI & Automation': 8,
    }
    return mapping.get(cat_name, 8)

def get_tag_ids(tags_str):
    """Map tag names to IDs from existing tags"""
    tag_map = {
        'konsultan AI Surabaya': 54,
        'Nucleasoft': 34,
        'Nucleasoft Digital Indonesia': 22,
        'otomasi bisnis': 9,
        'konsultan AI': 67,
        'transformasi digital': 80,
        'AI untuk bisnis': 52,
        'jasa AI Surabaya': None,
        'konsultan IT Surabaya': None,
        'AI automation': 98,
        'bisnis Surabaya': None,
        'workflow automation': None,
        'bisnis kecil': None,
        'AI UKM': 96,
        'otomasi bisnis kecil': None,
        'digitalisasi UKM': 17,
        'AI untuk perusahaan': 52,
        'konsultan otomasi bisnis': 26,
        'konsultan IT': None,
        'konsultan digital': None,
        'bisnis butuh AI': None,
        'AI marketing': 131,
        'meningkatkan omset': None,
        'strategi AI': None,
        'otomasi sales': None,
        'penerapan AI': None,
        'contoh AI bisnis': None,
        'AI retail': None,
        'AI logistik': None,
        'AI finansial': None,
        'AI UKM': 96,
        'solusi AI': 95,
        'implementasi AI': None,
        'AI perusahaan': 52,
        'konsultan AI terpercaya': 62,
        'tips konsultan AI': None,
        'memilih konsultan IT': None,
    }
    ids = []
    for t in tags_str.split(','):
        t = t.strip().lower()
        if t in tag_map and tag_map[t]:
            ids.append(tag_map[t])
    return list(set(ids))


# ─── ARTICLES ───
articles = [
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/01-konsultan-ai-surabaya.md',
        'category': 'otomasi bisnis' if False else 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/02-otomasi-bisnis-ai.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/03-manfaat-jasa-ai.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/04-solusi-ai-ukm.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/05-konsultan-ai-otomasi-terpercaya.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/06-tanda-butuh-konsultan-ai.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/07-strategi-ai-penjualan.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/08-contoh-penerapan-ai.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/09-keunggulan-jasa-ai-nucleasoft.md',
        'category': 8,
    },
    {
        'file': '/home/mantapman/.hermes/profiles/atun/workspace/nucleasoft-articles/10-tips-memilih-konsultan-ai.md',
        'category': 8,
    },
]

for i, art in enumerate(articles, 1):
    f = art['file']
    print(f"\n📝 [{i}/10] Uploading {f.split('/')[-1]}...")
    
    title = extract_md_section(f, 'title')
    slug = extract_md_section(f, 'slug')
    excerpt = extract_md_section(f, 'excerpt')
    kp = extract_md_section(f, 'keyphrase')
    cat_name = extract_md_section(f, 'category')
    tags_str = extract_md_section(f, 'tags')
    
    # Read full content (skip SEO data)
    with open(f, 'r') as fh:
        full_text = fh.read()
    
    # Extract content after "## Konten"
    content_match = re.search(r'## Konten\n(.*)', full_text, re.DOTALL)
    if content_match:
        md_content = content_match.group(1).strip()
    else:
        md_content = full_text
    
    # Clean featured image section if present
    md_content = re.sub(r'\n---\n\n### Featured Image\n.*?(?=\n### |\Z)', '', md_content, flags=re.DOTALL)
    
    # Convert to HTML
    html_content = md_to_html(md_content)
    
    # Clean up excerpt
    excerpt_clean = re.sub(r'\*{1,2}', '', excerpt)
    # Truncate excerpt if too long
    if len(excerpt_clean) > 160:
        excerpt_clean = excerpt_clean[:157] + '...'
    
    cat_id = art['category']
    tag_ids = get_tag_ids(tags_str)
    
    print(f"  Title: {title}")
    print(f"  Slug: {slug}")
    print(f"  KP: {kp}")
    print(f"  Cat: {cat_id}, Tags: {tag_ids}")
    
    result = wp_post(title, html_content, slug, excerpt_clean, cat_id, tag_ids)
    
    if result:
        print(f"  ✅ ID: {result['id']} | {result['link']}")
    else:
        print(f"  ❌ Gagal")
