#!/usr/bin/env python3
"""Test JSON macro directly to see what's happening with colors"""

import sys
import os
import tempfile
import subprocess

# Test STEP 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\n")

# Create output directory
output_dir = tempfile.mkdtemp()
output_json = os.path.join(output_dir, "test_model.json")

print(f"📁 Output directory: {output_dir}\n")

# Create the same script as macro function
script_content = f"""
import FreeCAD
import Part
import Import
import os
import sys

def log(msg):
    print(f"[JSON-MACRO] {{msg}}", flush=True)

# GUI modüllerini yükle
try:
    import FreeCADGui
    FreeCADGui.showMainWindow()
    import ImportGui
    log("GUI modulleri yuklendi")
except Exception as e:
    log(f"GUI yuklenemedi: {{e}}")
    raise

# STEP dosyasını yükle
doc = FreeCAD.newDocument("TempDoc")
FreeCADGui.ActiveDocument = FreeCADGui.getDocument("TempDoc")

try:
    # XCAF parametreleri
    param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Import/hSTEP")
    param.SetInt("ReadShapeCompoundMode", 0)
    param.SetBool("UseLinkGroup", False)
    param.SetBool("ImportHiddenObjects", True)
    param.SetBool("ReduceObjects", False)
    param.SetBool("ExpandCompound", True)
    param.SetBool("ShowProgress", False)
    param.SetInt("ImportMode", 0)

    log("STEP import parametreleri ayarlandi (XCAF color mode)")
    log("STEP dosyasi ImportGui.insert() ile yukleniyor: {test_file}")

    # ImportGui ile yükle
    ImportGui.insert("{test_file}", "TempDoc")
    log("ImportGui.insert basarili")

    # Parts al
    parts = [obj for obj in doc.Objects if hasattr(obj, 'Shape') and obj.Shape and len(obj.Shape.Faces) > 0]

    if not parts:
        raise Exception("STEP dosyasinda hic geometri bulunamadi")

    log(f"{{len(parts)}} adet Part nesnesi bulundu")

    # Document recompute
    doc.recompute()
    log("Document recomputed")

    # Selection'a ekle
    FreeCADGui.Selection.clearSelection()
    for obj in parts:
        FreeCADGui.Selection.addSelection(obj)
    log(f"{{len(parts)}} obje Selection'a eklendi")

    # Her part için renk kontrol et
    log("=" * 50)
    log("RENK OKUMA DEBUGU:")
    log("=" * 50)

    for part_idx, obj in enumerate(parts):
        shape = obj.Shape
        log(f"Part[{{part_idx}}] {{obj.Label}}: {{len(shape.Faces)}} face")

        # ViewObject var mı kontrol et
        if not hasattr(obj, 'ViewObject'):
            log("  ⚠️ ViewObject yok!")
            continue

        log(f"  ViewObject: {{obj.ViewObject}}")

        # DiffuseColor kontrol et
        if hasattr(obj.ViewObject, 'DiffuseColor'):
            diffuse = obj.ViewObject.DiffuseColor
            log(f"  ✅ DiffuseColor var: type={{type(diffuse).__name__}}, len={{len(diffuse) if diffuse else 'None'}}")
            if diffuse and len(diffuse) > 0:
                for i, color in enumerate(diffuse[:3]):
                    if isinstance(color, (tuple, list)):
                        log(f"     Color[{{i}}]: {{color}}")
                    else:
                        log(f"     Color[{{i}}]: {{color}} (type: {{type(color).__name__}})")
        else:
            log("  ❌ DiffuseColor yok!")

        # ShapeColor kontrol et
        if hasattr(obj.ViewObject, 'ShapeColor'):
            shape_color = obj.ViewObject.ShapeColor
            log(f"  ✅ ShapeColor var: {{shape_color}}")
        else:
            log("  ❌ ShapeColor yok!")

    log("=" * 50)

    # Şimdi JSON üret (basit)
    import json
    import MeshPart

    vertices = []
    triangles = []
    colors = []

    for part_idx, obj in enumerate(parts):
        shape = obj.Shape

        # Renk belirle
        color = (0.8, 0.8, 0.8)  # default
        if hasattr(obj.ViewObject, 'DiffuseColor'):
            diff = obj.ViewObject.DiffuseColor
            if diff and len(diff) > 0:
                c = diff[0]
                color = (float(c[0]), float(c[1]), float(c[2]))
                log(f"Part[{{part_idx}}] kullanilan renk: {{color}}")

        # Triangulate
        v_offset = len(vertices)
        for face in shape.Faces:
            mesh = MeshPart.meshFromShape(face, LinearDeflection=0.1, AngularDeflection=0.5)
            for tri in mesh.Facets:
                p = getattr(tri, "Points", None)
                if p:
                    v0 = len(vertices)
                    v1 = len(vertices) + 1
                    v2 = len(vertices) + 2
                    vertices.append(list(p[0]))
                    vertices.append(list(p[1]))
                    vertices.append(list(p[2]))
                    triangles.append([v0, v1, v2])
                    colors.extend([color[0], color[1], color[2]] * 3)

    # JSON output
    out = {{
        "vertices": vertices,
        "faces": {{
            "triangles": triangles,
            "color": colors
        }},
        "object_name": "Model"
    }}

    output_path = r"{output_json}"
    log(f"JSON'a yazılıyor: {{output_path}}")
    log(f"  Vertices: {{len(vertices)}}")
    log(f"  Triangles: {{len(triangles)}}")
    log(f"  Colors: {{len(colors)}} values")

    # Unique colors check
    unique_colors = 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_colors.add(c)
    log(f"  Unique colors: {{len(unique_colors)}}")
    for c in sorted(unique_colors):
        log(f"    - {{c}}")

    with open(output_path, "w") as f:
        json.dump(out, f)

    log("✅ JSON conversion complete!")

except Exception as e:
    log(f"❌ HATA: {{e}}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
finally:
    try:
        FreeCAD.closeDocument("TempDoc")
        log("TempDoc closed")
    except:
        pass
"""

script_path = os.path.join(output_dir, "test_macro.py")
with open(script_path, 'w') as f:
    f.write(script_content)

print(f"📝 Script created: {script_path}\n")

# Run with xvfb-run
print("🚀 Running with xvfb-run...\n")
cmd = ['xvfb-run', '-a', '-s', '-screen 0 1920x1080x24', 'python3', script_path]

result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)

print("=" * 60)
print("STDOUT:")
print("=" * 60)
print(result.stdout if result.stdout else "(no output)")

print("\n" + "=" * 60)
print("STDERR:")
print("=" * 60)
print(result.stderr if result.stderr else "(no errors)")

print("\n" + "=" * 60)
print(f"Return code: {result.returncode}")
print("=" * 60)

# Check output
if os.path.exists(output_json):
    print(f"\n✅ JSON created: {output_json}")
    import json
    with open(output_json) as f:
        data = json.load(f)

    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"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):
        print(f"  - {c}")
else:
    print(f"\n❌ JSON not created!")
