import base64,json,requests
WP='https://tslaw.id/wp-json/wp/v2'
UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120 Safari/537.36'
AUTH='Basic '+base64.b64encode(b'bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y').decode()

WA_FULL='6281935000624'

def get_rendered(pid):
    r=requests.get(f'{WP}/posts/{pid}',headers={'User-Agent':UA},timeout=60)
    if r.status_code!=200: return None, r.status_code, r.text
    return r.json().get('content',{}).get('rendered',''), 200, ''

def replace_all(html):
    # 1. brand TTA -> TSLaw
    out=html.replace('TTA Law Firm','TSLaw').replace('TTA Law','TSLaw').replace('TTA','TSLaw')
    # 2. nomor WA placeholder -> nomor TSLaw
    import re
    def fix_wa(m):
        return m.group(0)
    out=re.sub(r'https://wa\.me/628[0-9]*\u2026', 'https://wa.me/'+WA_FULL, out)
    out=re.sub(r'https://wa\.me/628\.\.\.', 'https://wa.me/'+WA_FULL, out)
    out=re.sub(r'https://wa\.me/628', 'https://wa.me/'+WA_FULL, out, flags=re.I)
    # teks placeholder di body
    out=out.replace('wa.me/628…','wa.me/'+WA_FULL).replace('wa.me/628...','wa.me/'+WA_FULL)
    out=out.replace('(Silakan hubungi kami melalui website TTA Law Firm)','(Konsultasi senantiasa bersama TSLaw)')
    out=out.replace('(Silakan hubungi kami melalui website untuk kontak WhatsApp resmi)','(Konsultasi senantiasa bersama TSLaw)')
    return out

for pid in [3208, 3317]:
    print(f'===== POST {pid} =====')
    html,st,err=get_rendered(pid)
    if st!=200:
        print('  fetch err',st); continue
    print('  rendered len:',len(html),'| TTA:',html.count('TTA'),'| wa placeholder:',html.count('wa.me/628'))
    newhtml=replace_all(html)
    print('  new TTA:',newhtml.count('TTA'),'| wa.me/6281935:',newhtml.count('6281935000624'))
    # update
    up=requests.post(f'{WP}/posts/{pid}',
        headers={'Authorization':AUTH,'User-Agent':UA,'Content-Type':'application/json'},
        json={'content':newhtml},timeout=90)
    print('  update status:',up.status_code)
    if up.status_code not in (200,201):
        print('  ERR:',up.text[:400])
    else:
        # verify
        v=requests.get(f'{WP}/posts/{pid}',headers={'User-Agent':UA},timeout=60).json()
        vr=v.get('content',{}).get('rendered','')
        print('  VERIFY post {pid}: TTA=',vr.count('TTA'),'| TSLaw=',vr.count('TSLaw'),'| WA=6281935=',vr.count('6281935000624'),'| wa placeholder=',vr.count('wa.me/628'))
