#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
publish_schedule_das.py — Publish & jadwalkan 10 artikel DAS (status future, 1/hari).

Baca header markdown + konten, konversi ke HTML, upload featured image WebP,
buat post scheduled + Yoast meta. Schedule mulai tanggal START_DATE 08:00 WIB (01:00 UTC).
"""
import os, re, json, sys, time, base64, io, datetime
import requests

ROOT = os.path.dirname(os.path.abspath(__file__))
WP = "https://dasindonesia.com/wp-json/wp/v2"
USER, PASSWORD = "bambangbot", "VzXR 72KF NJWn XxHI MhJN B9Hs"
AUTH = base64.b64encode(f"{USER}:{PASSWORD}".encode()).decode()
H = {"Authorization": f"Basic {AUTH}"}

# Kategori berdasarkan nama (dari verifikasi awal: Perawatan Mobil 622, Tips Teknis 623, Tips & Perawatan 636)
KAT = {"Perawatan Mobil": 622, "Tips Teknis": 623, "Tips & Perawatan": 636}

# Tag tambahan agar konsisten
TAGS = {
    "pentingnya overhaul": "pentiangya-overhaul",
}
# Tags per artikel via keyword (pakai slug tag yg sederhana; bila tag belum ada dipakai nama)
def build_tags(keyphrase):
    words = [w for w in re.split(r"[\s\-]+", keyphrase.lower()) if w]
    tag = " ".join(words[:3]).title()
    return [tag]

# ── Konversi markdown body → HTML ──
def md_to_html(body: str) -> str:
    lines = body.splitlines()
    html = []
    for ln in lines:
        s = ln.strip()
        if not s:
            continue
        # CTA block (sudah HTML) — lewati
        if s.startswith("<p style="):
            # sisipkan sebagai raw HTML
            html.append(s)
            continue
        if s.startswith("### "):
            html.append(f"<h3>{s[4:]}</h3>")
        elif s.startswith("## "):
            html.append(f"<h2>{s[3:]}</h2>")
        elif s.startswith("# "):
            continue  # judul H1 dari WP field
        elif s.startswith("- "):
            html.append(f"<li>{inline(s[2:])}</li>")
        elif s.startswith("**SEO") or s.startswith("**Meta") or s.startswith("**Slug") or \
             s.startswith("**Keyphrase") or s.startswith("**Kategori") or s.startswith("**Alt"):
            continue
        else:
            html.append(f"<p>{inline(s)}</p>")
    # gabungkan list
    out = []
    i = 0
    while i < len(html):
        if html[i].startswith("<li>"):
            buf = []
            while i < len(html) and html[i].startswith("<li>"):
                buf.append(html[i]); i += 1
            out.append("<ul>" + "".join(buf) + "</ul>")
        else:
            out.append(html[i]); i += 1
    return "\n".join(out)

def inline(s: str) -> str:
    # **bold** → <strong>
    s = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", s)
    # link [text](url) → <a>
    s = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', s)
    return s

def parse_article(path):
    txt = open(path, encoding="utf-8").read()
    def field(name):
        m = re.search(rf"\*\*{name}:\*\*\s*(.+)", txt)
        return m.group(1).strip() if m else ""
    title_m = re.search(r"^# (.+)$", txt, re.M)
    title = title_m.group(1).strip() if title_m else ""
    # hilangkan prefix "Artikel N: " biar rapi di post title
    title = re.sub(r"^Artikel \d+:\s*", "", title)
    # body mulai dari '## Konten'
    body = txt.split("## Konten", 1)[1] if "## Konten" in txt else txt
    return {
        "title": title,
        "seo_title": field("SEO Title"),
        "meta_desc": field("Meta Description"),
        "slug": field("Slug"),
        "keyphrase": field("Keyphrase"),
        "kategori": field("Kategori"),
        "alt": field("Alt"),
        "body": body,
    }

def upload_media(wp_path, alt):
    with open(wp_path, "rb") as f:
        files = {"file": (os.path.basename(wp_path), f, "image/webp")}
        data = {"alt": alt}
        r = requests.post(f"{WP}/media", headers=H, files=files, data=data, timeout=120)
        if r.status_code in (200, 201):
            return r.json()["id"]
        print(f"  !! media {r.status_code}: {r.text[:200]}", flush=True)
        return None

def create_post(a):
    content_html = md_to_html(a["body"])
    cat_id = KAT.get(a["kategori"], 622)
    tag = build_tags(a["keyphrase"])
    payload = {
        "title": a["title"],
        "slug": a["slug"],
        "content": content_html,
        "status": "draft",   # sementara draft, date di-set utk schedule
        "categories": [cat_id],
        "tags": [],
        "meta": {
            "_yoast_wpseo_focuskw": a["keyphrase"],
            "_yoast_wpseo_title": a["seo_title"] or a["title"],
            "_yoast_wpseo_metadesc": a["meta_desc"],
        },
    }
    r = requests.post(f"{WP}/posts", headers=H, json=payload, timeout=60)
    if r.status_code not in (200, 201):
        return None, f"create {r.status_code}: {r.text[:200]}"
    return r.json(), None

def schedule_post(post_id, iso_dt):
    # update: set status future + tanggal jadwal
    r = requests.post(f"{WP}/posts/{post_id}", headers=H,
                      json={"status": "future", "date": iso_dt, "date_gmt": iso_dt}, timeout=60)
    return r

def main():
    only = sys.argv[1] if len(sys.argv) > 1 else None
    start = datetime.datetime(2026, 8, 19, 1, 0, 0)  # 08:00 WIB UTC
    results = []
    all_slugs = [parse_article(f"artikel-{i:02d}.md")["slug"] for i in range(1, 11)]
    for i in range(1, 11):
        stem = f"artikel-{i:02d}"
        if only and stem != only:
            continue
        print(f"\n=== {stem} ===", flush=True)
        a = parse_article(f"{stem}.md")
        # 1. upload image
        img = f"{stem}-featured.webp"
        if not os.path.exists(img):
            print(f"  !! image {img} tidak ada", flush=True); continue
        media_id = upload_media(img, a["alt"])
        if not media_id:
            print("  !! gagal upload image", flush=True); continue
        print(f"  media id {media_id}", flush=True)
        # 2. buat post + set featured
        post, err = create_post(a)
        if err:
            print(f"  !! {err}", flush=True); continue
        pid = post["id"]
        # set featured media
        r = requests.post(f"{WP}/posts/{pid}", headers=H, json={"featured_media": media_id}, timeout=120)
        sched_dt = start + datetime.timedelta(days=i - 1)
        iso = sched_dt.strftime("%Y-%m-%dT%H:%M:%S")
        rs = schedule_post(pid, iso)
        print(f"  POST {pid} schedule {iso} -> {rs.status_code}", flush=True)
        # tambah internal link ke artikel lain
        results.append({"stem": stem, "id": pid, "slug": a["slug"], "link": post["link"].replace("?p=", f"?p={pid}") if "?p=" in post["link"] else f"https://dasindonesia.com/{a['slug']}/", "schedule": iso, "media": media_id})
    with open(os.path.join(ROOT, "publish_results.json"), "w") as f:
        json.dump(results, f, indent=2)
    print("\n=== DONE ===", flush=True)

if __name__ == "__main__":
    main()
