# -*- coding: utf-8 -*-
"""
USD Conversion Functionality - Quick Examples
Author: CraftPilot

This file demonstrates several simple examples of how to use the USD conversion functionality.
"""

import os
import sys
import json

# Add module path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from pypapi import format_converter


def example1_simple_conversion():
    """Example 1: Simple USD file conversion"""
    print("\n" + "="*70)
    print("Example 1: Simple USD File Conversion")
    print("="*70)
    
    # Check USD support
    if not format_converter.check_usd_support():
        print("⚠ USD library not installed, please run: pip install usd-core==23.11")
        return
    
    # Find test USD file
    test_file = os.path.join(
        os.path.dirname(__file__),
        '..',
        'temp',
        'usd_test_user',
        'usd_test_path',
        'sample_sphere.usda'
    )
    
    if not os.path.exists(test_file):
        print(f"⚠ Test file does not exist: {test_file}")
        return
    
    print(f"Source file: {test_file}")
    
    # Convert USD to JSON
    output_file = os.path.join(
        os.path.dirname(__file__),
        'example_output.json'
    )
    
    try:
        json_data = format_converter.usd_to_json(test_file, output_file)
        
        print(f"✓ Conversion successful!")
        print(f"  Output file: {output_file}")
        print(f"  Mesh count: {json_data['metadata']['mesh_count']}")
        
        # Display geometry data summary
        if 'attribs' in json_data['Output_Geo']:
            positions = json_data['Output_Geo']['attribs']['point']['P']['data']
            faces = json_data['Output_Geo']['faces']
            print(f"  Vertex count: {len(positions)}")
            print(f"  Face count: {len(faces)}")
        
        return output_file
        
    except Exception as e:
        print(f"✗ Conversion failed: {str(e)}")


def example2_check_file_format():
    """Example 2: Check file format"""
    print("\n" + "="*70)
    print("Example 2: Check File Format")
    print("="*70)
    
    test_files = [
        'model.usd',
        'scene.usda',
        'character.usdc',
        'texture.png',
        'mesh.obj',
    ]
    
    print("Checking the following file formats:")
    for filename in test_files:
        is_usd = format_converter.is_usd_file(filename)
        icon = "✓" if is_usd else "✗"
        print(f"  {icon} {filename}: {'USD format' if is_usd else 'Non-USD format'}")


def example3_batch_conversion():
    """Example 3: Batch conversion"""
    print("\n" + "="*70)
    print("Example 3: Batch Convert USD Files")
    print("="*70)
    
    if not format_converter.check_usd_support():
        print("⚠ USD library not installed, skipping this example")
        return
    
    # Test directory
    test_dir = os.path.join(
        os.path.dirname(__file__),
        '..',
        'temp',
        'usd_test_user',
        'usd_test_path'
    )
    
    if not os.path.exists(test_dir):
        print(f"⚠ Test directory does not exist: {test_dir}")
        return
    
    # Find USD files
    usd_files = [
        f for f in os.listdir(test_dir) 
        if format_converter.is_usd_file(f)
    ]
    
    if not usd_files:
        print("⚠ No USD files in test directory")
        return
    
    print(f"Found {len(usd_files)} USD files:")
    for f in usd_files:
        print(f"  - {f}")
    
    # Create output directory
    output_dir = os.path.join(os.path.dirname(__file__), 'batch_output')
    
    try:
        # Batch conversion
        converted = format_converter.batch_convert_usd_to_json(
            test_dir,
            output_dir,
            recursive=False
        )
        
        print(f"\n✓ Successfully converted {len(converted)} files:")
        for usd_path, json_path in converted:
            usd_name = os.path.basename(usd_path)
            json_name = os.path.basename(json_path)
            print(f"  {usd_name} → {json_name}")
        
        return output_dir
        
    except Exception as e:
        print(f"✗ Batch conversion failed: {str(e)}")


def example4_read_converted_json():
    """Example 4: Read converted JSON data"""
    print("\n" + "="*70)
    print("Example 4: Read and Parse Converted JSON")
    print("="*70)
    
    # Use file generated from example 1
    json_file = os.path.join(os.path.dirname(__file__), 'example_output.json')
    
    if not os.path.exists(json_file):
        print(f"⚠ JSON file does not exist, please run example 1 first")
        return
    
    # Read JSON
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    print(f"Reading file: {json_file}")
    print("\nJSON structure:")
    print(f"  Root keys: {list(data.keys())}")
    
    # Parse metadata
    if 'metadata' in data:
        meta = data['metadata']
        print(f"\nMetadata:")
        print(f"  Source file: {meta.get('source', 'N/A')}")
        print(f"  Type: {meta.get('source_type', 'N/A')}")
        print(f"  Mesh count: {meta.get('mesh_count', 0)}")
    
    # Parse geometry data
    if 'Output_Geo' in data:
        geo = data['Output_Geo']
        
        if 'attribs' in geo:
            attribs = geo['attribs']
            print(f"\nGeometry data:")
            
            # Point attributes
            if 'point' in attribs:
                point_attrs = attribs['point']
                print(f"  Point attributes: {list(point_attrs.keys())}")
                
                if 'P' in point_attrs:
                    positions = point_attrs['P']['data']
                    print(f"    - Position (P): {len(positions)} points")
                    if positions:
                        print(f"      Example: {positions[0]}")
                
                if 'N' in point_attrs:
                    normals = point_attrs['N']['data']
                    print(f"    - Normal (N): {len(normals)} normals")
            
            # Vertex attributes
            if 'vertex' in attribs and attribs['vertex']:
                vertex_attrs = attribs['vertex']
                print(f"  Vertex attributes: {list(vertex_attrs.keys())}")
            
            # Face data
            if 'faces' in geo:
                faces = geo['faces']
                print(f"  Faces: {len(faces)} triangles")
                if faces:
                    print(f"    Example: {faces[0]}")
            
            # Transform information
            if 'transform' in geo:
                transform = geo['transform']
                print(f"  Transform:")
                print(f"    - Translation: {transform.get('translate', 'N/A')}")
                print(f"    - Rotation: {transform.get('rotate', 'N/A')}")
                print(f"    - Scale: {transform.get('scale', 'N/A')}")


def main():
    """Run all examples"""
    print("=" * 70)
    print("USD Conversion Functionality - Quick Examples")
    print("=" * 70)
    print("\nThese examples demonstrate how to use the USD conversion functionality")
    
    # Run examples
    example1_simple_conversion()
    example2_check_file_format()
    example3_batch_conversion()
    example4_read_converted_json()
    
    print("\n" + "=" * 70)
    print("All Examples Completed")
    print("=" * 70)
    print("\nFor detailed documentation, see: HoudiniServer/docs/USD_CONVERSION_GUIDE.md")


if __name__ == '__main__':
    main()
