#!/usr/bin/env python3
"""Publish 25 TSC articles to WordPress via REST API"""
import requests, os, re, sys

USER = "watibot"
PASS = "HDLe Wkuz el12 U2cd MRqT 1z48"
BASE = "https://www.theskincodeclinic.com/wp-json/wp/v2"
AUTH = (USER, PASS)

img_map_10 = {
    "tsc_01_facial_medis.webp": 8790, "tsc_02_botox_dan_filler.webp": 8791,
    "tsc_03_chemical_peeling.webp": 8792, "tsc_04_laser_rejuvenation.webp": 8793,
    "tsc_05_microneedling.webp": 8794, "tsc_06_perawatan_kulit_berminyak.webp": 8795,
    "tsc_07_body_contouring.webp": 8796, "tsc_08_anti_aging.webp": 8797,
    "tsc_09_manfaat_facial_medis.webp": 8798, "tsc_010_tips_memilih_klinik.webp": 8789,
}
img_map_15 = {
    "tsc_01_flek_hitam.webp": 8799, "tsc_02_jerawat.webp": 8800,
    "tsc_03_kulit_kering.webp": 8801, "tsc_04_eksim.webp": 8802,
    "tsc_05_sunscreen.webp": 8803, "tsc_06_kenali_pms.webp": 8804,
    "tsc_07_kutil_kelamin.webp": 8805, "tsc_08_herpes.webp": 8806,
    "tsc_09_sifilis.webp": 8807, "tsc_10_cegah_pms.webp": 8808,
    "tsc_11_kulit_kenyal.webp": 8809, "tsc_12_hidung.webp": 8810,
    "tsc_13_bibir.webp": 8811, "tsc_14_tubuh.webp": 8812,
    "tsc_15_perawatan.webp": 8813,
}

cat_map = {"Perawatan Wajah":22,"Perawatan Estetika":22,"Perawatan Tubuh":558,"Anti Aging":22,"Informasi":22,"Dermatology":197,"Venereology":197,"Aesthetic":558}

def parse_md(content):
    m = re.match(r'^---\s*\n(.*?)\n---\s*\n(.*)', content, re.DOTALL)
    front, body = {}, content
    if m:
        for line in m.group(1).split('\n'):
            if ':' in line:
                k, v = line.split(':', 1)
                front[k.strip()] = v.strip()
        body = m.group(2).strip()
    return front, body

def md_to_html(body, img_id=None):
    lines = body.split('\n')
    html, in_list = [], False
    for line in lines:
        s = line.strip()
        if not s:
            if in_list: html.append('</ul>'); in_list = False
            continue
        if 'images/' in s and '.webp' in s and img_id:
            html.append(f'<figure><img src="https://www.theskincodeclinic.com/wp-json/wp/v2/media/{img_id}" alt="TSC" /></figure>')
            continue
        if s.startswith('### '):
            if in_list: html.append('</ul>'); in_list = False
            html.append(f'<h3>{s[4:]}</h3>')
        elif s.startswith('## '):
            if in_list: html.append('</ul>'); in_list = False
            html.append(f'<h2>{s[3:]}</h2>')
        elif s.startswith('# '):
            if in_list: html.append('</ul>'); in_list = False
            continue
        elif s.startswith('- ') or s.startswith('* '):
            if not in_list: html.append('<ul>'); in_list = True
            t = s[2:]
            # bold in list
            t = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', t)
            html.append(f'<li>{t}</li>')
        elif re.match(r'^\d+\.\s', s):
            if not in_list: html.append('<ol>'); in_list = True
            t = re.sub(r'^\d+\.\s', '', s)
            t = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', t)
            html.append(f'<li>{t}</li>')
        elif s.startswith('> '):
            if in_list: html.append('</ul>'); in_list = False
            html.append(f'<blockquote>{s[2:]}</blockquote>')
        else:
            if in_list: html.append('</ul>'); in_list = False
            text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', s)
            text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
            html.append(f'<p>{text}</p>')
    if in_list: html.append('</ul>')
    return '\n'.join(html)

def get_or_create_tags(tag_str):
    ids = []
    for name in [t.strip() for t in tag_str.split(',') if t.strip()]:
        r = requests.get(f"{BASE}/tags?search={name}", auth=AUTH)
        if r.status_code == 200 and r.json():
            ids.append(r.json()[0]['id'])
        else:
            r2 = requests.post(f"{BASE}/tags", auth=AUTH, json={"name": name})
            if r2.status_code == 201:
                ids.append(r2.json()['id'])
    return ids

def publish_article(fpath, img_map):
    with open(fpath) as f:
        content = f.read()
    front, body = parse_md(content)
    
    seo_title = front.get('SEO Title', '')
    meta_desc = front.get('Meta Description', '')
    slug = front.get('Slug', '')
    focus_kw = front.get('Focus Keyphrase', '')
    featured = front.get('Featured Image', '')
    cat_id = cat_map.get(front.get('Kategori', ''), 22)
    
    img_id = None
    for fname, fid in img_map.items():
        if featured and fname in featured:
            img_id = fid
            break
    
    title_line = body.split('\n')[0] if body else ''
    title = title_line.replace('# ', '').strip() or 'Artikel'
    
    html_body = md_to_html(body, img_id)
    
    post = {
        "title": title, "content": html_body, "slug": slug,
        "status": "publish", "categories": [cat_id],
        "featured_media": img_id,
        "meta": {"_yoast_wpseo_title": seo_title, "_yoast_wpseo_metadesc": meta_desc, "_yoast_wpseo_focuskw": focus_kw}
    }
    
    tag_str = front.get('Tags', '')
    if tag_str:
        tag_ids = get_or_create_tags(tag_str)
        if tag_ids:
            post["tags"] = tag_ids
    
    r = requests.post(f"{BASE}/posts", auth=AUTH, json=post, timeout=60)
    if r.status_code == 201:
        d = r.json()
        print(f"✅ {d['id']}: {title[:60]} → {d['link']}")
    else:
        print(f"❌ {r.status_code}: {title[:60]} → {r.text[:150]}")
    sys.stdout.flush()

# === MAIN ===
print("=" * 60)
print("PUBLISH 25 ARTIKEL THE SKIN CODE CLINIC")
print("=" * 60)
sys.stdout.flush()

dir10 = "/home/mantapman/.hermes/profiles/atun/workspace/tsc_10_artikel"
dir15 = "/home/mantapman/.hermes/profiles/atun/workspace/tsc_15_artikel"

for fname in sorted([f for f in os.listdir(dir10) if f.endswith('.md')]):
    publish_article(os.path.join(dir10, fname), img_map_10)

for fname in sorted([f for f in os.listdir(dir15) if f.endswith('.md')]):
    publish_article(os.path.join(dir15, fname), img_map_15)

print("\n" + "=" * 60)
print("🎉 SELESAI! 25 ARTIKEL DIPUBLISH!")
print("=" * 60)
