#!/usr/bin/env python3
"""
Test the JSON-like API for Wasot.

This demonstrates how Python developers familiar with JSON can use Wasot
with the same interface.
"""

import sys
import os
sys.path.insert(0, os.path.join(os.getcwd(), 'python'))

import pywasot
import json
from io import StringIO


def test_basic_loading():
    """Test loading Wasot from string."""
    print("=" * 60)
    print("Test 1: Basic loading from string")
    print("=" * 60)
    
    wasot_content = """.article title="My Article" author="John Doe"
Introduction paragraph here.

..section id="intro"
This is the introduction section.

...subsection
A nested subsection with some content.
./
./

..section id="main"
Main content goes here.

...code lang="python"
def hello():
    print("Hello, Wasot!")
./
./

..footer
Copyright 2024
./
./"""
    
    print("Input Wasot:")
    print(wasot_content)
    print("\nParsed structure:")
    
    data = pywasot.loads(wasot_content)
    print(json.dumps(data, indent=2))
    
    return data


def test_round_trip(data):
    """Test converting back to Wasot."""
    print("\n" + "=" * 60)
    print("Test 2: Round-trip conversion")
    print("=" * 60)
    
    # Convert back to Wasot
    wasot_output = pywasot.dumps(data)
    print("Reconstructed Wasot:")
    print(wasot_output)
    
    # Parse again and compare
    data2 = pywasot.loads(wasot_output)
    print("\nRe-parsed structure matches original:", data == data2)
    
    return wasot_output


def test_file_operations():
    """Test file I/O operations."""
    print("\n" + "=" * 60)
    print("Test 3: File operations")
    print("=" * 60)
    
    # Create test data
    test_data = {
        '_type': 'block',
        'name': 'document',
        'kwargs': {'version': '1.0', 'lang': 'en'},
        'children': [
            {
                '_type': 'block',
                'name': 'header',
                'children': ['Document Header']
            },
            'Some plain text content.',
            {
                '_type': 'block',
                'name': 'list',
                'args': ['ordered'],
                'children': [
                    {
                        '_type': 'block',
                        'name': 'item',
                        'children': ['First item']
                    },
                    {
                        '_type': 'block',
                        'name': 'item',
                        'children': ['Second item']
                    }
                ]
            }
        ]
    }
    
    # Test dump/load with StringIO (simulating file)
    file_obj = StringIO()
    pywasot.dump(test_data, file_obj)
    
    # Get the written content
    wasot_content = file_obj.getvalue()
    print("Written Wasot content:")
    print(wasot_content)
    
    # Read it back
    file_obj.seek(0)
    loaded_data = pywasot.load(file_obj)
    
    print("\nLoaded data matches original:", test_data == loaded_data)
    
    return test_data


def test_simple_structures():
    """Test simple data structures."""
    print("\n" + "=" * 60)
    print("Test 4: Simple structures")
    print("=" * 60)
    
    # Just text
    text_data = pywasot.loads("Hello, World!")
    print("Plain text:", text_data)
    
    # Single block
    single_block = pywasot.loads(".paragraph\nSome text here")
    print("\nSingle block:", json.dumps(single_block, indent=2))
    
    # Multiple root elements
    multi_root = pywasot.loads(""".heading
Title

.paragraph
First paragraph.

.paragraph
Second paragraph.""")
    print("\nMultiple root elements:", json.dumps(multi_root, indent=2))


def test_json_compatibility():
    """Show how Wasot is as easy as JSON for Python developers."""
    print("\n" + "=" * 60)
    print("Test 5: JSON-like usage")
    print("=" * 60)
    
    print("JSON workflow:")
    json_data = {"name": "Alice", "age": 30, "city": "NYC"}
    json_str = json.dumps(json_data)
    json_loaded = json.loads(json_str)
    print(f"  Original: {json_data}")
    print(f"  Serialized: {json_str}")
    print(f"  Loaded: {json_loaded}")
    
    print("\nWasot workflow (same API):")
    wasot_data = {
        '_type': 'block',
        'name': 'person',
        'kwargs': {"name": "Alice", "age": "30", "city": "NYC"},
        'children': []
    }
    wasot_str = pywasot.dumps(wasot_data)
    wasot_loaded = pywasot.loads(wasot_str)
    print(f"  Original: {wasot_data}")
    print(f"  Serialized: {wasot_str}")
    print(f"  Loaded: {wasot_loaded}")
    
    print("\nBoth use the same pattern: dumps() to serialize, loads() to parse!")


def main():
    """Run all tests."""
    print("PyWasot JSON-like API Test Suite")
    print("=" * 60)
    print("Just like JSON, Wasot now has:")
    print("  - loads(string) -> parse from string")
    print("  - load(file) -> parse from file object")
    print("  - dumps(data) -> convert to string")
    print("  - dump(data, file) -> write to file object")
    print("  - load_file(path) -> convenience for file paths")
    print("  - save_file(data, path) -> convenience for file paths")
    print()
    
    # Run tests
    data = test_basic_loading()
    test_round_trip(data)
    test_file_operations()
    test_simple_structures()
    test_json_compatibility()
    
    print("\n" + "=" * 60)
    print("All tests completed!")
    print("Python developers can now use Wasot just like JSON!")
    print("=" * 60)


if __name__ == "__main__":
    main()