#!/usr/bin/env python3
import json, re, subprocess, sys, time

# Konfigurasi WP
WP_URL = "https://studiosoft.id/wp-json/wp/v2"
USER = "bambangbot"
APP_PASS = "q26r RePo BVy6 pwU2 F3z7 ouyl"

ARTIKEL = [
    {
        "file": "artikel_pilar/01_apa_itu_seo.md",
        "title": "Apa itu SEO? Pengertian, Cara Kerja, dan Manfaatnya untuk Bisnis di 2026",
        "slug": "apa-itu-seo-pengertian-cara-kerja-manfaat",
        "category": 330,
        "focus": "apa itu seo",
        "meta": "SEO adalah proses mengoptimalkan website agar muncul di halaman pertama Google. Pelajari pengertian, cara kerja, dan manfaat SEO untuk bisnis Anda di 2026."
    },
    {
        "file": "artikel_pilar/02_biaya_website.md",
        "title": "Berapa Biaya Jasa Pembuatan Website di Indonesia? Rincian Lengkap 2026",
        "slug": "berapa-biaya-jasa-pembuatan-website",
        "category": 23,
        "focus": "biaya jasa pembuatan website",
        "meta": "Biaya jasa pembuatan website di Indonesia mulai Rp1,5 juta hingga Rp150 juta. Lihat rincian harga per jenis website dan faktor yang memengaruhinya di 2026."
    },
    {
        "file": "artikel_pilar/03_jasa_seo_surabaya.md",
        "title": "Cara Memilih Jasa SEO Terbaik di Surabaya: Panduan Lengkap 2026",
        "slug": "cara-memilih-jasa-seo-surabaya",
        "category": 26,
        "focus": "jasa seo surabaya",
        "meta": "Cara memilih jasa SEO terbaik di Surabaya: panduan lengkap cek portofolio, metode, biaya, dan tanda jasa SEO abal-abal di 2026."
    },
]

def read_and_parse(file):
    with open(file) as f:
        txt = f.read()
    # Split antara judul/metadata dan isi
    # Ambil bagian "## Isi Artikel (HTML)" sampai "## FAQ Schema"
    m = re.search(r'## Isi Artikel \(HTML\)\n(.*?)\n## FAQ Schema', txt, re.S)
    isi = m.group(1).strip() if m else ""
    # Ambil FAQ schema JSON
    m2 = re.search(r'## FAQ Schema \(JSON-LD for dipasang\)\n```json\n(.*?)\n```', txt, re.S)
    m2b = re.search(r'## FAQ Schema \(JSON-LD\)\n```json\n(.*?)\n```', txt, re.S)
    schema_raw = (m2 or m2b).group(1) if (m2 or m2b) else None
    schema = json.loads(schema_raw) if schema_raw else None
    return isi, schema

def md_to_html(md):
    """Konversi markdown sederhana ke HTML (h2, tabel, list, bold, paragraph)."""
    lines = md.split('\n')
    html = []
    in_table = False
    in_ul = False
    in_ol = False
    for line in lines:
        # skip konfigurasi file pilar (---, ## Isi Artikel, dsb)
        if line.strip() == '' :
            if in_table:
                html.append('</table>'); in_table = False
            if in_ul:
                html.append('</ul>'); in_ul = False
            if in_ol:
                html.append('</ol>'); in_ol = False
            continue
        # Heading
        hm = re.match(r'^(#{2,3})\s+(.*)', line)
        if hm:
            if in_table: html.append('</table>'); in_table=False
            if in_ul: html.append('</ul>'); in_ul=False
            if in_ol: html.append('</ol>'); in_ol=False
            lvl = len(hm.group(1))
            t = hm.group(2)
            if lvl == 2: html.append(f'<h2>{t}</h2>')
            else: html.append(f'<h3>{t}</h3>')
            continue
        # Tabel
        if line.startswith('|'):
            if not in_table:
                html.append('<table>'); in_table = True
            cells = [c.strip() for c in line.strip('|').split('|')]
            # skip separator line (---)
            if all(re.fullmatch(r':?-{2,}:?', c) for c in cells):
                continue
            tag = 'th' if in_table and not html[-1].startswith('<tr') and len(html)>=1 and 'td' not in html[-1] and 'th' not in html[-1] else 'td'
            # simpler: first row = header (th)
            if cells and not html[-1].startswith('<tr><th'):
                pass
            html.append('<tr>' + ''.join(f'<th>{c}</th>' if in_table and not any('<td' in h for h in html[-1:]) else f'<td>{c}</td>' for c in cells) + '</tr>')
            continue
        # img
        im = re.match(r'!\[(.*?)\]\((.*?)\)', line)
        if im:
            html.append(f'<img src="{im.group(2)}" alt="{im.group(1)}" />')
            continue
        # bullet
        bm = re.match(r'^\s*[-*]\s+(.*)', line)
        if bm:
            if not in_ul: html.append('<ul>'); in_ul=True
            html.append(f'<li>{bm.group(1)}</li>')
            continue
        # numbered
        om = re.match(r'^\s*(\d+)\.\s+(.*)', line)
        if om:
            if not in_ol: html.append('<ol>'); in_ol=True
            html.append(f'<li>{om.group(2)}</li>')
            continue
        # paragraph (with **bold** conversion)
        t = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', line)
        t = re.sub(r'`(.+?)`', r'<code>\1</code>', t)
        html.append(f'<p>{t}</p>')
    if in_table: html.append('</table>')
    if in_ul: html.append('</ul>')
    if in_ol: html.append('</ol>')
    return '\n'.join(html)

for a in ARTIKEL:
    isi, schema = read_and_parse(a["file"])
    body = md_to_html(isi)
    # tambah FAQ schema di akhir body
    if schema:
        script = f'<script type="application/ld+json">{json.dumps(schema, ensure_ascii=False)}</script>'
        body = body + '\n' + script

    payload = {
        "title": a["title"],
        "slug": a["slug"],
        "content": body,
        "status": "publish",
        "categories": [a["category"]],
        "author": 3,
        "meta_description": a["meta"],
        "focus_keyword": a["focus"],
    }
    # meta_description & focus_keyword pakai rank math/yoast meta fields kalau ada
    payload["meta"] = {
        "rank_math_description": a["meta"],
        "rank_math_focus_keyword": a["focus"],
    }

    print(f"\n=== Publish: {a['title']} ===")
    print(f"Panjang body: {len(body)} chars")
    code = subprocess.run(
        ["curl", "-s", "-w", "\\n%{http_code}", "-u", f"{USER}:{APP_PASS}",
         "-H", "Content-Type: application/json",
         "-X", "POST", f"{WP_URL}/posts",
         "-d", json.dumps(payload, ensure_ascii=False)],
        capture_output=True, text=True
    )
    out = code.stdout
    # split http code
    if "\n" in out:
        resp, http = out.rsplit("\n", 1)
    else:
        resp, http = out, "?"
    try:
        j = json.loads(resp)
        if http == "201":
            print(f"✅ SUCCESS — ID: {j.get('id')} | Link: {j.get('link')}")
        else:
            print(f"⚠️ HTTP {http}")
            if isinstance(j, dict) and j.get('data'):
                print("Error:", j['data'].get('message'))
            else:
                print(j)
    except Exception as e:
        print(f"HTTP {http} | Parse error: {e}")
        print(resp[:500])
    time.sleep(1)

print("\nSelesai.")
