"""Simple expression lister - writes to file regardless of print issues"""
import NXOpen
import os
import json

session = NXOpen.Session.GetSession()
output_lines = []
results = {'expressions': [], 'success': False}

try:
    # Get all open parts and find M1_Blank
    for part in session.Parts:
        part_name = part.Name if hasattr(part, 'Name') else str(part)
        if 'M1_Blank' in part_name and '_fem' not in part_name.lower() and '_i' not in part_name.lower():
            output_lines.append(f"Found part: {part_name}")

            for expr in part.Expressions:
                try:
                    name = expr.Name
                    # Skip internal expressions (p0, p1, etc.)
                    if name.startswith('p') and len(name) > 1:
                        rest = name[1:].replace('.', '').replace('_', '')
                        if rest.isdigit():
                            continue

                    value = expr.Value
                    units = expr.Units.Name if expr.Units else ''
                    rhs = expr.RightHandSide if hasattr(expr, 'RightHandSide') else ''

                    results['expressions'].append({
                        'name': name,
                        'value': value,
                        'units': units,
                        'rhs': rhs
                    })
                    output_lines.append(f"{name}: {value} {units}")
                except:
                    pass

            results['success'] = True
            break

except Exception as e:
    output_lines.append(f"Error: {str(e)}")
    results['error'] = str(e)

# Write to file
output_path = r"C:\Users\antoi\Atomizer\_expressions_output.json"
with open(output_path, 'w') as f:
    json.dump(results, f, indent=2)

# Also write text version
text_path = r"C:\Users\antoi\Atomizer\_expressions_output.txt"
with open(text_path, 'w') as f:
    f.write('\n'.join(output_lines))
