#!/usr/bin/env python3
"""DAS: tulis ulang atribut gambar untuk 4 artikel yang belum masuk, sambil menampilkan balasan server."""
import base64, json, re, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = CFG["domain"], base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
PETA = json.load(open(f"{WS}/drafts/das_peta_media.json"))
PIDS = [5873, 5820, 5600, 5569]


def kunci_dari(u):
    k = u.split("?")[0].strip()
    if k.startswith("//"):
        k = "https:" + k
    elif k.startswith("/"):
        k = "https://dasindonesia.com" + k
    elif not k.startswith("http"):
        k = "https://dasindonesia.com/" + k.lstrip("/")
    return k.replace("http://dasindonesia.com", "https://dasindonesia.com")


def tambah(tag):
    src = re.search(r'src="([^"]+)"', tag)
    if not src:
        return tag
    info = PETA.get(kunci_dari(src.group(1)))
    if info and info.get("w") and "srcset=" not in tag:
        calon = [(s["w"], s["url"]) for nama, s in (info.get("sizes") or {}).items()
                 if s.get("w") and s.get("url") and nama != "full"]
        calon.append((info["w"], src.group(1)))
        calon = sorted(set(calon))
        if len(calon) > 1:
            tag = tag.replace("<img", '<img srcset="' + ", ".join(f"{u} {w}w" for w, u in calon) + '"', 1)
            tag = tag.replace("<img", '<img sizes="(max-width: 768px) 100vw, 800px"', 1)
        if 'width="' not in tag:
            tag = tag.replace("<img", f'<img width="{info["w"]}"', 1)
        if 'height="' not in tag:
            tag = tag.replace("<img", f'<img height="{info["h"]}"', 1)
    if 'loading="' not in tag:
        tag = tag.replace("<img", '<img loading="lazy"', 1)
    if 'decoding="' not in tag:
        tag = tag.replace("<img", '<img decoding="async"', 1)
    return tag


def req(p, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode(); h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{p}", data=body, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=220) as x:
            return x.status, x.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")[:300]
    except Exception as e:
        return 0, str(e)[:150]


for pid in PIDS:
    st, isi = req(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=slug,content,author")
    try:
        d = json.loads(isi) if st == 200 else {}
    except Exception:
        d = {}
    raw = (d.get("content") or {}).get("raw", "") if isinstance(d, dict) else ""
    if not raw:
        st2, isi2 = req(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
        raw = (json.loads(isi2).get("content") or {}).get("raw", "")
    baru = re.sub(r"<img[^>]*>", lambda mm: tambah(mm.group(0)), raw, flags=re.I)
    berubah = baru != raw
    st3, bal = req(f"/wp-json/wp/v2/posts/{pid}", "POST", {"content": baru})
    st4, isi4 = req(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=content")
    raw2 = (json.loads(isi4).get("content") or {}).get("raw", "") if st4 == 200 else ""
    print(f"\n#{pid} | baca {st} | ada perubahan: {berubah} | tulis HTTP {st3} {bal[:80]}")
    print(f"      setelah tulis: panjang {len(raw2)} | img {len(re.findall('<img', raw2, re.I))} | "
          f"srcset {len(re.findall('srcset=', raw2))} | lazy {len(re.findall('loading=', raw2))} | "
          f"sesuai kiriman: {'✅' if raw2 == baru else '⚠️'}")
