#!/usr/bin/env python3
"""Publish konten panjang (>=1300 kata + embed reel + penutup dokter) utk 2 post SSC."""
import base64, json, re, urllib.request, urllib.parse

DOM='surabaya-skincentre.com'
AUTH=base64.b64encode(b'bambangbot:r4bI jsIF CsAn uTIz SlFa TnJz').decode()

def wp(ep, method='GET', data=None):
    url=f'https://{DOM}/wp-json/wp/v2/{ep}'
    body=json.dumps(data).encode() if data is not None else None
    req=urllib.request.Request(url,data=body,method=method,headers={
        'Authorization':f'Basic {AUTH}','Content-Type':'application/json','User-Agent':'Bot/1.0'})
    try:
        with urllib.request.urlopen(req,timeout=90) as r: return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e: return e.code, e.read().decode(errors='ignore')[:400]

def inline(s):
    s=re.sub(r'\*\*(.+?)\*\*',r'<strong>\1</strong>',s)
    s=re.sub(r'\*(.+?)\*',r'<em>\1</em>',s)
    s=re.sub(r'\[(.+?)\]\((.*?)\)',r'<a href="\2">\1</a>',s)
    return s

def md_to_html(md):
    lines=md.strip().split('\n')
    out=[]; in_ul=False; in_p=False; in_table=False
    def cp():
        nonlocal in_p
        if in_p: out.append('</p>'); in_p=False
    def cu():
        nonlocal in_ul
        if in_ul: out.append('</ul>'); in_ul=False
    for ln in lines:
        s=ln.strip()
        if not s:
            cp(); continue
        if s in ('---','...'): continue
        # headings
        m=re.match(r'^### (.+)$',s)
        if m: cp();cu();out.append(f'<h3>{inline(m.group(1))}</h3>');continue
        m=re.match(r'^## (.+)$',s)
        if m: cp();cu();out.append(f'<h2>{inline(m.group(1))}</h2>');continue
        m=re.match(r'^# (.+)$',s)
        if m: cp();cu();out.append(f'<h1>{inline(m.group(1))}</h1>');continue
        # table
        if s.startswith('|') and '|' in s[1:]:
            cells=[c.strip() for c in s.strip('|').split('|')]
            if all(re.match(r'^:?-+:?$',c) for c in cells):
                continue
            if not in_table:
                out.append('<table><tbody>'); in_table=True
            out.append('<tr>'+''.join(f'<td>{inline(c)}</td>' for c in cells if c)+'</tr>')
            continue
        else:
            if in_table: out.append('</tbody></table>'); in_table=False
        # blockquote
        if s.startswith('> '):
            cp();cu();out.append(f'<blockquote>{inline(s[2:])}</blockquote>');continue
        # iframe
        if s.startswith('<iframe'):
            cp();cu();out.append(s);continue
        # video (blok independen, jangan dibungkus <p>)
        if s.startswith('<video'):
            cp();cu();out.append(s);continue
        # hr
        if s in ('---','***','___'):
            cp();cu();out.append('<hr/>');continue
        # list
        if re.match(r'^\s*[-*] ',s):
            cp()
            if not in_ul: out.append('<ul>'); in_ul=True
            out.append('<li>'+inline(re.sub(r'^\s*[-*] ','',s))+'</li>')
            continue
        else:
            cu()
        # numbered list (1.)
        m=re.match(r'^(\d+)\.\s+(.*)$',s)
        if m:
            cp();cu();out.append(f'<ol><li>{inline(m.group(2))}</li></ol>')
            continue
        # paragraph
        if not in_p: out.append('<p>'); in_p=True
        out.append(inline(s))
    cp();cu()
    if in_table: out.append('</tbody></table>')
    return '\n'.join(out)

def read_art(path):
    md=open(path).read()
    m=re.match(r'^---\n(.*?)\n---\n',md,re.S)
    fm=m.group(1); body=md[m.end():]
    def v(k):
        mm=re.search(rf'^{k}:\s*(.+)$',fm,re.M); return mm.group(1).strip().strip('"') if mm else ''
    return {'title':v('title'),'slug':v('slug'),'meta':v('meta_description'),'body':body}

arts=[
    {'id':4411,'path':'/home/mantapman/.openclaw/workspace-ujang/artikel_ssc_begadang.md'},
    {'id':4412,'path':'/home/mantapman/.openclaw/workspace-ujang/artikel_ssc_pori.md'},
]
for a in arts:
    art=read_art(a['path'])
    html=md_to_html(art['body'])
    print(f"=== Post {a['id']}: {art['slug']} ===")
    print('  html length:',len(html))
    payload={'title':art['title'],'content':html,
             'meta':{'_yoast_wpseo_metadesc':art['meta'][:155],
                     '_yoast_wpseo_title':art['title'][:60]}}
    s,res=wp(f'posts/{a["id"]}',method='POST',data=payload)
    print('  update status:',s)
    print('  link:',res.get('link') if isinstance(res,dict) else res)
