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

This script is used to quickly verify if the USD conversion functionality is working properly.
"""

import os
import sys

print("=" * 70)
print("USD Conversion Functionality Verification")
print("=" * 70)

# 1. Check module import
print("\n[1/5] Checking module import...")
try:
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
    from pypapi import format_converter
    print("  ✓ format_converter module imported successfully")
except ImportError as e:
    print(f"  ✗ format_converter module import failed: {e}")
    sys.exit(1)

# 2. Check USD support
print("\n[2/5] Checking USD library support...")
usd_available = format_converter.check_usd_support()
if usd_available:
    print("  ✓ USD library installed and available")
else:
    print("  ⚠ USD library not installed")
    print("     Install command: pip install usd-core==23.11")
    print("     Continuing verification of interfaces...")

# 3. Verify API interfaces
print("\n[3/5] Verifying API interfaces...")
required_functions = [
    'is_usd_file',
    'check_usd_support',
    'usd_to_json',
    'usd_file_to_json_file',
    'batch_convert_usd_to_json',
]

all_ok = True
for func_name in required_functions:
    if hasattr(format_converter, func_name):
        print(f"  ✓ {func_name}")
    else:
        print(f"  ✗ {func_name} missing")
        all_ok = False

if not all_ok:
    print("\nVerification failed: Some API interfaces are missing")
    sys.exit(1)

# 4. Test file format detection
print("\n[4/5] Testing file format detection...")
test_cases = [
    ('test.usd', True),
    ('test.usda', True),
    ('test.usdc', True),
    ('test.obj', False),
]

for filename, expected in test_cases:
    result = format_converter.is_usd_file(filename)
    status = "✓" if result == expected else "✗"
    print(f"  {status} {filename}: {result} (expected: {expected})")

# 5. Find test files
print("\n[5/5] Finding test files...")
test_dir = os.path.join(
    os.path.dirname(__file__),
    '..',
    'temp',
    'usd_test_user',
    'usd_test_path'
)

if os.path.exists(test_dir):
    usd_files = [f for f in os.listdir(test_dir) if format_converter.is_usd_file(f)]
    if usd_files:
        print(f"  ✓ Found {len(usd_files)} USD test files:")
        for f in usd_files:
            print(f"     - {f}")
        
        # If USD library is available, try converting the first file
        if usd_available and usd_files:
            print("\n[Extra] Attempting to convert test file...")
            test_usd = os.path.join(test_dir, usd_files[0])
            try:
                import tempfile
                temp_json = os.path.join(tempfile.gettempdir(), 'test_convert.json')
                
                json_data = format_converter.usd_to_json(test_usd, temp_json)
                
                print(f"  ✓ Conversion successful: {usd_files[0]}")
                print(f"     Output: {temp_json}")
                print(f"     Mesh count: {json_data.get('metadata', {}).get('mesh_count', 0)}")
                
                # Cleanup
                if os.path.exists(temp_json):
                    os.remove(temp_json)
                    
            except Exception as e:
                print(f"  ⚠ Conversion test failed: {str(e)}")
    else:
        print(f"  ⚠ Test directory exists but has no USD files: {test_dir}")
else:
    print(f"  ⚠ Test directory does not exist: {test_dir}")
    print("     This does not affect functionality, just cannot perform complete testing")

# Summary
print("\n" + "=" * 70)
print("Verification Complete")
print("=" * 70)

if usd_available:
    print("✓ USD conversion functionality fully enabled")
    print("\nYou can start using:")
    print("  1. Upload USD files to /UploadFile/ endpoint")
    print("  2. Server will automatically convert to JSON format")
    print("  3. Converted JSON can be used for Houdini processing")
else:
    print("⚠ USD conversion functionality partially enabled")
    print("\nCurrent status:")
    print("  - API interfaces implemented ✓")
    print("  - USD library not installed ⚠")
    print("\nTo fully enable, please run:")
    print("  pip install usd-core==23.11")

print("\nDetailed documentation: HoudiniServer/docs/USD_CONVERSION_GUIDE.md")
print("=" * 70)
