#!/usr/bin/env python3
"""Upload image to Joomla Media + Create article."""
import json, subprocess, sys

# Read token
with open('/home/hermes/.hermes/joomla_token.txt') as f:
    token = f.read().strip()

print(f"Token length: {len(token)}")

# Step 1: Upload media
print("\n=== Uploading media ===")
media_cmd = [
    'curl', '-s', '-X', 'POST',
    'https://www.brettspiel-news.de/api/index.php/v1/media/files',
    '-H', 'Accept: application/vnd.api+json',
    '-H', f'X-Joomla-Token: {token}',
    '-F', 'file=@/home/hermes/workspace/dune_uprising_sale_2026-06-20.png',
    '-F', 'path=images/Spiele/2026',
]
result = subprocess.run(media_cmd, capture_output=True, text=True, timeout=30)
print(result.stdout)
try:
    media_data = json.loads(result.stdout)
    if 'data' in media_data:
        media_attrs = media_data['data'].get('attributes', {})
        media_filename = media_attrs.get('path', media_attrs.get('filename', ''))
        print(f"Uploaded: {media_filename}")
    elif 'errors' in media_data:
        print(f"ERROR: {json.dumps(media_data['errors'], indent=2)}")
except json.JSONDecodeError:
    print(f"Raw: {result.stdout}")

# Step 2: Create article
print("\n=== Creating article ===")
with open('/home/hermes/workspace/daily_article_2026-06-20.html') as f:
    article_html = f.read().strip()

title = '„Spione gegen Frust" – vom Clank!-Designer Paul Dennen: Dune Imperium Uprising heute 26 % reduziert'

payload = {
    'title': title,
    'introtext': '',
    'text': article_html,
    'catid': 61,
    'state': 0,
    'access': 6,
    'created_by': 560,
    'language': 'de',
    'featured': 1
}

article_cmd = [
    'curl', '-s', '-X', 'POST',
    'https://www.brettspiel-news.de/api/index.php/v1/content/articles',
    '-H', 'Accept: application/vnd.api+json',
    '-H', 'Content-Type: application/json',
    '-H', f'X-Joomla-Token: {token}',
    '-d', json.dumps(payload),
]
result = subprocess.run(article_cmd, capture_output=True, text=True, timeout=30)
print(result.stdout)
try:
    art_data = json.loads(result.stdout)
    if 'data' in art_data:
        art_id = art_data['data'].get('id', 'UNKNOWN')
        print(f"Article created! ID: {art_id}")
    elif 'errors' in art_data:
        print(f"ERROR: {json.dumps(art_data['errors'], indent=2)}")
except json.JSONDecodeError:
    print(f"Raw: {result.stdout}")
