#!/usr/bin/env python3
"""Test export-all endpoint"""
import sys
sys.path.insert(0, '/app')

from datetime import datetime
from db import get_db, get_cursor, r2d

print("Testing export-all logic...")

with get_db() as conn:
    cur = get_cursor(conn)
    cur.execute("SELECT * FROM ai_prompts ORDER BY sort_order, slug")
    prompts = [r2d(row) for row in cur.fetchall()]

print(f"Found {len(prompts)} prompts")

# Convert to export format (clean up DB-specific fields)
export_data = []
for idx, p in enumerate(prompts):
    print(f"\nProcessing prompt {idx+1}: {p.get('slug')}")
    try:
        export_item = {
            'slug': p['slug'],
            'name': p['name'],
            'display_name': p.get('display_name'),
            'description': p.get('description'),
            'type': p.get('type', 'pipeline'),
            'category': p.get('category', 'ganzheitlich'),
            'template': p.get('template'),
            'stages': p.get('stages'),
            'output_format': p.get('output_format', 'text'),
            'output_schema': p.get('output_schema'),
            'question_augmentations': p.get('question_augmentations'),
            'graph_data': p.get('graph_data'),
            'active': p.get('active', True),
            'sort_order': p.get('sort_order', 0)
        }
        export_data.append(export_item)
        print(f"  ✓ OK")
    except Exception as e:
        print(f"  ✗ ERROR: {type(e).__name__}: {e}")
        import traceback
        traceback.print_exc()
        break

print(f"\n\nSuccessfully processed {len(export_data)} prompts")

# Try to create the response dict
try:
    result = {
        'export_date': datetime.now().isoformat(),
        'count': len(export_data),
        'prompts': export_data
    }
    print("✓ Result dict created successfully")

    # Try JSON serialization
    import json
    json_str = json.dumps(result)
    print(f"✓ JSON serialization OK, length: {len(json_str)}")
except Exception as e:
    print(f"✗ ERROR creating result: {type(e).__name__}: {e}")
    import traceback
    traceback.print_exc()
