#!/usr/bin/env python3
"""
Convert Discord JSON export to simplified message format.
Usage: python script.py <input_json_file>
"""

import json
import sys
import io

# Принудительно устанавливаем UTF-8 для stdout и stderr
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

def convert_discord_export(input_file):
    """Convert Discord export JSON to simplified message format."""
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"Error: File '{input_file}' not found.", file=sys.stderr)
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON in '{input_file}': {e}", file=sys.stderr)
        sys.exit(1)
    
    # Extract messages array
    messages = data.get('messages', [])
    
    # Convert each message to simplified format
    simplified_messages = []
    for msg in messages:
        simplified = {
            "timestamp": msg.get("timestamp"),
            "from": msg.get("author", {}).get("nickname"),
            "from_id": msg.get("author", {}).get("name"),
            "content": msg.get("content")
        }
        simplified_messages.append(simplified)
    
    # Output as JSON array with UTF-8
    output = json.dumps(simplified_messages, ensure_ascii=False, indent=2)
    print(output)

def main():
    if len(sys.argv) != 2:
        print("Usage: python script.py <discord_export.json>", file=sys.stderr)
        sys.exit(1)
    
    input_file = sys.argv[1]
    convert_discord_export(input_file)

if __name__ == "__main__":
    main()
