#!/usr/bin/env python3
"""
Publish 2 DAS Fortuner articles to dasindonesia.com via WordPress REST API.
Keyword target: bengkel fortuner surabaya
Each article gets its own featured image (1000x567 webp) + Yoast SEO meta.
"""
import requests
from requests.auth import HTTPBasicAuth
import json, re, html, os, time, sys

WP_URL = "https://dasindonesia.com/wp-json/wp/v2"
USER = "bambangbot"
APP_PASSWORD = "VzXR 72KF NJWn XxHI MhJN B9Hs"  # from cfg_das.py
AUTH = HTTPBasicAuth(USER, APP_PASSWORD)

_s = requests.Session()
_s.auth = AUTH
_ad = requests.adapters.HTTPAdapter(max_retries=2)
_s.mount('https://', _ad)

def api(method, url, **kw):
    kw.setdefault('timeout', 40)
    return _s.request(method, url, **kw)

BASE = "/home/mantapman/.hermes/profiles/atun/workspace/artikel-das-fortuner"
IMG = os.path.join(BASE, "images")

# Category: TOYOTA (1) + Tips Teknis (623)
CATS = {
    "artikel-1": [1, 623],
    "artikel-2": [1, 623],
}

# Tags yang sudah ada di WP DAS
PRESET_TAGS = {
    "overhaul": 633,          # overhaul mesin
    "overhaulmesin": 554,     # overhaul mesin mobil
    "perawatan": 604,
    "perawatanmobil": 622,
    "tips": 623,
}
# Tag fortuner yang sudah ada
FORTUNER_TAGS = {
    "bengkelfortunersurabaya": 589,  # bengkel fortuner surabaya
    "fortuner": 228,
    "perawatanfortuner": 591,        # perawatan fortuner
    "servicefortunersurabaya": 590,  # service fortuner surabaya
}

def find_or_create_tag(name, slug=None):
    if not slug:
        slug = name.lower().replace(' ', '-')
    r = api('GET', f"{WP_URL}/tags", params={"search": name})
    if r.status_code == 200:
        for t in r.json():
            if t['name'].lower() == name.lower():
                return t['id']
    r = api('POST', f"{WP_URL}/tags", json={"name": name, "slug": slug})
    if r.status_code in (200, 201):
        print(f"  🏷️ Created tag '{name}' ({r.json()['id']})")
        return r.json()['id']
    return None

def upload_image(filepath, alt):
    fn = os.path.basename(filepath)
    with open(filepath, 'rb') as f:
        files = {'file': (fn, f, 'image/webp')}
        data = {'alt': alt, 'caption': alt}
        r = _s.post(f"{WP_URL}/media", files=files, data=data, timeout=90)
    if r.status_code in (200, 201):
        j = r.json()
        print(f"  🖼️ Img ID {j['id']}")
        return j['id']
    else:
        print(f"  ⚠️ Img fail HTTP {r.status_code}: {r.text[:200]}")
        return None

def md_to_wp(md_text):
    parts = []
    lines = md_text.split('\n')
    i = 0
    while i < len(lines):
        line = lines[i]
        if not line.strip():
            i += 1; continue
        if line.startswith('## '):
            parts.append(f'<!-- wp:heading --><h2>{html.escape(line[3:].strip())}</h2><!-- /wp:heading -->')
        elif line.startswith('### '):
            parts.append(f'<!-- wp:heading {{"level":3}} --><h3>{html.escape(line[4:].strip())}</h3><!-- /wp:heading -->')
        elif line.startswith('#### '):
            parts.append(f'<!-- wp:heading {{"level":4}} --><h4>{html.escape(line[5:].strip())}</h4><!-- /wp:heading -->')
        elif line.strip().startswith('- ') or line.strip().startswith('* '):
            items = []
            while i < len(lines) and (lines[i].strip().startswith('- ') or lines[i].strip().startswith('* ')):
                raw = lines[i].strip()[2:]
                raw = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', raw)
                m = re.match(r'\[( |x|X)\] (.+)', raw)
                if m:
                    chk = 'checked' if m.group(1).lower() == 'x' else ''
                    items.append(f'<li><input type="checkbox" {chk} disabled=""> {m.group(2)}</li>')
                else:
                    items.append(f'<li>{raw}</li>')
                i += 1
            parts.append(f'<!-- wp:list --><ul>{"".join(items)}</ul><!-- /wp:list -->')
            continue
        elif re.match(r'^\d+[\.\)] ', line.strip()):
            items = []
            while i < len(lines) and re.match(r'^\d+[\.\)] ', lines[i].strip()):
                raw = re.sub(r'^\d+[\.\)] ', '', lines[i].strip())
                raw = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', raw)
                items.append(f'<li>{raw}</li>')
                i += 1
            parts.append(f'<!-- wp:list {{"ordered":true}} --><ol>{"".join(items)}</ol><!-- /wp:list -->')
            continue
        elif line.strip().startswith('> '):
            quote = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', line.strip()[2:])
            parts.append(f'<!-- wp:quote --><blockquote class="wp-block-quote"><p>{quote}</p></blockquote><!-- /wp:quote -->')
            i += 1
            continue
        elif line.strip() == '---':
            i += 1; continue
        else:
            para = []
            while i < len(lines):
                l = lines[i]
                if (l.startswith('#') or l.strip().startswith('- ') or l.strip().startswith('* ')
                        or re.match(r'^\d+[\.\)] ', l.strip()) or l.strip() == '---'
                        or not l.strip() or l.strip().startswith('|') or l.strip().startswith('> ')):
                    break
                para.append(l.strip())
                i += 1
            if para:
                txt = '<br>'.join(para)
                txt = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', txt)
                txt = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', txt)
                parts.append(f'<!-- wp:paragraph --><p>{txt}</p><!-- /wp:paragraph -->')
            continue
        i += 1
    return '\n'.join(parts)

def parse_article(path, article_key):
    with open(path, 'r', encoding='utf-8') as f:
        c = f.read()
    m = re.match(r'^# (.+)', c)
    title = m.group(1).strip() if m else "Untitled"
    meta = re.search(r'\*\*Meta Description:\*\*\s*(.+)', c)
    meta_desc = meta.group(1).strip() if meta else ""
    kw = re.search(r'\*\*Keyword Utama:\*\*\s*(.+)', c)
    keyphrase = kw.group(1).strip() if kw else "bengkel fortuner surabaya"
    # Body HTML
    body = c
    body = re.sub(r'\*\*Meta Description:\*\*.+?\n', '', body)
    body = re.sub(r'\*\*Keyword Utama:\*\*.+?\n', '', body)
    body = re.sub(r'\*\*Keyword Sekunder:\*\*.+?\n', '', body)
    body = re.sub(r'^# .+\n', '', body)
    body = re.sub(r'^---\s*\n', '', body, count=1)
    # Tambahkan promo button di akhir
    wp = md_to_wp(body)
    promo = ('<p style="text-align:center;margin-top:30px;"><a href="https://wa.me/6285242380789'
             '?text=Hallo+DAS+Saya+ingin+AMBIL+PROMO" target="_blank" rel="noopener" '
             'style="display:inline-block;background-color:#f97316;color:#ffffff;padding:16px 36px;'
             'font-size:20px;font-weight:bold;text-decoration:none;border-radius:8px;">AMBIL PROMO SEKARANG</a></p>')
    wp += '\n' + promo
    slug = {"artikel-1": "bengkel-fortuner-surabaya-servis-berkala",
            "artikel-2": "bengkel-fortuner-surabaya-overhaul-mesin-diesel"}[article_key]
    return {'title': title, 'slug': slug, 'meta': meta_desc, 'kw': keyphrase, 'content': wp}

def build_tags(stub, kw, content_lower):
    tags = set()
    tags.add(FORTUNER_TAGS['fortuner'])       # fortuner
    tags.add(FORTUNER_TAGS['bengkelfortunersurabaya'])  # bengkel fortuner surabaya
    tags.add(FORTUNER_TAGS['perawatanfortuner'])        # perawatan fortuner
    tags.add(FORTUNER_TAGS['servicefortunersurabaya'])  # service fortuner surabaya
    if 'overhaul' in content_lower:
        tags.add(PRESET_TAGS['overhaul'])
        tags.add(PRESET_TAGS['overhaulmesin'])
    tags.add(PRESET_TAGS['perawatan'])
    tags.add(PRESET_TAGS['perawatanmobil'])
    tags.add(PRESET_TAGS['tips'])
    return [t for t in tags if t]

def main():
    only = sys.argv[1] if len(sys.argv) > 1 else None  # e.g. artikel-1
    files = sorted([f for f in os.listdir(BASE) if f.endswith('.md')])
    if only:
        files = [f for f in files if f.startswith(only + '-')]
    print(f"Found {len(files)} .md files to process")
    r = api('GET', f"{WP_URL}/categories", params={"per_page": 1})
    if r.status_code != 200:
        print("❌ Connection failed", r.status_code, r.text[:200])
        return
    print("✅ Connected to WordPress")
    results = []
    for idx, fn in enumerate(files, 1):
        stub = 'artikel-' + fn.split('-')[1]
        path = os.path.join(BASE, fn)
        art = parse_article(path, stub)
        imgpath = os.path.join(IMG, f"{stub}.webp")
        print(f"\n[{idx}/{len(files)}] {stub}: {art['title'][:60]}", flush=True)
        if not os.path.exists(imgpath):
            print("  ⚠️ Feature image missing:", imgpath)
            fid = None
        else:
            fid = upload_image(imgpath, art['title'])
        cats = CATS.get(stub, [1, 623])
        tags = build_tags(stub, art['kw'], art['content'].lower())
        data = {
            'title': art['title'],
            'content': art['content'],
            'slug': art['slug'],
            'status': 'publish',
            'categories': cats,
            'tags': tags,
            'excerpt': art['meta'][:155],
            'featured_media': fid,
            'meta': {
                '_yoast_wpseo_title': art['title'],
                '_yoast_wpseo_metadesc': art['meta'][:155],
                '_yoast_wpseo_focuskw': art['kw'],
            }
        }
        r = api('POST', f"{WP_URL}/posts", json=data)
        if r.status_code in (200, 201):
            j = r.json()
            print(f"  ✅ Post {j['id']} — {j.get('link')}", flush=True)
            results.append((stub, art['title'], j['id'], j.get('link'), True))
        else:
            print(f"  ❌ HTTP {r.status_code}: {r.text[:400]}", flush=True)
            results.append((stub, art['title'], None, None, False))
        time.sleep(2)
    print("\n=== SUMMARY ===")
    ok = sum(1 for r in results if r[4])
    print(f"✅ {ok}/{len(results)} published")
    for s, t, pid, link, good in results:
        print(f"  {'✅' if good else '❌'} {s} — {t[:55]}" + (f"  [{pid}]" if pid else ""))

if __name__ == "__main__":
    main()
