#!/usr/bin/env python3
"""Test the macro function directly to debug the issue"""

import sys
import os
import tempfile
import shutil

# Copy test file to a temp location
test_file = "D:\\__sistem__\\Masaustu\\FikoYT.Yeni.Cag\\fikoyt-zorro.com\\node_modules\\occt-import-js\\test\\testfiles\\cax-if\\as1-oc-214.stp"

if not os.path.exists(test_file):
    print(f"Test file not found: {test_file}")
    sys.exit(1)

# Create temp copy
with tempfile.NamedTemporaryFile(delete=False, suffix='.stp') as tf:
    temp_path = tf.name
    with open(test_file, 'rb') as src:
        tf.write(src.read())

print(f"Test file copied to: {temp_path}")

# Import the macro function
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from freecad_api_server import _convert_step_to_json_macro

# Test the macro
print("\n" + "="*60)
print("Testing _convert_step_to_json_macro...")
print("="*60)

try:
    json_path = _convert_step_to_json_macro(temp_path, "as1-oc-214.stp")
    print(f"\n✅ SUCCESS: JSON created at {json_path}")

    # Check file size and contents
    with open(json_path) as f:
        content = f.read()
        import json
        data = json.loads(content)

        colors = data.get('faces', {}).get('color', [])
        unique = set()
        for i in range(0, len(colors), 3):
            if i+2 < len(colors):
                c = (round(colors[i], 2), round(colors[i+1], 2), round(colors[i+2], 2))
                unique.add(c)

        print(f"\nJSON Content:")
        print(f"  Vertices: {len(data.get('vertices', []))}")
        print(f"  Triangles: {len(data.get('faces', {}).get('triangles', []))}")
        print(f"  Unique colors: {len(unique)}")
        for c in sorted(unique)[:10]:
            print(f"    - {c}")

except Exception as e:
    print(f"\n❌ FAILED: {e}")
    import traceback
    traceback.print_exc()
finally:
    # Cleanup
    try:
        os.unlink(temp_path)
    except:
        pass
