#!/usr/bin/env python3
"""Perbaiki konten 2 post SSC: embed reel IG (iframe) + render bold di list."""
import base64, json, urllib.request, urllib.parse, re

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=60) 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 embed(code, width=560):
    return (f'<iframe src="https://www.instagram.com/reel/{code}/embed/" '
            f'width="{width}" height="{int(width*560/315)}" frameBorder="0" '
            f'scrolling="no" allowtransparency="true"></iframe>')

# fix bold ** inside <li>
def fix_list_bold(html):
    # within <ul>...</ul>, replace **x** with <strong>x</strong>
    def rep(m):
        seg=m.group(0)
        seg=re.sub(r'\*\*(.+?)\*\*',r'<strong>\1</strong>',seg)
        return seg
    return re.sub(r'<ul>.*?</ul>', rep, html, flags=re.S)

def prep(html, code):
    # render bold in list
    html=fix_list_bold(html)
    # replace the instagram link with embed iframe
    # find link to reel
    pattern=re.compile(r'<p>\s*<a href="https://www\.instagram\.com/reel/[A-Za-z0-9_-]+/">[^<]*</a>\s*</p>')
    html=pattern.sub(embed(code), html)
    # also handle plain paragraph "Simak video ... :" before it — keep it, replace only the link block
    return html

# update posts
updates=[
    {'id':4411,'code':'DcIBr-YCIQP'},
    {'id':4412,'code':'Dbnaq1XlN8s'},
]
for u in updates:
    sc,cur=wp(f'posts/{u["id"]}?context=edit')
    raw=cur['content']['raw']
    has_link = 'instagram.com/reel/' in raw
    new=prep(raw, u['code'])
    changed = new!=raw
    print(f"=== Post {u['id']} === link_found={has_link} changed={changed}")
    if changed:
        s,res=wp(f'posts/{u["id"]}', method='POST', data={'content':new})
        print('  update:',s, res.get('link') if isinstance(res,dict) else res)
    else:
        print('  (tidak ada perubahan konten)')
