"""
STEP to GLB Converter - FIXED VERSION
Label issue resolved - meshes exported directly without metadata
"""

import sys
import json
from pathlib import Path
from datetime import datetime

print("=" * 70)
print("STEP to GLB Converter - Fixed Version")
print("=" * 70)

# Import FreeCAD modules
try:
    print("Importing FreeCAD modules...")
    import FreeCAD
    import Import
    import Mesh
    print(f"✓ FreeCAD Version: {FreeCAD.Version()}")
except ImportError as e:
    print(f"✗ ERROR: FreeCAD modules not found: {e}")
    print("This script must be run with FreeCAD Python environment")
    sys.exit(1)

# ============================================================================
# CONFIGURATION
# ============================================================================
STEP_FILE = Path("D:\\__sistem__\\ProgramFiles\\FreeCAD\\bin\\freecad.stp")
OUTPUT_FILE = None  # None = auto (same name, same folder)

# Mesh settings
MESH_TOLERANCE = 0.1  # Increased from 0.05 - try coarser mesh first
EXPORT_EDGES = False  # Disabled to simplify

# Colors
DEFAULT_COLOR = (0.8, 0.8, 0.8)

# ============================================================================

def safe_get_color(body, face_index):
    """Get color safely"""
    try:
        if hasattr(body, 'ViewObject') and hasattr(body.ViewObject, 'DiffuseColor'):
            colors = body.ViewObject.DiffuseColor
            if colors:
                return colors[face_index % len(colors)]
    except:
        pass
    return DEFAULT_COLOR


def safe_get_alpha(body):
    """Get transparency safely"""
    try:
        if hasattr(body, 'ViewObject'):
            trans = getattr(body.ViewObject, 'Transparency', 0)
            return 1.0 - (trans / 100.0)
    except:
        pass
    return 1.0


def create_face_mesh(face, body, body_idx, face_idx):
    """Create mesh from face - SIMPLIFIED VERSION"""
    try:
        print(f"    Tessellating face {face_idx}...", end=" ")
        
        # Tessellate face
        mesh = Mesh.Mesh(face.tessellate(MESH_TOLERANCE))
        
        if mesh.CountFacets == 0:
            print(f"NO FACETS")
            return None
        
        print(f"✓ {mesh.CountFacets} facets")
        
        # Try to apply colors (optional)
        try:
            color = safe_get_color(body, face_idx)
            alpha = safe_get_alpha(body)
            
            # Create color list for all vertices
            num_facets = mesh.CountFacets
            colors = []
            for _ in range(num_facets):
                colors.append((color[0], color[1], color[2], alpha))
            
            mesh.VertexColors = colors
            print(f"      → Colors applied")
        except AttributeError:
            print(f"      → Colors not supported in this FreeCAD version")
        except Exception as e:
            print(f"      → Color warning: {e}")
        
        return mesh
        
    except Exception as e:
        print(f"FAILED: {e}")
        return None


def main():
    print("\n" + "=" * 70)
    print("Configuration:")
    print(f"  Input: {STEP_FILE}")
    print(f"  Exists: {STEP_FILE.exists()}")
    if STEP_FILE.exists():
        print(f"  Size: {STEP_FILE.stat().st_size} bytes")
    print(f"  Mesh Tolerance: {MESH_TOLERANCE}")
    print(f"  Export Edges: {EXPORT_EDGES}")
    print("=" * 70)
    
    # Validate input
    if not STEP_FILE.exists():
        print(f"\n✗ ERROR: File not found: {STEP_FILE}")
        return 1
    
    if STEP_FILE.suffix.lower() not in ['.stp', '.step']:
        print(f"\n✗ ERROR: Invalid file type: {STEP_FILE.suffix}")
        return 1
    
    # Determine output
    if OUTPUT_FILE:
        output_path = OUTPUT_FILE
    else:
        output_path = STEP_FILE.with_suffix('.glb')
    
    print(f"\nOutput: {output_path}")
    
    doc = None
    
    try:
        # Open STEP file
        print("\n" + "=" * 70)
        print("STEP 1: Opening STEP file...")
        print("=" * 70)
        
        Import.open(str(STEP_FILE))
        doc = FreeCAD.ActiveDocument
        
        if not doc:
            print("✗ Failed to open document")
            return 1
        
        print(f"✓ Document opened: {doc.Name}")
        print(f"✓ Total objects: {len(doc.Objects)}")
        
        # List all objects
        print("\nObjects in document:")
        for i, obj in enumerate(doc.Objects):
            has_shape = hasattr(obj, 'Shape') and obj.Shape
            shape_info = ""
            if has_shape:
                shape_info = f" - Faces: {len(obj.Shape.Faces)}"
            print(f"  [{i}] {obj.Label} (Type: {obj.TypeId}){shape_info}")
        
        # Process bodies
        print("\n" + "=" * 70)
        print("STEP 2: Processing bodies...")
        print("=" * 70)
        
        meshes = []
        stats = {"faces": 0, "bodies": 0, "total_facets": 0}
        
        for body_idx, body in enumerate(doc.Objects):
            if not hasattr(body, 'Shape') or not body.Shape:
                continue
            
            body_label = getattr(body, 'Label', f'Body{body_idx}')
            face_count = len(body.Shape.Faces)
            
            if face_count == 0:
                continue
            
            print(f"\nBody {body_idx}: {body_label} ({face_count} faces)")
            
            body_mesh_count = 0
            
            # Process faces
            for face_idx, face in enumerate(body.Shape.Faces):
                face_mesh = create_face_mesh(face, body, body_idx, face_idx)
                if face_mesh:
                    meshes.append(face_mesh)
                    stats["faces"] += 1
                    stats["total_facets"] += face_mesh.CountFacets
                    body_mesh_count += 1
            
            if body_mesh_count > 0:
                stats["bodies"] += 1
                print(f"  → Body complete: {body_mesh_count} face meshes created")
        
        # Check results
        print("\n" + "=" * 70)
        print("STEP 3: Export Summary")
        print("=" * 70)
        print(f"Total meshes to export: {len(meshes)}")
        print(f"  Bodies processed: {stats['bodies']}")
        print(f"  Faces meshed: {stats['faces']}")
        print(f"  Total facets: {stats['total_facets']}")
        
        if len(meshes) == 0:
            print("\n✗ ERROR: No meshes created!")
            print("\nPossible reasons:")
            print("  1. STEP file contains no solid geometry")
            print("  2. All faces failed tessellation")
            print("  3. Try increasing MESH_TOLERANCE (currently: {})".format(MESH_TOLERANCE))
            print("\nTry changing MESH_TOLERANCE to 0.5 or 1.0")
            return 1
        
        # Export
        print(f"\nExporting to: {output_path}")
        
        # Try export with different methods
        try:
            print("Attempting export...")
            Import.export(meshes, str(output_path))
        except Exception as e:
            print(f"✗ Export failed: {e}")
            
            # Try alternative: merge all meshes first
            print("\nTrying alternative: merging meshes...")
            merged = Mesh.Mesh()
            for m in meshes:
                merged.addMesh(m)
            
            print(f"Merged mesh: {merged.CountFacets} facets")
            Import.export([merged], str(output_path))
        
        # Verify
        if not output_path.exists():
            print("✗ ERROR: Output file was not created!")
            return 1
        
        size_kb = output_path.stat().st_size / 1024
        print(f"\n✓ File created: {size_kb:.2f} KB")
        
        print("\n" + "=" * 70)
        print("✓ SUCCESS!")
        print("=" * 70)
        print(f"Output: {output_path}")
        
        return 0
        
    except Exception as e:
        print(f"\n✗ FATAL ERROR: {e}")
        import traceback
        traceback.print_exc()
        return 1
        
    finally:
        if doc:
            try:
                print("\nClosing document...")
                FreeCAD.closeDocument(doc.Name)
                print("✓ Document closed")
            except Exception as e:
                print(f"⚠ Could not close document: {e}")


if __name__ == "__main__":
    print("\n[Starting execution...]")
    try:
        exit_code = main()
        print(f"\nExit code: {exit_code}")
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n\n✗ Interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n✗ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)