"""
NX Journal Script to Export Expressions to .exp File

This script exports all expressions from the work part to a .exp file.
The .exp format is NX's native expression export format and captures ALL expressions
including formulas, references, and unitless expressions.

Usage: run_journal.exe export_expressions.py <prt_file_path> <output_exp_path>
"""

import sys
import NXOpen


def main(args):
    """
    Export expressions from a .prt file to .exp format.

    Args:
        args: Command line arguments
              args[0]: .prt file path
              args[1]: output .exp file path (without .exp extension)
    """
    if len(args) < 2:
        print("ERROR: Not enough arguments")
        print("Usage: export_expressions.py <prt_file> <output_path>")
        return False

    prt_file_path = args[0]
    output_path = args[1]  # NX adds .exp automatically

    print(f"[JOURNAL] Exporting expressions from: {prt_file_path}")
    print(f"[JOURNAL] Output path: {output_path}.exp")

    try:
        theSession = NXOpen.Session.GetSession()

        # Close any currently open parts
        print("[JOURNAL] Closing any open parts...")
        try:
            partCloseResponses = [NXOpen.BasePart.CloseWholeTree]
            theSession.Parts.CloseAll(partCloseResponses)
        except:
            pass

        # Open the .prt file
        print(f"[JOURNAL] Opening part file...")
        basePart, partLoadStatus = theSession.Parts.OpenActiveDisplay(
            prt_file_path,
            NXOpen.DisplayPartOption.AllowAdditional
        )
        partLoadStatus.Dispose()

        workPart = theSession.Parts.Work

        if workPart is None:
            print("[JOURNAL] ERROR: No work part loaded")
            return False

        # Export expressions to .exp file
        print("[JOURNAL] Exporting expressions...")
        workPart.Expressions.ExportToFile(
            NXOpen.ExpressionCollection.ExportMode.WorkPart,
            output_path,
            NXOpen.ExpressionCollection.SortType.AlphaNum
        )

        print(f"[JOURNAL] Successfully exported expressions to: {output_path}.exp")
        return True

    except Exception as e:
        print(f"[JOURNAL] ERROR: {e}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == '__main__':
    success = main(sys.argv[1:])
    sys.exit(0 if success else 1)
