#!/usr/bin/env python3
"""Inventaris halaman DAS yang menyasar Alphard/Lexus (+ cek duplikasi/kanibalisasi)."""
import base64, json, re, urllib.request

SITE = "https://dasindonesia.com"
AUTH = base64.b64encode(b"bambangbot:u3a1 G2pQ 3SWY f0zI OlGP YAjU").decode()


def api(path):
    r = urllib.request.Request(SITE + path, headers={"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(r, timeout=240) as x:
        return json.loads(x.read())


posts, page = [], 1
while True:
    d = api(f"/wp-json/wp/v2/posts?per_page=100&page={page}&_fields=id,slug,title,date,status,link")
    posts += d
    if len(d) < 100:
        break
    page += 1
print(f"total post DAS: {len(posts)}")

for brand in ("alphard", "lexus"):
    hit = [p for p in posts if brand in (p["slug"] + " " + p["title"]["rendered"]).lower()]
    print(f"\n=== {brand.upper()}: {len(hit)} artikel ===")
    for p in sorted(hit, key=lambda x: x["date"]):
        print(f"  #{p['id']} {p['date'][:10]} [{p['status']}] {p['link'].replace('https://dasindonesia.com','')}")
        print(f"      {p['title']['rendered'][:100]}")

# juga cek halaman (pages) — DAS service URL menurut baseline = post
for brand in ("alphard", "lexus"):
    try:
        d = api(f"/wp-json/wp/v2/pages?per_page=100&search={brand}&_fields=id,slug,title,status,link")
        print(f"\npages berisi '{brand}': {len(d)}")
        for p in d:
            print(f"  #{p['id']} [{p['status']}] {p['link']} | {p['title']['rendered'][:70]}")
    except Exception as ex:
        print("pages error:", str(ex)[:120])
