#!/usr/bin/env python3
"""
Download featured images from MEC JSON export and attach to Kurs posts.
"""

import json
import subprocess
import sys
import re
import urllib.request
import os
from pathlib import Path

# Paths
JSON_FILE = Path(__file__).parent.parent.parent.parent.parent.parent / "export" / "mec-events-20251203UTC0947.json"
CONTAINER = "mec_wordpress_staging"
UPLOAD_DIR = "/var/www/html/wp-content/uploads/kurs-images"


def run_wp_cli(cmd: str) -> str:
    """Run WP-CLI command in container."""
    full_cmd = f'docker exec {CONTAINER} wp {cmd} --allow-root'
    result = subprocess.run(full_cmd, shell=True, capture_output=True, text=True)
    return result.stdout.strip()


def get_kurs_id_by_mec_id(mec_id: int) -> int | None:
    """Get kurs post ID by original MEC ID."""
    result = run_wp_cli(f'post list --post_type=kurs --meta_key=_mec_original_id --meta_value={mec_id} --field=ID')
    if result and result.isdigit():
        return int(result)
    return None


def download_image(url: str, filename: str) -> str | None:
    """Download image to temp file."""
    try:
        temp_path = f"/tmp/{filename}"
        urllib.request.urlretrieve(url, temp_path)
        return temp_path
    except Exception as e:
        print(f"  [ERROR] Download failed: {e}")
        return None


def import_image_to_wp(local_path: str, title: str) -> int | None:
    """Import image to WordPress media library."""
    # Copy file to container
    copy_cmd = f'docker cp "{local_path}" {CONTAINER}:/tmp/'
    subprocess.run(copy_cmd, shell=True, capture_output=True)

    filename = os.path.basename(local_path)

    # Import using WP-CLI
    result = run_wp_cli(f'media import /tmp/{filename} --title="{title}" --porcelain')

    # Clean up
    subprocess.run(f'docker exec {CONTAINER} rm -f /tmp/{filename}', shell=True, capture_output=True)
    os.remove(local_path)

    if result and result.isdigit():
        return int(result)
    return None


def set_featured_image(post_id: int, attachment_id: int) -> bool:
    """Set featured image for a post."""
    result = run_wp_cli(f'post meta update {post_id} _thumbnail_id {attachment_id}')
    return 'Success' in result or 'Updated' in result


def main():
    print("=" * 60)
    print("Featured Images Import")
    print("=" * 60)

    # Load JSON
    if not JSON_FILE.exists():
        print(f"[ERROR] JSON file not found: {JSON_FILE}")
        sys.exit(1)

    with open(JSON_FILE, 'r', encoding='utf-8') as f:
        events = json.load(f)

    print(f"Loaded {len(events)} events from JSON\n")

    imported = 0
    skipped = 0
    errors = 0

    for event in events:
        mec_id = event.get('ID')
        title = event.get('title', 'Unknown')[:50]

        # Get featured image URL
        featured = event.get('featured_image', {})
        image_url = featured.get('large') or featured.get('medium') or featured.get('full')

        if not image_url:
            print(f"[{mec_id}] {title}...")
            print(f"  -> Kein Bild vorhanden")
            skipped += 1
            continue

        # Find corresponding kurs post
        kurs_id = get_kurs_id_by_mec_id(mec_id)
        if not kurs_id:
            print(f"[{mec_id}] {title}...")
            print(f"  -> Kurs nicht gefunden")
            skipped += 1
            continue

        # Check if already has featured image
        existing = run_wp_cli(f'post meta get {kurs_id} _thumbnail_id')
        if existing and existing.isdigit():
            print(f"[{mec_id}] {title}...")
            print(f"  -> Bereits Bild vorhanden (ID: {existing})")
            skipped += 1
            continue

        print(f"[{mec_id}] {title}...")
        print(f"  URL: {image_url[:60]}...")

        # Extract filename from URL
        filename = image_url.split('/')[-1].split('?')[0]
        if not filename:
            filename = f"kurs-{mec_id}.jpg"

        # Download image
        local_path = download_image(image_url, filename)
        if not local_path:
            errors += 1
            continue

        # Import to WordPress
        attachment_id = import_image_to_wp(local_path, f"Kurs: {title}")
        if not attachment_id:
            print(f"  [ERROR] Import failed")
            errors += 1
            continue

        # Set as featured image
        if set_featured_image(kurs_id, attachment_id):
            print(f"  -> Importiert (Attachment: {attachment_id}, Kurs: {kurs_id})")
            imported += 1
        else:
            print(f"  [ERROR] Featured Image setzen fehlgeschlagen")
            errors += 1

    print("\n" + "=" * 60)
    print(f"FERTIG: {imported} importiert, {skipped} übersprungen, {errors} Fehler")
    print("=" * 60)


if __name__ == "__main__":
    main()
