"""
NX Journal: Import expressions from .exp file

Usage: run_journal.exe import_expressions.py -args <prt_file> <exp_file>
"""
import sys
import NXOpen


def main(args):
    if len(args) < 2:
        print("[ERROR] Usage: import_expressions.py <prt_file> <exp_file>")
        sys.exit(1)

    prt_file = args[0]
    exp_file = args[1]

    theSession = NXOpen.Session.GetSession()

    # Open the part file
    partLoadStatus1 = None
    try:
        workPart, partLoadStatus1 = theSession.Parts.OpenActiveDisplay(
            prt_file,
            NXOpen.DisplayPartOption.AllowAdditional
        )
    finally:
        if partLoadStatus1:
            partLoadStatus1.Dispose()

    print(f"[JOURNAL] Opened part: {prt_file}")

    # Import expressions from .exp file
    markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Import Expressions")

    try:
        expModified, errorMessages = workPart.Expressions.ImportFromFile(
            exp_file,
            NXOpen.ExpressionCollection.ImportMode.Replace
        )

        print(f"[JOURNAL] Imported expressions from: {exp_file}")

        # expModified can be either a bool or an array depending on NX version
        if isinstance(expModified, bool):
            print(f"[JOURNAL] Import completed: {expModified}")
        else:
            print(f"[JOURNAL] Expressions modified: {len(expModified)}")

        if errorMessages:
            print(f"[JOURNAL] Import errors: {errorMessages}")

        # Update the part to apply expression changes
        markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "NX update")
        nErrs = theSession.UpdateManager.DoUpdate(markId2)
        theSession.DeleteUndoMark(markId2, "NX update")

        print(f"[JOURNAL] Part updated (errors: {nErrs})")

        # Save the part
        partSaveStatus = workPart.Save(
            NXOpen.BasePart.SaveComponents.TrueValue,
            NXOpen.BasePart.CloseAfterSave.FalseValue
        )
        partSaveStatus.Dispose()

        print(f"[JOURNAL] Part saved: {prt_file}")

        # Close all parts to ensure changes are written to disk and not cached in memory
        # This is critical so the solve journal loads the updated PRT from disk
        theSession.Parts.CloseAll(NXOpen.BasePart.CloseModified.UseResponses, None)
        print(f"[JOURNAL] All parts closed to release file")

    except Exception as e:
        print(f"[ERROR] Failed to import expressions: {e}")
        sys.exit(1)

    print("[JOURNAL] Expression import complete!")


if __name__ == '__main__':
    main(sys.argv[1:])
