"""
One-time script to create the required WordPress categories for the MissionNews theme.
All names and slugs are in English.
"""
import requests
import logging
from config import WP_URL, WP_USERNAME, WP_APP_PASSWORD, REQUIRED_CATEGORIES

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

def create_categories():
    """Creates or updates all required categories in WordPress depending on config."""
    auth = (WP_USERNAME, WP_APP_PASSWORD)
    categories_url = f"{WP_URL.rstrip('/')}/wp-json/wp/v2/categories"
    
    # Fetch existing categories
    try:
        resp = requests.get(categories_url, params={"per_page": 100}, auth=auth, timeout=10)
        existing = {cat["slug"]: cat for cat in resp.json()} if resp.status_code == 200 else {}
    except Exception as e:
        logging.error(f"Failed to fetch existing categories: {e}")
        existing = {}
    
    created = []
    for cat in REQUIRED_CATEGORIES:
        if cat["slug"] in existing:
            existing_cat = existing[cat["slug"]]
            existing_id = existing_cat["id"]
            existing_name = existing_cat["name"]
            
            # If name has changed (e.g. overridden by config_local.py), update it in WordPress
            if existing_name != cat["name"]:
                logging.info(f"Category '{cat['slug']}' exists but name is '{existing_name}'. Updating to '{cat['name']}'...")
                try:
                    update_url = f"{categories_url}/{existing_id}"
                    update_resp = requests.post(update_url, json={"name": cat["name"], "description": cat["description"]}, auth=auth, timeout=10)
                    if update_resp.status_code == 200:
                        logging.info(f"Successfully updated category '{cat['slug']}' to '{cat['name']}'")
                    else:
                        logging.error(f"Failed to update category '{cat['slug']}': {update_resp.status_code} - {update_resp.text}")
                except Exception as e:
                    logging.error(f"Error updating category '{cat['slug']}': {e}")
            else:
                logging.info(f"Category '{cat['name']}' (slug: {cat['slug']}) already exists with correct name (ID: {existing_id})")
                
            created.append({"name": cat["name"], "slug": cat["slug"], "id": existing_id})
            continue
            
        try:
            resp = requests.post(categories_url, json=cat, auth=auth, timeout=10)
            if resp.status_code == 201:
                data = resp.json()
                logging.info(f"Created category '{cat['name']}' (slug: {cat['slug']}, ID: {data['id']})")
                created.append({"name": cat["name"], "slug": cat["slug"], "id": data["id"]})
            else:
                logging.error(f"Failed to create '{cat['name']}': {resp.status_code} - {resp.text}")
        except Exception as e:
            logging.error(f"Error creating category '{cat['name']}': {e}")
    
    print("\n=== CATEGORY SETUP COMPLETE ===")
    for c in created:
        print(f"  {c['name']:20s} | slug: {c['slug']:15s} | ID: {c['id']}")
    
    return created

if __name__ == "__main__":
    create_categories()
