"""
Standalone expression extractor - opens part and extracts all expressions
Run with: ugraf.exe -run extract_expressions_standalone.py
"""
import NXOpen
import os
import json

def main():
    session = NXOpen.Session.GetSession()

    part_path = r"C:\Users\antoi\Atomizer\studies\m1_mirror_cost_reduction\1_setup\model\M1_Blank.prt"
    output_json = r"C:\Users\antoi\Atomizer\_expressions_output.json"
    output_txt = r"C:\Users\antoi\Atomizer\_expressions_output.txt"

    results = {'expressions': [], 'success': False, 'part': part_path}
    output_lines = []

    try:
        # Set load options
        working_dir = os.path.dirname(part_path)
        session.Parts.LoadOptions.ComponentLoadMethod = NXOpen.LoadOptions.LoadMethod.FromDirectory
        session.Parts.LoadOptions.SetSearchDirectories([working_dir], [True])

        # Open the part
        output_lines.append(f"Opening: {part_path}")
        basePart, loadStatus = session.Parts.OpenActiveDisplay(
            part_path,
            NXOpen.DisplayPartOption.AllowAdditional
        )
        loadStatus.Dispose()

        workPart = session.Parts.Work
        output_lines.append(f"Loaded: {workPart.Name}")
        output_lines.append("")
        output_lines.append("=" * 60)
        output_lines.append("EXPRESSIONS IN M1_Blank.prt")
        output_lines.append("=" * 60)

        # Extract expressions
        for expr in workPart.Expressions:
            try:
                name = expr.Name

                # Skip internal expressions (p0, p1, p123, etc.)
                if name.startswith('p') and len(name) > 1:
                    rest = name[1:]
                    # Check if rest is numeric (possibly with dots for decimals)
                    if rest.replace('.', '').replace('_', '').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,
                    'formula': rhs
                })

                units_str = f" [{units}]" if units else ""
                output_lines.append(f"{name}: {value}{units_str}")

            except Exception as e:
                output_lines.append(f"Error reading expression: {e}")

        results['success'] = True
        results['count'] = len(results['expressions'])
        output_lines.append("")
        output_lines.append(f"Total user expressions: {results['count']}")

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

    # Write outputs
    with open(output_json, 'w') as f:
        json.dump(results, f, indent=2)

    with open(output_txt, 'w') as f:
        f.write('\n'.join(output_lines))

    # Exit NX
    try:
        session.Parts.Work.Close(NXOpen.BasePart.CloseWholeTree.FalseValue,
                                  NXOpen.BasePart.CloseModified.CloseModified, None)
    except:
        pass

if __name__ == '__main__':
    main()
