#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test the JSON macro function directly"""

import sys
import os
import tempfile

# Add freecad_api_server to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from freecad_api_server import _convert_step_to_json_macro, _convert_step_to_json

# Test file
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)

print(f"✅ Test file found: {test_file}")
print(f"📊 File size: {os.path.getsize(test_file)} bytes")

# Test macro method
print("\n" + "="*60)
print("Testing MACRO method (ImportGui + colors)...")
print("="*60)

try:
    json_path = _convert_step_to_json_macro(test_file, "test_model.stp")
    print(f"\n✅ Macro succeeded!")
    print(f"JSON saved to: {json_path}")

    # Read and analyze colors
    import json
    with open(json_path, 'r') as f:
        data = json.load(f)

    print(f"📊 Vertices: {len(data.get('vertices', []))}")
    print(f"📊 Triangles: {len(data.get('faces', {}).get('triangles', []))}")

    colors = data.get('faces', {}).get('color', [])
    print(f"📊 Colors in vertex_colors array: {len(colors)} values")

    # Extract unique colors (every 3 values = 1 color)
    unique_colors = set()
    for i in range(0, len(colors), 3):
        if i+2 < len(colors):
            color = tuple([round(colors[i], 2), round(colors[i+1], 2), round(colors[i+2], 2)])
            unique_colors.add(color)

    print(f"🎨 Unique colors: {len(unique_colors)}")
    for color in sorted(unique_colors):
        print(f"   - {color}")

    # Cleanup
    try:
        os.unlink(json_path)
    except:
        pass

except Exception as e:
    print(f"\n❌ Macro failed: {e}")
    import traceback
    traceback.print_exc()

# Test old method for comparison
print("\n" + "="*60)
print("Testing OLD method (Import.insert, no colors)...")
print("="*60)

try:
    # Copy test file to temp location since _convert_step_to_json deletes it
    with tempfile.NamedTemporaryFile(delete=False, suffix='.stp') as tf:
        temp_path = tf.name
        with open(test_file, 'rb') as f:
            tf.write(f.read())

    json_path = _convert_step_to_json(temp_path, "test_model.stp")
    print(f"\n✅ Old method succeeded!")
    print(f"JSON saved to: {json_path}")

    # Read and analyze colors
    import json
    with open(json_path, 'r') as f:
        data = json.load(f)

    print(f"📊 Vertices: {len(data.get('vertices', []))}")
    print(f"📊 Triangles: {len(data.get('faces', {}).get('triangles', []))}")

    colors = data.get('faces', {}).get('color', [])
    print(f"📊 Colors in array: {len(colors)} values")

    # Extract unique colors (every 3 values = 1 color)
    unique_colors = set()
    for i in range(0, len(colors), 3):
        if i+2 < len(colors):
            color = tuple([round(colors[i], 2), round(colors[i+1], 2), round(colors[i+2], 2)])
            unique_colors.add(color)

    print(f"🎨 Unique colors: {len(unique_colors)}")
    for color in sorted(unique_colors):
        print(f"   - {color}")

    # Cleanup
    try:
        os.unlink(json_path)
    except:
        pass

except Exception as e:
    print(f"\n❌ Old method failed: {e}")
    import traceback
    traceback.print_exc()

print("\n" + "="*60)
print("Test complete!")
print("="*60)
