' 调试: 单步 STEP 导出定位 "File already exists" 来源
Option Strict Off
Imports System
Imports System.IO
Imports System.Text
Imports NXOpen
Imports NXOpen.UF

Module DebugExport
    Sub Main()
        Dim sb As New StringBuilder()
        Dim cur As String = Directory.GetCurrentDirectory()
        Dim masterPath As String = Path.Combine(cur, "KC_master.prt")
        sb.AppendLine("CWD=" & cur & " masterExists=" & File.Exists(masterPath))
        Dim partLoadStatus1 As NXOpen.PartLoadStatus = Nothing
        Session.GetSession().Parts.OpenBaseDisplay(masterPath, partLoadStatus1)
        Dim w As Part = Session.GetSession().Parts.Work
        sb.AppendLine("Work=" & (If(w Is Nothing, "NULL", w.FullPath)))
        If w IsNot Nothing Then
            Dim ufs As UFSession = UFSession.GetUFSession()
            Try
                ufs.Modl.EditExp("stroke=87")
                ufs.Modl.Update()
                sb.AppendLine("EditExp+Update OK")
            Catch ex As Exception
                sb.AppendLine("EditExp/Update 失败: " & ex.Message)
            End Try
            ' 诊断: 实体数与引用集
            Dim bodyCount As Integer = 0
            Try
                For Each b As NXOpen.Body In w.Bodies
                    bodyCount += 1
                Next
            Catch
            End Try
            sb.AppendLine("实体数=" & bodyCount)
            Try
                For Each rs As NXOpen.ReferenceSet In w.GetAllReferenceSets()
                    sb.AppendLine("引用集: " & rs.Name)
                Next
            Catch ex As Exception
                sb.AppendLine("引用集枚举失败: " & ex.Message)
            End Try
            Dim outDir As String = Path.Combine(cur, "dbg_out")
            Directory.CreateDirectory(outDir)
            Dim stpPath As String = Path.Combine(outDir, "DBG.stp")
            If File.Exists(stpPath) Then File.Delete(stpPath)
            Try
                Dim sc As NXOpen.StepCreator = Session.GetSession().DexManager.CreateStepCreator()
                sc.ExportFrom = NXOpen.StepCreator.ExportFromOption.ExistingPart   ' 批处理无显示部件 → 直接处理部件文件
                sc.InputFile = masterPath
                sc.ExportAs = NXOpen.StepCreator.ExportAsOption.Ap214
                sc.OutputFile = stpPath
                sc.ColorAndLayers = True
                sc.Commit()
                sc.Destroy()
                sb.AppendLine("STEP 导出成功: " & stpPath & " size=" & (New FileInfo(stpPath)).Length)
            Catch ex As Exception
                sb.AppendLine("STEP 导出失败: " & ex.GetType().Name & " / " & ex.Message)
                Dim inner As Exception = ex.InnerException
                While inner IsNot Nothing
                    sb.AppendLine("  inner: " & inner.Message)
                    inner = inner.InnerException
                End While
            End Try
        End If
        File.WriteAllText(Path.Combine(cur, "debug-export.txt"), sb.ToString(), Encoding.UTF8)
    End Sub
End Module
