#!/usr/bin/env python3
"""Salin draf artikel TSC #10134 menjadi berkas teks yang enak dibaca (untuk dikirim ke Bos)."""
import base64, importlib.util, html, json, re, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}

r = urllib.request.Request(f"https://{CFG['domain']}/wp-json/wp/v2/posts/10134?context=edit&_fields=title,slug,content,meta,status", headers=h)
d = json.loads(urllib.request.urlopen(r, timeout=120).read())
raw = d["content"]["raw"]
mm = d.get("meta") or {}

teks = raw
teks = re.sub(r"<h2[^>]*>(.*?)</h2>", lambda x: "\n\n## " + re.sub(r"<[^>]+>", "", x.group(1)).strip(), teks, flags=re.S)
teks = re.sub(r"<h3[^>]*>(.*?)</h3>", lambda x: "\n\n### " + re.sub(r"<[^>]+>", "", x.group(1)).strip(), teks, flags=re.S)
teks = re.sub(r"<li[^>]*>(.*?)</li>", lambda x: "- " + re.sub(r"<[^>]+>", "", x.group(1)).strip(), teks, flags=re.S)
teks = re.sub(r"<a[^>]*href=\"([^\"]+)\"[^>]*>(.*?)</a>", r"\2 (\1)", teks, flags=re.S)
teks = re.sub(r"<[^>]+>", "", teks)
teks = html.unescape(teks)
teks = re.sub(r"\n{3,}", "\n\n", teks).strip()

with open(f"{WS}/drafts/tsc_artikel_10134_dokter_kulit_sidoarjo.md", "w") as f:
    f.write(f"# {html.unescape(re.sub('<[^>]+>', '', d['title']['raw']))}\n\n")
    f.write(f"Status: draf (#10134) · slug: `{d['slug']}` · fokus: {mm.get('_yoast_wpseo_focuskw')}\n\n")
    f.write(f"Judul SEO: {mm.get('_yoast_wpseo_title')}\n\n")
    f.write(f"Deskripsi SEO: {mm.get('_yoast_wpseo_metadesc')}\n\n---\n\n")
    f.write(teks + "\n")
print("→ drafts/tsc_artikel_10134_dokter_kulit_sidoarjo.md")
print("kata:", len(teks.split()))
