#!/usr/bin/env python3
"""Fix DAS Indonesia: assign tags & featured images based on article titles"""
import json, urllib.request, base64, re, sys

AUTH = "bambangbot:u3a1 G2pQ 3SWY f0zI OlGP YAjU"
BASE = "https://dasindonesia.com/wp-json/wp/v2"

def api(method, path, data=None):
    url = f"{BASE}/{path}"
    creds = base64.b64encode(AUTH.encode()).decode()
    req = urllib.request.Request(url)
    req.add_header("Authorization", f"Basic {creds}")
    req.add_header("Content-Type", "application/json")
    if data:
        req.data = json.dumps(data).encode()
    req.method = method
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.loads(resp.read())
    except Exception as e:
        print(f"  API Error: {e}")
        return None

# --- TAG MAPPING ---
# Map keywords to tag IDs
TAG_MAP = {
    # General tags
    "bengkel": [230, 312, 408],
    "servis": [230, 312, 326],
    "perawatan": [230, 312],
    "tips": [312],
    
    # Brand-specific
    "bmw": [263, 341],
    "mercy": [349, 263],
    "mercedes": [349, 263],
    "toyota": [214, 189, 312],
    "honda": [359, 277, 278],
    "nissan": [204, 578, 580],
    "mitsubishi": [250, 413],
    "pajero": [250, 413],
    "lexus": [211, 342, 528],
    "alphard": [249, 252, 577],
    "innova": [534, 543],
    "fortuner": [589],
    "avanza": [265],
    "avanza": [265],
    "camry": [251],
    "brio": [584],
    "hr-v": [461],
    "hrv": [461],
    "xpander": [312],
    "land cruiser": [202],
    "landcruiser": [202],
    "jeep": [221],
    "wrangler": [221],
    "sienta": [199],
    "pajero": [250, 413],
    "accord": [363],
    "vellfire": [574],
    "livina": [580, 581],
    "serena": [581],
    "corolla cross": [312, 267],
    "corolla": [312],
    "fortuner": [589],
    
    # Vehicle types
    "hybrid": [267, 275, 550, 546],
    "listrik": [338, 334, 571],
    "ev ": [338, 571],
    "matic": [435, 439],
    "suv": [561],
    "premium": [341, 343, 576],
    "mewah": [341, 576],
    
    # Services
    "overhaul": [490, 496, 491, 504],
    "ac ": [213, 255, 288, 256],
    "flushing": [255, 288],
    "carbon clean": [312],
    "tune up": [208, 312],
    "oli": [312],
    "rem": [312],
    "aki": [301, 304, 307],
    "mesin": [312],
    "transmisi": [352],
    "check engine": [479, 482, 454],
    "injektor": [312],
    "bahan bakar": [391, 389],
    "darurat": [395],
    "promo": [270],
    
    # Others
    "surabaya": [408, 191],
    "musim hujan": [291, 304],
    "liburan": [312],
    "pickup": [397],
    "antar jemput": [397],
    "spesialis": [276],
    "terpercaya": [321, 420, 358],
    "terbaik": [262, 317, 497],
    
    # People
    "sariful": [312],
}

def get_tags_for_title(title):
    """Find tag IDs matching keywords in title"""
    title_lower = title.lower()
    matched = set()
    
    # Multi-word first
    multi_map = {k: v for k, v in TAG_MAP.items() if len(k.split()) > 1}
    for kw, tids in multi_map.items():
        if kw in title_lower:
            for t in tids: matched.add(t)
    
    # Single word
    single_map = {k: v for k, v in TAG_MAP.items() if len(k.split()) == 1}
    for kw, tids in single_map.items():
        if kw.lower() in title_lower.split():
            for t in tids: matched.add(t)
        # Also check as substring
        if re.search(r'\b' + re.escape(kw.lower()) + r'\b', title_lower):
            for t in tids: matched.add(t)
    
    return list(matched)[:5]  # max 5 tags

# --- CHECK images in library that match keywords ---
print("Fetching all images from media library...")
images = api("GET", "media?per_page=100&_fields=id,title,alt_text,source_url")
if not images:
    print("Failed to fetch images!")
    sys.exit(1)
print(f"Found {len(images)} images in library")

# Build keyword->image_id map
def find_best_image(title_keywords):
    """Find best matching image from library"""
    title_lower = title_keywords.lower()
    best = None
    best_score = 0
    
    for img in images:
        img_title = img.get("title", {}).get("rendered", "").lower()
        img_alt = img.get("alt_text", "").lower()
        img_text = img_title + " " + img_alt
        
        score = 0
        for kw in title_lower.split():
            if kw in img_text:
                score += 1
        
        if score > best_score:
            best_score = score
            best = img["id"]
    
    return best

# --- GET all posts from page 1 ---
print("\nFetching posts page 1...")
posts = api("GET", "posts?per_page=100&_fields=id,title,slug,tags,featured_media,status")
if posts:
    print(f"Got {len(posts)} posts")
    
    # Also get page 2
    posts2 = api("GET", "posts?per_page=100&offset=100&_fields=id,title,slug,tags,featured_media,status")
    if posts2:
        posts.extend(posts2)
        print(f"Total: {len(posts)} posts")
else:
    print("Failed!")
    sys.exit(1)

# Process posts that need fixing
print("\n--- Fixing posts ---")
fixed_tags = 0
fixed_feat = 0

for p in posts:
    pid = p["id"]
    title = p["title"]["rendered"]
    needs_fix = False
    
    # 1. Tags
    if not p.get("tags"):
        tags = get_tags_for_title(title)
        if tags:
            result = api("POST", f"posts/{pid}", {"tags": tags})
            if result:
                fixed_tags += 1
                print(f"  [{pid}] Tags assigned ({len(tags)}): {title[:50]}")
            needs_fix = True
    
    # 2. Featured image
    if p.get("featured_media", 0) == 0:
        best_img = find_best_image(title)
        if best_img:
            result = api("POST", f"posts/{pid}", {"featured_media": best_img})
            if result:
                fixed_feat += 1
                print(f"  [{pid}] Featured set (img {best_img}): {title[:50]}")
            needs_fix = True
    
    if not needs_fix:
        print(f"  [{pid}] OK: {title[:40]}")

print(f"\n✅ Done! Tags assigned: {fixed_tags}, Featured set: {fixed_feat}")
