﻿' 本文件由 原型\构建.ps1 拼接生成（头.vb + Core.vb + [SemCalc.vb] + 插件壳），请改 源码\ 下的文件，不要直接改这里。
' 脚本插件：放进 %LOCALAPPDATA%\AmosDevelopment\Amos\<版本号>\Plugins\ 即可，AMOS 自己编译。须保存为 UTF-8 带 BOM。
' 已验证 AMOS 版本：30（见 方案调研.md §十一）；其余版本未验证。
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports System.Windows.Forms
Imports Microsoft.VisualBasic
Imports Amos
Imports AmosEngineLib
Imports AmosEngineLib.AmosEngine.TMatrixID

' ============================================================================
' Core.vb —— 取数、计算、HTML 输出。「CFA 报告」与「SEM 报告」共用。
' 本文件不含 Imports 和插件类：由 构建.ps1 与 头.vb、各插件的 *.part.vb 拼成单个 .vb 发布
' （AMOS 一个插件文件里只能有一个插件类，所以共用代码靠构建时拼接，不靠引用）。
'
' 兼容性约束（已在 AMOS 30 验证；24 只验证了「同一份源码能对 24 的程序集编译通过」）：
'   · 脚本编译环境只引用 mscorlib、System、System.Windows.Forms、System.Drawing、Microsoft.VisualBasic、
'     Amos*、System.ComponentModel.Composition；没有 System.Core（LINQ）、System.Xml、System.Data、
'     System.IO.Compression。所以不用 LINQ，不用 HashSet，不用 XML 类。
'   · AMOS 路径图类在 24–28 叫 pd，29 起叫 Pd；VB 不区分大小写，一律写 pd。
'   · CDatabaseFormat 在 24 里叫 cDatabaseFormat，同理。
'   · 引擎的声明类方法（Standardized、NeedEstimates、NeedStandardErrors、SetSaturatedFit…）必须在 SpecifyModel 之前调。
'   · 不同时存在两个 AmosEngine 对象：先释放一个，再开下一个。
' ============================================================================

' ---------------------------------------------------------------- 各插件共用的常量
Friend Class PluginInfo
    ' 菜单显示名的统一前缀。AMOS 的 Plugins 菜单按显示名转小写后逐字符（序数）比较排序，
    ' 「+」（0x2B）排在字母与数字之前，所以本套插件都排在 AMOS 自带插件的前面。
    Public Const MenuPrefix As String = "+ "
End Class

' ---------------------------------------------------------------- 报告用语：中英文对照与斜体标记
' 表里的数据（RTable 的 Cols、Rows）一律存中文原文，核对脚本按原文取数；排版时再按这里登记的对照输出中文、英文两套。
' 显示文字里用一对星号标出要排斜体的统计符号（*p*、*df*、*SE*、*N*、*b*）；希腊字母与缩写不排斜体（APA 第 7 版）。
' 只有表题、列名、论文表注、结果行文过这一层；页面上的说明、诊断、摘要是给学员看的，只有中文。
Friend Class Tx
    Private Shared ZhMap As New Dictionary(Of String, String)()
    Private Shared EnMap As New Dictionary(Of String, String)()
    Private Shared Ready As Boolean = False

    ' 登记：原文 → 中文显示、英文显示（中文显示可以与原文不同，如「S.E.」显示成 *SE*）
    Public Shared Sub Reg(ByVal key As String, ByVal zhText As String, ByVal enText As String)
        Init()
        ZhMap(key) = zhText
        EnMap(key) = enText
    End Sub

    ' 就地登记英文并返回中文原文：t.Title = Tx.T("结构路径", "Structural Paths")
    Public Shared Function T(ByVal zhText As String, ByVal enText As String) As String
        Init()
        EnMap(zhText) = enText
        Return zhText
    End Function

    Public Shared Function Has(ByVal key As String) As Boolean
        Init()
        Return EnMap.ContainsKey(key)
    End Function

    Public Shared Function Zh(ByVal key As String) As String
        Init()
        If ZhMap.ContainsKey(key) Then Return ZhMap(key)
        Return key
    End Function

    Public Shared Function En(ByVal key As String) As String
        Init()
        If EnMap.ContainsKey(key) Then Return EnMap(key)
        Return Zh(key)
    End Function

    ' 行名（模型名、层级名一类写在单元格里的固定用语）单独登记：单元格里多数是学员自己的变量名，
    ' 不能拿去查列名的对照（否则名叫 N、p 的变量会被改写）。登记后同一文字作列名时也有英文
    Private Shared RowZhMap As New Dictionary(Of String, String)()
    Private Shared RowEnMap As New Dictionary(Of String, String)()

    Public Shared Function Row(ByVal zhText As String, ByVal enText As String) As String
        Return Row3(zhText, zhText, enText)
    End Function

    ' 原文、中文显示、英文显示（中文显示与原文不同时用，如「基准模型（Baseline）」显示成「基准模型」）
    Public Shared Function Row3(ByVal key As String, ByVal zhText As String, ByVal enText As String) As String
        Init()
        RowZhMap(key) = zhText
        RowEnMap(key) = enText
        ZhMap(key) = zhText
        EnMap(key) = enText
        Return key
    End Function

    Public Shared Function HasRow(ByVal key As String) As Boolean
        Init()
        Return RowEnMap.ContainsKey(key)
    End Function

    Public Shared Function RowZh(ByVal key As String) As String
        If RowZhMap.ContainsKey(key) Then Return RowZhMap(key)
        Return key
    End Function

    Public Shared Function RowEn(ByVal key As String) As String
        If RowEnMap.ContainsKey(key) Then Return RowEnMap(key)
        Return key
    End Function

    Private Shared Sub Same(ByVal key As String, ByVal text As String)
        ZhMap(key) = text
        EnMap(key) = text
    End Sub

    Private Shared Sub Two(ByVal key As String, ByVal zhText As String, ByVal enText As String)
        ZhMap(key) = zhText
        EnMap(key) = enText
    End Sub

    ' 各插件共用的列名与行名
    Private Shared Sub Init()
        If Ready Then Return
        Ready = True
        ' ---- 统计符号
        Same("p", "*p*")
        Same("df", "*df*")
        Same("N", "*N*")
        Same("b", "*b*")
        Same("z", "*z*")
        Same("S.E.", "*SE*")
        Same("C.R.", "C.R.")
        Same("c.r.", "C.R.")
        Same("R²", "*R*²")
        Same("SMC (R²)", "*R*²")
        Same("χ²/df", "χ²/*df*")
        Same("Δdf", "Δ*df*")
        Same("非标准化估计 b", "*b*")
        Same("估计 b", "*b*")
        Same("标准化系数 β", "β")
        Same("被解释的比例 β²", "*R*²")
        Same("相关 r", "*r*")
        Same("S.E.（bootstrap）", "Bootstrap *SE*")
        Same("BC 95% 区间", "95% CI")
        Same("Wald 95% 区间", "Wald 95% CI")
        Same("BC 95% 区间（bootstrap）", "Bootstrap 95% CI")
        Two("Δχ²（Δdf）", "Δχ²（Δ*df*）", "Δχ² (Δ*df*)")
        Two("RMSEA（AMOS 口径）", "RMSEA（AMOS）", "RMSEA (AMOS)")
        Two("RMSEA（× √G 口径）", "RMSEA（× √*G*）", "RMSEA (× √*G*)")
        Two("RMSEA（AMOS）", "RMSEA（AMOS）", "RMSEA (AMOS)")
        Two("RMSEA（× √G）", "RMSEA（× √*G*）", "RMSEA (× √*G*)")
        Two("ΔRMSEA（AMOS）", "ΔRMSEA（AMOS）", "ΔRMSEA (AMOS)")
        Two("ΔRMSEA（× √G）", "ΔRMSEA（× √*G*）", "ΔRMSEA (× √*G*)")
        ' ---- 列名
        Two("构念", "构念", "Construct")
        Two("题项", "题项", "Item")
        Two("因子", "因子", "Factor")
        Two("变量", "变量", "Variable")
        Two("模型", "模型", "Model")
        Two("路径", "路径", "Path")
        Two("组", "组", "Group")
        Two("层级", "模型", "Model")
        Two("阶段", "模型", "Model")
        Two("步", "步骤", "Step")
        Two("标准化载荷 β", "标准化载荷", "Standardized loading")
        Two("题项数", "题项数", "No. of items")
        Two("载荷范围", "标准化载荷范围", "Loading range")
        Two("标准化载荷范围", "标准化载荷范围", "Loading range")
        Two("Cronbach α", "Cronbach α", "Cronbach’s α")
        Two("α（标准化）", "标准化 α", "Standardized α")
        Two("参数个数", "参数个数", "Parameters")
        Two("估计参数个数", "参数个数", "Parameters")
        Two("标准化估计", "标准化估计", "Standardized estimate")
        Two("自变量 → 因变量", "路径", "Path")
        Two("直接效应", "直接效应", "Direct effect")
        Two("间接效应", "间接效应", "Indirect effect")
        Two("间接效应 BC 95% 区间", "间接效应 95% CI", "Indirect effect 95% CI")
        Two("总效应", "总效应", "Total effect")
        Two("总效应 BC 95% 区间", "总效应 95% CI", "Total effect 95% CI")
        Two("标准化总效应", "标准化总效应", "Standardized total effect")
        Two("模型（约束更多）", "模型", "Model")
        Two("比较（约束多的 对 约束少的）", "模型比较", "Comparison")
        Two("比较", "模型比较", "Comparison")
        Two("因子对", "因子对", "Factor pair")
        Two("构念对", "构念对", "Construct pair")
        Two("约束后 χ²", "约束模型 χ²", "Constrained χ²")
        Two("高阶因子", "高阶因子", "Higher-order factor")
        Two("一阶因子", "一阶因子", "First-order factor")
        Two("一阶因子数", "一阶因子数", "No. of first-order factors")
        Two("本步 χ² 下降", "本步 χ² 下降", "χ² decrease")
        Two("差值", "差值", "Difference")
        Two("方法载荷", "方法载荷", "Method loading")
        Two("方法载荷的平方", "方法载荷的平方", "Squared method loading")
        Two("实质载荷（含方法载荷）", "实质载荷（加入方法因子后）", "Substantive loading (with method factor)")
        Two("最小值", "最小值", "Min")
        Two("最大值", "最大值", "Max")
        Two("偏度", "偏度", "Skewness")
        Two("峰度", "峰度", "Kurtosis")
        ' ---- 行名
        Row("　总间接效应", "　Total indirect effect")
        Row("多元（Mardia）", "Multivariate (Mardia)")
    End Sub
End Class

' ---------------------------------------------------------------- 行文里的统计量写法（APA 第 7 版；小数点前的 0 保留，用户 2026-10-13 定）
Friend Class Ap
    ' 数字前的连字符换成负号（U+2212）
    Public Shared Function Minus(ByVal s As String) As String
        If s Is Nothing OrElse s.IndexOf("-"c) < 0 Then Return s
        Return System.Text.RegularExpressions.Regex.Replace(s, "(^|[\s\[\(（,，=：])-(?=[\d.])", "$1−")
    End Function

    ' 由表里印出的 p（「< 0.001」「0.012」）得到行文写法：*p* < 0.001、*p* = 0.012
    Public Shared Function PEq(ByVal pText As String) As String
        If pText Is Nothing OrElse pText = "" OrElse pText = "—" Then Return "*p* —"
        If pText.StartsWith("<") Then Return "*p* " & pText
        Return "*p* = " & pText
    End Function

    Public Shared Function PVal(ByVal p As Double) As String
        Return PEq(Calc.PText(p))
    End Function

    Public Shared Function Chi(ByVal df As Integer, ByVal x As Double) As String
        Return "χ²(" & df.ToString() & ") = " & Calc.N3(x)
    End Function

    Public Shared Function ChiN(ByVal df As Integer, ByVal n As Integer, ByVal x As Double) As String
        Return "χ²(" & df.ToString() & ", *N* = " & n.ToString() & ") = " & Calc.N3(x)
    End Function

    ' 英文表注里拟合指标缩写的全称（APA 要求表内缩写在表注里交代；中文稿一般不写）
    Public Const AbbrFit As String = "CFI = comparative fit index; TLI = Tucker–Lewis index; RMSEA = root-mean-square error of approximation."
    Public Const AbbrIc As String = "AIC = Akaike information criterion; BIC = Bayesian information criterion."

    Public Shared Function DChi(ByVal ddf As Integer, ByVal d As Double) As String
        Return "Δχ²(" & ddf.ToString() & ") = " & Calc.N3(d)
    End Function

    ' 由表里印出的两个字符串拼「Δχ²(Δdf) = …，p …」（中英文相同，逗号由调用方选）
    Public Shared Function DChiP(ByVal dText As String, ByVal ddfText As String, ByVal pText As String, ByVal sep As String) As String
        Return "Δχ²(" & ddfText & ") = " & Minus(dText) & sep & PEq(pText)
    End Function

    ' 一组数的最小值、最大值
    Public Shared Sub Range(ByVal xs As List(Of Double), ByRef lo As Double, ByRef hi As Double)
        lo = Double.NaN
        hi = Double.NaN
        For Each x As Double In xs
            If Double.IsNaN(x) Then Continue For
            If Double.IsNaN(lo) OrElse x < lo Then lo = x
            If Double.IsNaN(hi) OrElse x > hi Then hi = x
        Next
    End Sub
End Class

' ---------------------------------------------------------------- 对话框按屏幕缩放比例放大
' 插件的对话框按 96 DPI 的像素写位置与尺寸。AMOS 是感知 DPI 的程序：高分屏（如 175% 缩放）上字体会随 DPI 放大，
' 而控件的位置与尺寸不变，文字就被截断（2026-10-09 窗口实测发现）。每个对话框在加完控件之后调用 UiScale.Fit(Me)。
Friend Class UiScale
    Public Shared Sub Fit(ByVal f As Form)
        Try
            Dim g As System.Drawing.Graphics = f.CreateGraphics()
            Dim k As Single = g.DpiX / 96.0F
            g.Dispose()
            If k > 1.01F Then f.Scale(New System.Drawing.SizeF(k, k))
        Catch
        End Try
    End Sub
End Class

' ---------------------------------------------------------------- 引擎取出的数据（引擎释放后仍可用）
Friend Class ModelData
    Public AmwPath As String = ""
    Public NGroups As Integer = 1
    Public Fmt As MiscAmosTypes.CDatabaseFormat
    Public FileName As String = ""
    Public TableName As String = ""
    Public GroupVar As String = ""            ' 第 1 组的分组变量与取值（没有分组时为空）
    Public GroupVal As Object = Nothing
    Public NCases As Integer
    Public HasMissing As Boolean
    Public FitStatus As Integer = -1
    Public FitMessage As String = ""
    Public Cmin As Double, Df As Integer, Npar As Integer, PVal As Double
    Public Rmsea As Double, RmseaLo As Double, RmseaHi As Double
    Public Admissible As Boolean = True, Stable As Boolean = True
    Public BaseOK As Boolean, BaseCmin As Double, BaseDf As Integer
    Public SatOK As Boolean, SatCmin As Double, IndCmin As Double
    Public Obs() As String
    Public RowNames() As String, ColNames() As String
    Public Dir(,) As Double, StdDir(,) As Double
    Public Tot(,) As Double, Ind(,) As Double, StdTot(,) As Double, StdInd(,) As Double   ' 总效应、间接效应（非标准化与标准化）
    Public BootN As Integer
    Public BootDirect As List(Of Double(,))                       ' 每个 bootstrap 样本的直接效应矩阵
    Public BcLo(,) As Double, BcHi(,) As Double                   ' 间接效应的 BC 区间
    Public BcLoTot(,) As Double, BcHiTot(,) As Double             ' 总效应的 BC 区间
    Public BcLoDir(,) As Double, BcHiDir(,) As Double             ' 直接效应的 BC 区间
    Public SeDir(,) As Double, SeInd(,) As Double, SeTot(,) As Double   ' bootstrap 标准误
    Public ParamEst As New Dictionary(Of String, Double)()   ' 键「因变量|自变量」：回归权重的估计
    Public ParamSe As New Dictionary(Of String, Double)()    ' 同键：S.E.（取自参数协方差矩阵，与 AMOS 输出表一致）
    Public ParamCov As New Dictionary(Of String, Double)()   ' 两个回归参数键以Tab连接，保存完整协方差
    Public RegressionLabels As New List(Of String)()
    Public AllCov(,) As Double
    Public CovAllNames() As String
    Public SampleMean() As Double
    Public MeanNames() As String
    Public BootSeed As Integer = 2026
    Public BootPlanned As Integer
    Public AllNames() As String, AllCor(,) As Double
    Public ImpNames() As String, ImpCor(,) As Double
    Public CovNames() As String, Cov(,) As Double, Cor(,) As Double
    Public CovSource As String = ""
    Public ErrorCovPairs As New List(Of String)()
    Public DiagramOrder As New List(Of String)()   ' 路径图里观测变量、潜变量的出现次序（引擎自己的次序是反的）
    Public Notes As New List(Of String)()
End Class

Friend Delegate Sub EngineSetup(ByVal sem As AmosEngine)

' ---------------------------------------------------------------- 取数
Friend Class Collector
    Public Shared Function Run() As ModelData
        Dim m As New ModelData()
        m.AmwPath = pd.AmwFileName()
        m.NGroups = pd.GetNGroups()
        ReadDiagram(m)
        Return FitCore(m, Nothing)
    End Function

    ' 核验与生产共用同一取数实现；外壳只提供模型，不提供估计结果。
    Public Shared Function RunForModel(ByVal setup As EngineSetup, ByVal modelPath As String, ByVal order As List(Of String), Optional ByVal groups As Integer = 1) As ModelData
        Dim m As New ModelData()
        m.AmwPath = modelPath
        m.NGroups = groups
        m.DiagramOrder.AddRange(order)
        Return FitCore(m, setup)
    End Function

    Private Shared Function FitCore(ByVal m As ModelData, ByVal setup As EngineSetup) As ModelData
        Pass(m, False, 0, 0, setup)
        If m.FitStatus <> 0 Then Return m
        If m.HasMissing Then
            ' 有缺失值（FIML）：先分别拟合饱和模型与独立模型（都估计均值），再把两个 χ² 回填给主模型
            FitSatInd(m)
            If m.SatOK Then
                Pass(m, True, m.SatCmin, m.IndCmin, setup)
                m.BaseCmin = m.IndCmin - m.SatCmin
                ' AMOS 在 FIML 下的独立模型自由度是 p(p+1)/2（10-2 的输出：独立模型 NPAR 19、DF 190），不是 p(p-1)/2；CFI 对此不敏感，TLI 敏感
                m.BaseDf = m.Obs.Length * (m.Obs.Length + 1) \ 2
                m.BaseOK = True
            End If
        Else
            FitIndependence(m)
        End If
        Return m
    End Function

    ' bootstrap 一遍（只有完整数据能做）：取各样本的直接效应、效应的 BC 区间与 bootstrap 标准误
    Public Shared Sub BootPass(ByVal m As ModelData, ByVal n As Integer, ByVal seed As Integer, Optional ByVal setup As EngineSetup = Nothing)
        If n < 5000 OrElse seed < 1 OrElse seed > 29999 Then Throw New ArgumentException("Bootstrap次数须至少5000，AMOS种子须为1—29999。")
        If m.HasMissing Then Throw New InvalidOperationException("当前数据有缺失值，AMOS Bootstrap需要完整数据。")
        If m.NGroups <> 1 Then Throw New InvalidOperationException("多群组请使用SEM Multigroup的分组Bootstrap。")
        m.BootN = 0 : m.BootPlanned = n : m.BootSeed = seed
        Dim sem As New AmosEngine()
        Try
            sem.Standardized()
            sem.Bootstrap(n)
            sem.Seed(seed)
            sem.ConfidenceBC(95)
            sem.NeedBootSampleEstimates(DirectEffects)
            For Each id As AmosEngine.TMatrixID In New AmosEngine.TMatrixID() {DirectEffects, IndirectEffects, TotalEffects}
                sem.NeedEstimates(id)
                sem.NeedBCLowerBounds(id)
                sem.NeedBCUpperBounds(id)
                sem.NeedStandardErrors(id)
            Next
            If setup Is Nothing Then pd.SpecifyModel(sem) Else setup(sem)
            If sem.FitModel() <> 0 Then
                m.Notes.Add("bootstrap 这一遍模型没有拟合成功，区间不可用。")
                Return
            End If
            m.BootDirect = New List(Of Double(,))()
            For b As Integer = 1 To n
                Dim x(,) As Double = Nothing
                sem.GetBootSampleEstimates(DirectEffects, x, b)
                m.BootDirect.Add(x)
            Next
            m.BootN = m.BootDirect.Count
            sem.GetBCLowerBounds(DirectEffects, m.BcLoDir)
            sem.GetBCUpperBounds(DirectEffects, m.BcHiDir)
            sem.GetBCLowerBounds(IndirectEffects, m.BcLo)
            sem.GetBCUpperBounds(IndirectEffects, m.BcHi)
            sem.GetBCLowerBounds(TotalEffects, m.BcLoTot)
            sem.GetBCUpperBounds(TotalEffects, m.BcHiTot)
            sem.GetStandardErrors(DirectEffects, m.SeDir)
            sem.GetStandardErrors(IndirectEffects, m.SeInd)
            sem.GetStandardErrors(TotalEffects, m.SeTot)
        Catch ex As Exception
            m.BootN = 0
            m.Notes.Add("bootstrap 失败：" & ex.Message)
        Finally
            sem.Dispose()
        End Try
    End Sub

    ' 用 Pd 读路径图里的误差相关（CR 公式假定误差互相独立，有误差相关时要提示）
    Private Shared Sub ReadDiagram(ByVal m As ModelData)
        Try
            Dim e As PDElement
            For Each e In pd.PDElements
                If e.IsObservedVariable() OrElse e.IsLatentVariable() Then m.DiagramOrder.Add(e.NameOrCaption)
                If e.IsCovariance() Then
                    If e.Variable1.IsUniqueVariable() AndAlso e.Variable2.IsUniqueVariable() Then
                        m.ErrorCovPairs.Add(e.Variable1.NameOrCaption & " ~ " & e.Variable2.NameOrCaption)
                    End If
                End If
            Next
        Catch ex As Exception
            m.Notes.Add("读取路径图失败：" & ex.Message)
        End Try
    End Sub

    Private Shared Sub Pass(ByVal m As ModelData, ByVal useSatInd As Boolean, ByVal sat As Double, ByVal ind As Double, Optional ByVal setup As EngineSetup = Nothing)
        Dim sem As New AmosEngine()
        Try
            sem.Standardized()
            sem.NeedEstimates(DirectEffects)
            sem.NeedEstimates(StandardizedDirectEffects)
            sem.NeedEstimates(TotalEffects)
            sem.NeedEstimates(IndirectEffects)
            sem.NeedEstimates(StandardizedTotalEffects)
            sem.NeedEstimates(StandardizedIndirectEffects)
            sem.NeedEstimates(AllImpliedCorrelations)
            sem.NeedEstimates(AllImpliedCovariances)
            sem.NeedEstimates(ImpliedCorrelations)
            sem.NeedEstimates(SampleCovariances)
            sem.NeedEstimates(SampleCorrelations)
            sem.NeedEstimates(SampleMeans)
            If useSatInd Then
                sem.SetSaturatedFit(True, sat)
                sem.SetIndependenceFit(True, ind)
            End If
            If setup Is Nothing Then pd.SpecifyModel(sem) Else setup(sem)
            Dim gv As String = ""
            Dim gval As Object = Nothing
            sem.GetDataFile(1, m.Fmt, m.FileName, m.TableName, gv, gval)
            If gv IsNot Nothing Then m.GroupVar = gv
            m.GroupVal = gval
            m.FitStatus = sem.FitModel()
            If m.FitStatus <> 0 Then
                If m.FitStatus = -6 Then
                    m.FitMessage = "AMOS 判定模型很可能不可识别（引擎状态 -6）。可先运行「" & PluginInfo.MenuPrefix & "Model Check」查找原因。"
                Else
                    m.FitMessage = "引擎返回状态 " & m.FitStatus.ToString() & "，模型没有拟合成功。可先运行「" & PluginInfo.MenuPrefix & "Model Check」查找原因。"
                End If
                Return
            End If
            m.HasMissing = sem.AnyMissingValues
            m.NCases = sem.DataFileNCases(1)
            m.Npar = sem.Npar
            ' 有缺失值（FIML）时，没回填饱和模型与独立模型的拟合之前，χ²、p、RMSEA 没有定义，读取会抛错；第一遍只当探路
            Try
                m.Cmin = sem.Cmin
                m.Df = sem.Df
                m.PVal = sem.P
                m.Rmsea = sem.Rmsea
                m.RmseaLo = sem.RmseaLo
                m.RmseaHi = sem.RmseaHi
            Catch
                m.Cmin = Double.NaN
                m.Rmsea = Double.NaN
                m.RmseaLo = Double.NaN
                m.RmseaHi = Double.NaN
                m.PVal = Double.NaN
            End Try
            m.Admissible = sem.Admissible
            m.Stable = sem.Stable
            sem.GetEstimates(DirectEffects, m.Dir)
            ' S.E.：不用 NeedStandardErrors / GetStandardErrors（那是 bootstrap 标准误，有缺失值时直接报错），
            ' 而用参数协方差矩阵的对角线开方，数与 AMOS 输出表里的 S.E. 逐位一致（完整数据与 FIML 都验证过）
            m.ParamEst.Clear()
            m.ParamSe.Clear()
            m.ParamCov.Clear()
            m.RegressionLabels.Clear()
            Dim ids As New Dictionary(Of String, Integer)()
            For i As Integer = 1 To sem.NumberOfParameters
                Dim g As Integer, t As Integer, lv As Integer, rv As Integer
                sem.ParameterInfo(i, g, t, lv, rv)
                If t = 1 Then
                    Dim label As String=sem.ParameterName(i)
                    If label IsNot Nothing AndAlso label<>"" AndAlso Not m.RegressionLabels.Contains(label) Then m.RegressionLabels.Add(label)
                    Dim key As String = sem.VariableName(lv) & "|" & sem.VariableName(rv)
                    m.ParamEst(key) = sem.ParameterValue(i)
                    m.ParamSe(key) = Math.Sqrt(sem.ParameterCovariance(i))
                    ids(key) = i
                End If
            Next
            For Each a As KeyValuePair(Of String,Integer) In ids
                For Each b As KeyValuePair(Of String,Integer) In ids
                    m.ParamCov(a.Key & vbTab & b.Key) = sem.ParameterCovariance(a.Value,b.Value)
                Next
            Next
            sem.GetEstimates(StandardizedDirectEffects, m.StdDir)
            sem.GetEstimates(TotalEffects, m.Tot)
            sem.GetEstimates(IndirectEffects, m.Ind)
            sem.GetEstimates(StandardizedTotalEffects, m.StdTot)
            sem.GetEstimates(StandardizedIndirectEffects, m.StdInd)
            sem.RowNames(DirectEffects, m.RowNames)
            sem.ColumnNames(DirectEffects, m.ColNames)
            sem.GetEstimates(AllImpliedCorrelations, m.AllCor)
            sem.RowNames(AllImpliedCorrelations, m.AllNames)
            sem.GetEstimates(AllImpliedCovariances, m.AllCov)
            sem.RowNames(AllImpliedCovariances, m.CovAllNames)
            sem.GetEstimates(ImpliedCorrelations, m.ImpCor)
            sem.RowNames(ImpliedCorrelations, m.ImpNames)
            m.Obs = m.ImpNames
            If Not m.HasMissing Then
                sem.GetEstimates(SampleCovariances, m.Cov)
                sem.GetEstimates(SampleCorrelations, m.Cor)
                sem.RowNames(SampleCorrelations, m.CovNames)
                ' 不带均值结构时AMOS不提供SampleMeans；描述统计另拟合饱和均值模型。
                Try
                    sem.GetEstimates(SampleMeans, m.SampleMean)
                    sem.RowNames(SampleMeans, m.MeanNames)
                Catch
                    m.SampleMean=Nothing : m.MeanNames=Nothing
                End Try
                m.CovSource = "样本"
            End If
        Catch ex As Exception
            m.FitStatus = -2
            m.FitMessage = ex.Message
        Finally
            sem.Dispose()
        End Try
    End Sub

    ' 完整数据：独立（基线）模型，所有观测变量只有方差
    Private Shared Sub FitIndependence(ByVal m As ModelData)
        Dim s2 As New AmosEngine()
        Try
            s2.GenerateDefaultCovariances(False)
            s2.BeginGroupEx(m.Fmt, m.FileName, m.TableName)
            For Each v As String In m.Obs
                s2.Var(v)
            Next
            If s2.FitModel() = 0 Then
                m.BaseCmin = s2.Cmin
                m.BaseDf = s2.Df
                m.BaseOK = True
            End If
        Catch ex As Exception
            m.Notes.Add("独立模型拟合失败，CFI、TLI 不可用：" & ex.Message)
        Finally
            s2.Dispose()
        End Try
    End Sub

    ' 有缺失值：饱和模型（同时给出 ML 估计的协方差与相关，供 α、HTMT 用）与独立模型
    Private Shared Sub FitSatInd(ByVal m As ModelData)
        Dim s1 As New AmosEngine()
        Try
            s1.ModelMeansAndIntercepts()
            s1.NeedEstimates(ImpliedCovariances)
            s1.NeedEstimates(ImpliedCorrelations)
            s1.GenerateDefaultCovariances(True)
            s1.BeginGroupEx(m.Fmt, m.FileName, m.TableName)
            For Each v As String In m.Obs
                s1.Mean(v)
            Next
            If s1.FitModel() = 0 Then
                m.SatCmin = s1.Cmin
                s1.GetEstimates(ImpliedCovariances, m.Cov)
                s1.GetEstimates(ImpliedCorrelations, m.Cor)
                s1.RowNames(ImpliedCorrelations, m.CovNames)
                m.CovSource = "饱和模型的 ML（FIML）估计"
                m.SatOK = True
            End If
        Catch ex As Exception
            m.Notes.Add("饱和模型拟合失败：" & ex.Message)
        Finally
            s1.Dispose()
        End Try
        If Not m.SatOK Then Return
        Dim s2 As New AmosEngine()
        Try
            s2.ModelMeansAndIntercepts()
            s2.GenerateDefaultCovariances(False)
            s2.BeginGroupEx(m.Fmt, m.FileName, m.TableName)
            For Each v As String In m.Obs
                s2.Mean(v)
            Next
            If s2.FitModel() = 0 Then
                m.IndCmin = s2.Cmin
            Else
                m.SatOK = False
            End If
        Catch ex As Exception
            m.SatOK = False
            m.Notes.Add("独立模型拟合失败：" & ex.Message)
        Finally
            s2.Dispose()
        End Try
    End Sub
End Class

' ---------------------------------------------------------------- 模型类型：每个插件只接受自己适用的类型
' 判定只看直接效应矩阵（行＝因变量，列＝自变量，不含误差与扰动项）：
'   观测变量 ← 潜变量              测量载荷
'   潜变量 ← 没有观测指标的潜变量   高阶因子的载荷（仍属测量模型）
'   其余（潜变量 ← 潜变量、潜变量 ← 观测变量、观测变量 ← 观测变量）  结构路径
' 有结构路径：有因子的是 SEM，没有因子的是路径分析；没有结构路径而有因子的是 CFA。
Friend Class ModelKind
    Public Const CFA As String = "CFA"
    Public Const SEM As String = "SEM"
    Public Const PATH As String = "PATH"
    Public Const OTHER As String = "OTHER"

    Public Kind As String = OTHER
    Public NFactors As Integer = 0        ' 有观测指标的潜变量个数
    Public NStruct As Integer = 0         ' 结构路径条数
    Public NHigher As Integer = 0         ' 高阶因子的载荷条数

    Public Shared Function Detect(ByVal m As ModelData) As ModelKind
        Dim k As New ModelKind()
        Dim nc As Integer = m.ColNames.Length
        Dim colObs(nc - 1) As Boolean
        Dim hasInd(nc - 1) As Boolean
        For j As Integer = 0 To nc - 1
            colObs(j) = Calc.IndexOf(m.Obs, m.ColNames(j)) >= 0
            If colObs(j) Then Continue For
            For i As Integer = 0 To m.RowNames.Length - 1
                If Math.Abs(m.Dir(i, j)) > 0.000000000001 AndAlso Calc.IndexOf(m.Obs, m.RowNames(i)) >= 0 Then
                    hasInd(j) = True
                    Exit For
                End If
            Next
            If hasInd(j) Then k.NFactors += 1
        Next
        For j As Integer = 0 To nc - 1
            For i As Integer = 0 To m.RowNames.Length - 1
                If Math.Abs(m.Dir(i, j)) <= 0.000000000001 Then Continue For
                Dim rowObs As Boolean = Calc.IndexOf(m.Obs, m.RowNames(i)) >= 0
                If rowObs AndAlso Not colObs(j) Then Continue For
                If Not rowObs AndAlso Not colObs(j) AndAlso Not hasInd(j) Then
                    k.NHigher += 1
                Else
                    k.NStruct += 1
                End If
            Next
        Next
        If k.NStruct > 0 Then
            If k.NFactors > 0 Then k.Kind = SEM Else k.Kind = PATH
        ElseIf k.NFactors > 0 Then
            k.Kind = CFA
        End If
        Return k
    End Function

    ' 给学员看的说法
    Public Function Label() As String
        Select Case Kind
            Case CFA
                If NHigher > 0 Then Return "测量模型（CFA，含高阶因子）"
                Return "测量模型（CFA）"
            Case SEM
                Return "结构方程模型（SEM，含 " & NStruct.ToString() & " 条结构路径）"
            Case PATH
                Return "路径分析模型（没有潜变量，" & NStruct.ToString() & " 条路径）"
        End Select
        Return "无法归类的模型（没有找到带观测指标的潜变量，也没有路径）"
    End Function
End Class

' ---------------------------------------------------------------- 结果表
Friend Class RTable
    Public Title As String = ""
    Public Cols As New List(Of String)()
    Public Rows As New List(Of String())()
    Public Notes As New List(Of String)()
    Public Id As String = ""
    Public Section As String = ""                 ' 非空时，在本表之前输出一个小节标题
    Public Lead As New List(Of String)()          ' 小节标题之后、表之前的说明段落
    Public Paras As New List(Of String)()         ' 表注之后的正文段落（结论等）
    Public WrapLast As Boolean = False            ' 最后一列是文字说明：左对齐并允许换行
    Public TextCols As Integer = 1                ' 开头有几列是文字（左对齐）；其余列是数字（居中）
    ' ---- 论文用表（APA 第 7 版三线表）
    Public Paper As Boolean = True                ' False：只供检查的表（设定清单、搜索日志、检查结果），不译英文、不改数字写法，复制时整表照搬
    Public NoCopy As New List(Of String)()        ' 复制进论文时去掉的列（按列名）：判断、含义、提示一类，页面上以浅底显示
    Public PaperNotes As New List(Of String)()    ' 论文表注（中英文，Tx.T 登记），随表复制；Notes 是给学员的说明，只在页面显示
    Public Prose As New List(Of String)()         ' 结果行文（中英文，只写数不写评价），可单独复制
    ' 筛选元数据与原始数字分开保存；其他插件不设置这些字段。
    Public RowMeta As New List(Of String())()   ' 组合键、路径键、行类型、起点、终点
    Public ProseParts As New List(Of String())() ' 组合键、路径键、双语行文键
    Public GroupFirst As Boolean = False          ' 第一列连续相同的行只在首行显示（载荷表的构念名）
    Public BoldDiag As Boolean = False            ' 对角线加粗（Fornell–Larcker 矩阵的 AVE 平方根）
    Public NameCols As Boolean = False            ' 第 2 列起的列名是学员的变量名（矩阵表），不查对照
    Public Extra As New List(Of String())()       ' 不进表、但核对脚本要读的量（键、值），写在 table 的 data-extra 里
    Public Widths() As Double
    Public Merges As New List(Of Integer())()    ' 列、起始行、结束行；行从0起
    Public BoldCells As New List(Of Integer())()
    Public HeaderGroups As New List(Of Integer())() ' 首行跨列组标题的起止列
    Public Header2() As String
    Public Interp As New List(Of String())()       ' 自动统计结果解读：{level("ok"|"warn"|"info"), zhText, enText}

    ' 加一条统计结果解读
    Public Sub AddInterp(ByVal level As String, ByVal zhText As String, ByVal enText As String)
        Dim lv As String = If(level, "info").Trim().ToLowerInvariant()
        If lv <> "ok" AndAlso lv <> "warn" AndAlso lv <> "info" Then lv = "info"
        Interp.Add(New String() {lv, If(zhText, ""), If(enText, "")})
    End Sub

    ' 写入或覆盖 Extra 键值
    Public Sub SetExtra(ByVal key As String, ByVal value As String)
        If key Is Nothing Then Return
        Dim val As String = If(value, "")
        For Each kv As String() In Extra
            If kv IsNot Nothing AndAlso kv.Length >= 2 AndAlso String.Equals(kv(0), key, StringComparison.Ordinal) Then
                kv(1) = val
                Return
            End If
        Next
        Extra.Add(New String() {key, val})
    End Sub

    ' 读取 Extra 键值，找不到返回空串
    Public Function GetExtra(ByVal key As String) As String
        If key Is Nothing Then Return ""
        For Each kv As String() In Extra
            If kv IsNot Nothing AndAlso kv.Length >= 2 AndAlso String.Equals(kv(0), key, StringComparison.Ordinal) Then
                Return If(kv(1), "")
            End If
        Next
        Return ""
    End Function

    ' 加一条论文表注
    ' 中文可以留空：缩写的全称只有英文稿要写
    Public Sub PN(ByVal zhText As String, ByVal enText As String)
        If zhText = "" Then
            Dim k As String = ChrW(1) & enText
            Tx.Reg(k, "", enText)
            PaperNotes.Add(k)
        Else
            PaperNotes.Add(Tx.T(zhText, enText))
        End If
    End Sub

    ' 加一句结果行文
    Public Sub PR(ByVal zhText As String, ByVal enText As String)
        Prose.Add(Tx.T(zhText, enText))
    End Sub
End Class

Friend Class Factor
    Public Name As String = ""
    Public Items As New List(Of String)()
    Public Std As New List(Of Double)()
    Public Est As New List(Of Double)()
    Public Se As New List(Of Double)()
    Public CR As Double, AVE As Double, MSV As Double, ASV As Double
    Public AlphaRaw As Double, AlphaStd As Double
End Class

' ---------------------------------------------------------------- 计算与排版
Friend Class Calc
    Public Shared Function IndexOf(ByVal names() As String, ByVal s As String) As Integer
        If names Is Nothing Then Return -1
        For i As Integer = 0 To names.Length - 1
            If String.Equals(names(i), s, StringComparison.Ordinal) Then Return i
        Next
        Return -1
    End Function

    Public Shared Function N3(ByVal x As Double) As String
        If Double.IsNaN(x) OrElse Double.IsInfinity(x) Then Return "—"
        Return x.ToString("0.000", CultureInfo.InvariantCulture)
    End Function

    Public Shared Function N2(ByVal x As Double) As String
        If Double.IsNaN(x) OrElse Double.IsInfinity(x) Then Return "—"
        Return x.ToString("0.00", CultureInfo.InvariantCulture)
    End Function

    Public Shared Function PText(ByVal p As Double) As String
        If Double.IsNaN(p) Then Return "—"
        If p < 0.001 Then Return "< 0.001"
        Return p.ToString("0.000", CultureInfo.InvariantCulture)
    End Function

    ' 标准正态双侧 p 值：erfc 的 Numerical Recipes 近似（相对误差 < 1.2e-7）
    Public Shared Function PFromZ(ByVal z As Double) As Double
        Dim x As Double = Math.Abs(z) / Math.Sqrt(2.0)
        Dim t As Double = 1.0 / (1.0 + 0.5 * x)
        Dim ans As Double = t * Math.Exp(-x * x - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277)))))))))
        Return ans
    End Function

    ' ---- 找因子：DirectEffects 的列里，非观测变量且至少连两个观测变量的，就是测量模型里的因子
    Public Shared Function FindFactors(ByVal m As ModelData, ByVal notes As List(Of String)) As List(Of Factor)
        Dim res As New List(Of Factor)()
        For j As Integer = 0 To m.ColNames.Length - 1
            If IndexOf(m.Obs, m.ColNames(j)) >= 0 Then Continue For
            Dim f As New Factor()
            f.Name = m.ColNames(j)
            Dim nLatentDep As Integer = 0
            For i As Integer = 0 To m.RowNames.Length - 1
                If Math.Abs(m.StdDir(i, j)) > 0.000000000001 Then
                    If IndexOf(m.Obs, m.RowNames(i)) >= 0 Then
                        f.Items.Add(m.RowNames(i))
                        f.Std.Add(m.StdDir(i, j))
                        f.Est.Add(m.Dir(i, j))
                        Dim key As String = m.RowNames(i) & "|" & m.ColNames(j)
                        If m.ParamSe.ContainsKey(key) Then f.Se.Add(m.ParamSe(key)) Else f.Se.Add(0)
                    Else
                        nLatentDep += 1
                    End If
                End If
            Next
            If f.Items.Count >= 2 Then
                res.Add(f)
            ElseIf f.Items.Count = 1 Then
                notes.Add("构念 " & f.Name & " 只有 1 个指标（单指标构念），没有 CR、AVE、α，已从信效度表略去。")
            ElseIf nLatentDep >= 2 Then
                notes.Add("构念 " & f.Name & " 的指标是其他潜变量（二阶因子）：前面各表只列一阶因子的信效度；CFA Report 另有「高阶因子」一节列出它的载荷、CR 与 AVE。")
            End If
        Next
        ' 按路径图里的次序排列因子与题项（引擎的次序是反的）
        res.Sort(Function(x As Factor, y As Factor) OrderOf(m, x.Name).CompareTo(OrderOf(m, y.Name)))
        For Each f As Factor In res
            Dim idx As New List(Of Integer)()
            For q As Integer = 0 To f.Items.Count - 1
                idx.Add(q)
            Next
            Dim fc As Factor = f
            idx.Sort(Function(x As Integer, y As Integer) OrderOf(m, fc.Items(x)).CompareTo(OrderOf(m, fc.Items(y))))
            Dim it As New List(Of String)()
            Dim sd As New List(Of Double)()
            Dim es As New List(Of Double)()
            Dim se As New List(Of Double)()
            For Each q As Integer In idx
                it.Add(f.Items(q))
                sd.Add(f.Std(q))
                es.Add(f.Est(q))
                se.Add(f.Se(q))
            Next
            f.Items = it
            f.Std = sd
            f.Est = es
            f.Se = se
        Next
        ' 交叉载荷提示
        For a As Integer = 0 To res.Count - 1
            For Each it As String In res(a).Items
                For b As Integer = a + 1 To res.Count - 1
                    If res(b).Items.Contains(it) Then
                        notes.Add("题项 " & it & " 同时载入 " & res(a).Name & " 与 " & res(b).Name & "（交叉载荷）：CR、AVE 的公式按「每个题项只属于一个构念」推导，请谨慎解读。")
                    End If
                Next
            Next
        Next
        Return res
    End Function

    Private Shared Function OrderOf(ByVal m As ModelData, ByVal name As String) As Integer
        Dim i As Integer = m.DiagramOrder.IndexOf(name)
        If i < 0 Then Return 100000
        Return i
    End Function

    Private Shared Function Corr(ByVal m As ModelData, ByVal a As String, ByVal b As String) As Double
        Dim i As Integer = IndexOf(m.AllNames, a)
        Dim j As Integer = IndexOf(m.AllNames, b)
        If i < 0 OrElse j < 0 Then Return Double.NaN
        Return m.AllCor(i, j)
    End Function

    Private Shared Function ItemCor(ByVal m As ModelData, ByVal a As String, ByVal b As String) As Double
        Dim i As Integer = IndexOf(m.CovNames, a)
        Dim j As Integer = IndexOf(m.CovNames, b)
        If i < 0 OrElse j < 0 Then Return Double.NaN
        Return m.Cor(i, j)
    End Function

    Private Shared Function ItemCov(ByVal m As ModelData, ByVal a As String, ByVal b As String) As Double
        Dim i As Integer = IndexOf(m.CovNames, a)
        Dim j As Integer = IndexOf(m.CovNames, b)
        If i < 0 OrElse j < 0 Then Return Double.NaN
        Return m.Cov(i, j)
    End Function

    ' ---- 每个因子的 CR、AVE、MSV、ASV、α
    Public Shared Sub Reliability(ByVal m As ModelData, ByVal facs As List(Of Factor))
        For Each f As Factor In facs
            Dim k As Integer = f.Items.Count
            Dim s1 As Double = 0
            Dim s2 As Double = 0
            Dim e1 As Double = 0
            For q As Integer = 0 To k - 1
                Dim l As Double = f.Std(q)
                s1 += l
                s2 += l * l
                e1 += 1 - l * l
            Next
            f.CR = s1 * s1 / (s1 * s1 + e1)
            f.AVE = s2 / k
            Dim msv As Double = 0
            Dim asv As Double = 0
            For Each g As Factor In facs
                If Not Object.ReferenceEquals(f, g) Then
                    Dim r As Double = Corr(m, f.Name, g.Name)
                    asv += r * r
                    If r * r > msv Then msv = r * r
                End If
            Next
            f.MSV = msv
            If facs.Count > 1 Then f.ASV = asv / (facs.Count - 1) Else f.ASV = Double.NaN
            ' Cronbach α：原始（协方差）与标准化（相关）
            f.AlphaRaw = Double.NaN
            f.AlphaStd = Double.NaN
            If m.Cov IsNot Nothing AndAlso k >= 2 Then
                Dim tr As Double = 0
                Dim tot As Double = 0
                Dim sr As Double = 0
                Dim nr As Integer = 0
                For a As Integer = 0 To k - 1
                    For b As Integer = 0 To k - 1
                        tot += ItemCov(m, f.Items(a), f.Items(b))
                        If a = b Then
                            tr += ItemCov(m, f.Items(a), f.Items(b))
                        ElseIf a < b Then
                            sr += ItemCor(m, f.Items(a), f.Items(b))
                            nr += 1
                        End If
                    Next
                Next
                f.AlphaRaw = k / (k - 1.0) * (1 - tr / tot)
                Dim rbar As Double = sr / nr
                f.AlphaStd = k * rbar / (1 + (k - 1) * rbar)
            End If
        Next
    End Sub

    ' ---- HTMT（绝对相关）
    Public Shared Function Htmt(ByVal m As ModelData, ByVal a As Factor, ByVal b As Factor) As Double
        If m.Cor Is Nothing Then Return Double.NaN
        Dim het As Double = 0
        For Each x As String In a.Items
            For Each y As String In b.Items
                het += Math.Abs(ItemCor(m, x, y))
            Next
        Next
        het = het / (a.Items.Count * b.Items.Count)
        Dim ma As Double = Mono(m, a)
        Dim mb As Double = Mono(m, b)
        If Double.IsNaN(ma) OrElse Double.IsNaN(mb) OrElse ma <= 0 OrElse mb <= 0 Then Return Double.NaN
        Return het / Math.Sqrt(ma * mb)
    End Function

    Private Shared Function Mono(ByVal m As ModelData, ByVal f As Factor) As Double
        If f.Items.Count < 2 Then Return Double.NaN
        Dim s As Double = 0
        Dim n As Integer = 0
        For g As Integer = 0 To f.Items.Count - 2
            For h As Integer = g + 1 To f.Items.Count - 1
                s += Math.Abs(ItemCor(m, f.Items(g), f.Items(h)))
                n += 1
            Next
        Next
        Return s / n
    End Function

    ' ---- SRMR：公式取自 AMOS 自带的 Standardized RMR 插件源码
    '      样本与隐含相关矩阵下三角（不含对角线）之差的平方和 ÷ [p(p+1)/2]，再开方。有缺失值时官方插件也不提供。
    Public Shared Function Srmr(ByVal m As ModelData) As Double
        If m.HasMissing OrElse m.Cor Is Nothing Then Return Double.NaN
        Dim p As Integer = m.CovNames.Length
        Dim acc As Double = 0
        For i As Integer = 1 To p - 1
            For j As Integer = 0 To i - 1
                Dim ii As Integer = IndexOf(m.ImpNames, m.CovNames(i))
                Dim jj As Integer = IndexOf(m.ImpNames, m.CovNames(j))
                If ii < 0 OrElse jj < 0 Then Return Double.NaN
                acc += (m.Cor(i, j) - m.ImpCor(ii, jj)) ^ 2
            Next
        Next
        Return Math.Sqrt(acc / (p * (p + 1) / 2.0))
    End Function

    ' ---------------------------------------------------------------- 各张表
    ' 拟合量的（名称，数值）清单；FitTable 由它排成一行，核对外壳也读它
    Public Shared Function FitPairs(ByVal m As ModelData) As List(Of String())
        Dim t As New RTable()
        t.Rows.Add(New String() {"χ²", N3(m.Cmin)})
        t.Rows.Add(New String() {"df", m.Df.ToString()})
        t.Rows.Add(New String() {"p", PText(m.PVal)})
        t.Rows.Add(New String() {"χ²/df", N3(m.Cmin / m.Df)})
        Dim cfi As Double = Double.NaN
        Dim tli As Double = Double.NaN
        If m.BaseOK AndAlso m.BaseDf > 0 Then
            Dim d1 As Double = Math.Max(m.Cmin - m.Df, 0)
            Dim d2 As Double = Math.Max(Math.Max(m.BaseCmin - m.BaseDf, m.Cmin - m.Df), 0)
            If d2 > 0 Then cfi = 1 - d1 / d2 Else cfi = 1
            tli = ((m.BaseCmin / m.BaseDf) - (m.Cmin / m.Df)) / ((m.BaseCmin / m.BaseDf) - 1)
        End If
        If m.BaseOK Then t.Rows.Add(New String() {"独立模型 χ²（df）", N3(m.BaseCmin) & "（" & m.BaseDf.ToString() & "）"})
        t.Rows.Add(New String() {"CFI", N3(cfi)})
        t.Rows.Add(New String() {"TLI", N3(tli)})
        t.Rows.Add(New String() {"RMSEA [90% CI]", N3(m.Rmsea) & " [" & N3(m.RmseaLo) & ", " & N3(m.RmseaHi) & "]"})
        Dim sr As Double = Srmr(m)
        If Double.IsNaN(sr) Then
            t.Rows.Add(New String() {"SRMR", "—"})
        Else
            t.Rows.Add(New String() {"SRMR", N3(sr)})
        End If
        t.Rows.Add(New String() {"AIC", N3(m.Cmin + 2 * m.Npar)})
        If m.HasMissing Then
            t.Rows.Add(New String() {"BIC", "—"})
        Else
            t.Rows.Add(New String() {"BIC", N3(m.Cmin + m.Npar * Math.Log(m.NCases))})
        End If
        t.Rows.Add(New String() {"N", m.NCases.ToString()})
        t.Rows.Add(New String() {"估计参数个数", m.Npar.ToString()})
        Return t.Rows
    End Function

    Private Shared Function PairOf(ByVal prs As List(Of String()), ByVal key As String) As String
        For Each r As String() In prs
            If r(0) = key Then Return r(1)
        Next
        Return "—"
    End Function

    ' 模型拟合：论文里的写法是一个模型一行。zhLabel、enLabel 是这一行的模型名
    Public Shared Function FitTable(ByVal m As ModelData, Optional ByVal zhLabel As String = "当前模型", Optional ByVal enLabel As String = "Hypothesized model") As RTable
        Dim prs As List(Of String()) = FitPairs(m)
        Dim t As New RTable()
        t.Id = "fit"
        t.Title = Tx.T("模型拟合指标", "Model Fit Indices")
        Dim keys() As String = {"χ²", "df", "p", "χ²/df", "CFI", "TLI", "RMSEA [90% CI]", "SRMR", "AIC", "BIC"}
        t.Cols.Add("模型")
        t.Cols.AddRange(keys)
        ' AIC、BIC 只在比较模型时用得上，单个模型的拟合表不带进论文（页面上浅底照显示）
        t.NoCopy.Add("AIC")
        t.NoCopy.Add("BIC")
        Dim row As New List(Of String)()
        row.Add(Tx.Row(zhLabel, enLabel))
        For Each k As String In keys
            row.Add(PairOf(prs, k))
        Next
        t.Rows.Add(row.ToArray())
        t.Extra.Add(New String() {"N", m.NCases.ToString()})
        t.Extra.Add(New String() {"估计参数个数", m.Npar.ToString()})
        If m.BaseOK Then t.Extra.Add(New String() {"独立模型 χ²（df）", PairOf(prs, "独立模型 χ²（df）")})
        Dim abbr As String = "CFI = comparative fit index; TLI = Tucker–Lewis index; RMSEA = root-mean-square error of approximation; CI = confidence interval; SRMR = standardized root-mean-square residual."
        If m.HasMissing Then
            t.PN("*N* = " & m.NCases.ToString() & "。数据有缺失值，采用全信息最大似然（FIML）估计，该估计下未计算 SRMR。RMSEA 后方括号内为 90% 置信区间。", "*N* = " & m.NCases.ToString() & ". Missing data were handled with full-information maximum likelihood (FIML) estimation; SRMR was not computed under FIML. " & abbr)
            t.Notes.Add("估计参数 " & m.Npar.ToString() & " 个（含题项截距）。χ²、CFI、TLI 由饱和模型与独立模型的拟合回填；FIML 下 AMOS 不给 BIC，SRMR 官方插件同样不提供。")
        Else
            t.PN("*N* = " & m.NCases.ToString() & "。采用最大似然估计。RMSEA 后方括号内为 90% 置信区间。", "*N* = " & m.NCases.ToString() & ". Maximum likelihood estimation. " & abbr)
            t.Notes.Add("估计参数 q = " & m.Npar.ToString() & " 个" & If(m.BaseOK, "；独立模型 χ²(" & m.BaseDf.ToString() & ") = " & N3(m.BaseCmin) & "，CFI、TLI 由它算出", "") & "。AIC = χ² + 2q；BIC = χ² + q·ln(N)（与 AMOS 输出同一定义）；SRMR 公式取自 AMOS 自带的 Standardized RMR 插件。")
        End If
        ' 行文：只列数
        Dim parts As New List(Of String)()
        parts.Add(Ap.ChiN(m.Df, m.NCases, m.Cmin))
        parts.Add(Ap.PVal(m.PVal))
        parts.Add("χ²/*df* = " & PairOf(prs, "χ²/df"))
        parts.Add("CFI = " & PairOf(prs, "CFI"))
        parts.Add("TLI = " & PairOf(prs, "TLI"))
        parts.Add("RMSEA = " & N3(m.Rmsea))
        parts.Add("90% CI [" & N3(m.RmseaLo) & ", " & N3(m.RmseaHi) & "]")
        If PairOf(prs, "SRMR") <> "—" Then parts.Add("SRMR = " & PairOf(prs, "SRMR"))
        t.PR(zhLabel & "的拟合指标：" & String.Join("，", parts.ToArray()) & "。", "Fit indices for the " & enLabel.ToLowerInvariant() & ": " & String.Join(", ", parts.ToArray()) & ".")
        Return t
    End Function

    Public Shared Function LoadingTable(ByVal facs As List(Of Factor)) As RTable
        Dim t As New RTable()
        t.Id = "loadings"
        t.TextCols = 2
        t.GroupFirst = True
        t.Title = Tx.T("测量模型的因子载荷", "Factor Loadings for the Measurement Model")
        t.Cols.AddRange(New String() {"构念", "题项", "非标准化估计 b", "S.E.", "C.R.", "p", "标准化载荷 β", "SMC (R²)"})
        For Each f As Factor In facs
            For q As Integer = 0 To f.Items.Count - 1
                Dim se As Double = f.Se(q)
                Dim b As Double = f.Est(q)
                If se <= 0.0000000001 Then
                    t.Rows.Add(New String() {f.Name, f.Items(q), N3(b), "—", "—", "—", N3(f.Std(q)), N3(f.Std(q) * f.Std(q))})
                Else
                    Dim z As Double = b / se
                    t.Rows.Add(New String() {f.Name, f.Items(q), N3(b), N3(se), N2(z), PText(PFromZ(z)), N3(f.Std(q)), N3(f.Std(q) * f.Std(q))})
                End If
            Next
        Next
        t.PN("*b* 为非标准化载荷，*SE* 为其标准误，C.R. 为临界比（*b*／*SE*），*R*² 为题项方差中由构念解释的比例。标短横线的题项为参照指标，其载荷固定为 1。", "*b* = unstandardized loading; C.R. = critical ratio (*b*/*SE*); *R*² = proportion of item variance explained by the construct. Dashes indicate reference indicators whose loadings were fixed to 1.")
        t.Notes.Add("p 为 C.R. 的双侧正态检验，与 AMOS 输出表一致。R² 即 AMOS 的 SMC，等于标准化载荷的平方。")
        ' 行文：载荷范围与自由载荷的 p
        Dim lams As New List(Of Double)()
        Dim nItems As Integer = 0
        Dim maxP As Double = Double.NaN
        For Each f As Factor In facs
            For q As Integer = 0 To f.Items.Count - 1
                lams.Add(f.Std(q))
                nItems += 1
                If f.Se(q) > 0.0000000001 Then
                    Dim pq As Double = PFromZ(f.Est(q) / f.Se(q))
                    If Double.IsNaN(maxP) OrElse pq > maxP Then maxP = pq
                End If
            Next
        Next
        Dim lo As Double, hi As Double
        Ap.Range(lams, lo, hi)
        If nItems > 0 Then
            Dim pz As String = ""
            Dim pe As String = ""
            If Not Double.IsNaN(maxP) Then
                If maxP < 0.001 Then
                    pz = "（自由估计的载荷 *p* 均 < 0.001）"
                    pe = " (all freely estimated loadings *p* < 0.001)"
                Else
                    pz = "（自由估计的载荷 *p* ≤ " & PText(maxP) & "）"
                    pe = " (freely estimated loadings *p* ≤ " & PText(maxP) & ")"
                End If
            End If
            t.PR(nItems.ToString() & " 个题项的标准化载荷介于 " & N3(lo) & " 与 " & N3(hi) & " 之间" & pz & "。", "Standardized loadings of the " & nItems.ToString() & " items ranged from " & N3(lo) & " to " & N3(hi) & pe & ".")
        End If
        Return t
    End Function

    Public Shared Function ReliabilityTable(ByVal m As ModelData, ByVal facs As List(Of Factor)) As RTable
        Dim t As New RTable()
        t.Id = "reliability"
        t.Title = Tx.T("信度与聚合效度", "Reliability and Convergent Validity")
        t.Cols.AddRange(New String() {"构念", "题项数", "载荷范围", "CR", "AVE", "MSV", "ASV", "Cronbach α", "α（标准化）"})
        For Each f As Factor In facs
            Dim mn As Double = Double.MaxValue
            Dim mx As Double = Double.MinValue
            For Each l As Double In f.Std
                If l < mn Then mn = l
                If l > mx Then mx = l
            Next
            t.Rows.Add(New String() {f.Name, f.Items.Count.ToString(), N3(mn) & " – " & N3(mx), N3(f.CR), N3(f.AVE), N3(f.MSV), N3(f.ASV), N3(f.AlphaRaw), N3(f.AlphaStd)})
        Next
        t.PN("CR = 组合信度；AVE = 平均方差抽取量；MSV = 最大共享方差；ASV = 平均共享方差。", "CR = composite reliability; AVE = average variance extracted; MSV = maximum shared variance; ASV = average shared variance.")
        t.Notes.Add("CR = (Σλ)² / [(Σλ)² + Σ(1 − λ²)]；AVE = Σλ² / k；λ 为标准化载荷，公式假定误差互相独立（Fornell & Larcker, 1981）。MSV、ASV 为该构念与其余构念相关系数平方的最大值、平均值。")
        If m.Cov Is Nothing Then
            t.Notes.Add("Cronbach α 需要题项协方差，本次未取到。")
        Else
            t.Notes.Add("Cronbach α 的协方差来源：" & m.CovSource & "。")
        End If
        RelProse(t, facs, m.Cov IsNot Nothing)
        Return t
    End Function

    ' 信度表的行文：α、CR、AVE 的范围（SEM Report 的测量部分摘要也用）
    Public Shared Sub RelProse(ByVal t As RTable, ByVal facs As List(Of Factor), ByVal hasAlpha As Boolean)
        If facs.Count = 0 Then Return
        Dim a As New List(Of Double)()
        Dim c As New List(Of Double)()
        Dim v As New List(Of Double)()
        For Each f As Factor In facs
            a.Add(f.AlphaRaw)
            c.Add(f.CR)
            v.Add(f.AVE)
        Next
        Dim lo As Double, hi As Double
        Dim zh As New List(Of String)()
        Dim en As New List(Of String)()
        If hasAlpha Then
            Ap.Range(a, lo, hi)
            zh.Add("Cronbach α 为 " & N3(lo) & "–" & N3(hi))
            en.Add("Cronbach’s α ranged from " & N3(lo) & " to " & N3(hi))
        End If
        Ap.Range(c, lo, hi)
        zh.Add("CR 为 " & N3(lo) & "–" & N3(hi))
        en.Add("CR " & If(en.Count = 0, "ranged ", "") & "from " & N3(lo) & " to " & N3(hi))
        Ap.Range(v, lo, hi)
        zh.Add("AVE 为 " & N3(lo) & "–" & N3(hi))
        en.Add("and AVE from " & N3(lo) & " to " & N3(hi))
        If facs.Count = 1 Then
            Dim f0 As Factor = facs(0)
            t.PR(f0.Name & "：" & If(hasAlpha, "Cronbach α = " & N3(f0.AlphaRaw) & "，", "") & "CR = " & N3(f0.CR) & "，AVE = " & N3(f0.AVE) & "。", f0.Name & ": " & If(hasAlpha, "Cronbach’s α = " & N3(f0.AlphaRaw) & ", ", "") & "CR = " & N3(f0.CR) & ", AVE = " & N3(f0.AVE) & ".")
        Else
            t.PR(facs.Count.ToString() & " 个构念的 " & String.Join("，", zh.ToArray()) & "。", "Across the " & facs.Count.ToString() & " constructs, " & String.Join(", ", en.ToArray()) & ".")
        End If
    End Sub

    Public Shared Function FlTable(ByVal m As ModelData, ByVal facs As List(Of Factor)) As RTable
        Dim t As New RTable()
        t.Id = "fl"
        t.BoldDiag = True
        t.NameCols = True
        t.Title = Tx.T("区分效度：Fornell–Larcker 准则", "Discriminant Validity: Fornell–Larcker Criterion")
        t.Cols.Add("")
        For Each f As Factor In facs
            t.Cols.Add(f.Name)
        Next
        For a As Integer = 0 To facs.Count - 1
            Dim row As New List(Of String)()
            row.Add(facs(a).Name)
            For b As Integer = 0 To facs.Count - 1
                If b > a Then
                    row.Add("")
                ElseIf b = a Then
                    row.Add(N3(Math.Sqrt(facs(a).AVE)))
                Else
                    row.Add(N3(Corr(m, facs(a).Name, facs(b).Name)))
                End If
            Next
            t.Rows.Add(row.ToArray())
        Next
        t.PN("对角线上加粗的数值为 AVE 的平方根，对角线以下为构念之间的相关系数。", "Values on the diagonal (in bold) are the square roots of the average variance extracted (AVE); values below the diagonal are correlations between constructs.")
        t.Notes.Add("相关系数是模型隐含的因子相关（潜变量层面）。每个构念的对角线值应大于所在行、列的相关系数（Fornell & Larcker, 1981）。")
        If facs.Count >= 2 Then
            Dim minRoot As Double = Double.MaxValue
            Dim maxR As Double = 0
            Dim pairZh As String = ""
            Dim pairEn As String = ""
            For a As Integer = 0 To facs.Count - 1
                minRoot = Math.Min(minRoot, Math.Sqrt(facs(a).AVE))
                For b As Integer = 0 To a - 1
                    Dim r As Double = Corr(m, facs(a).Name, facs(b).Name)
                    If Not Double.IsNaN(r) AndAlso Math.Abs(r) >= Math.Abs(maxR) Then
                        maxR = r
                        pairZh = facs(b).Name & " 与 " & facs(a).Name
                        pairEn = facs(b).Name & " and " & facs(a).Name
                    End If
                Next
            Next
            t.PR("AVE 平方根的最小值为 " & N3(minRoot) & "；构念间相关系数绝对值最大的是 " & pairZh & "（*r* = " & Ap.Minus(N3(maxR)) & "）。", "The smallest square root of the AVE was " & N3(minRoot) & "; the largest correlation between constructs in absolute value was between " & pairEn & " (*r* = " & Ap.Minus(N3(maxR)) & ").")
        End If
        Return t
    End Function

    Public Shared Function HtmtTable(ByVal m As ModelData, ByVal facs As List(Of Factor)) As RTable
        Dim t As New RTable()
        t.Id = "htmt"
        t.NameCols = True
        t.Title = Tx.T("区分效度：HTMT", "Discriminant Validity: Heterotrait–Monotrait Ratio (HTMT)")
        t.Cols.Add("")
        For Each f As Factor In facs
            t.Cols.Add(f.Name)
        Next
        For a As Integer = 0 To facs.Count - 1
            Dim row As New List(Of String)()
            row.Add(facs(a).Name)
            For b As Integer = 0 To facs.Count - 1
                If b >= a Then
                    row.Add("")
                Else
                    row.Add(N3(Htmt(m, facs(a), facs(b))))
                End If
            Next
            t.Rows.Add(row.ToArray())
        Next
        t.PN("HTMT = 异质—单质比率。", "HTMT = heterotrait–monotrait ratio of correlations.")
        t.Notes.Add("HTMT 用题项相关系数的绝对值计算（Henseler et al., 2015，脚注 7：严格说应取绝对值）。常用参照线 0.85（保守）与 0.90（Henseler et al., 2015）。")
        t.Notes.Add("题项相关的来源：" & m.CovSource & "。")
        Dim maxH As Double = Double.NaN
        Dim hZh As String = ""
        Dim hEn As String = ""
        For a As Integer = 0 To facs.Count - 1
            For b As Integer = 0 To a - 1
                Dim h As Double = Htmt(m, facs(a), facs(b))
                If Not Double.IsNaN(h) AndAlso (Double.IsNaN(maxH) OrElse h > maxH) Then
                    maxH = h
                    hZh = facs(b).Name & " 与 " & facs(a).Name
                    hEn = facs(b).Name & " and " & facs(a).Name
                End If
            Next
        Next
        If Not Double.IsNaN(maxH) Then t.PR("HTMT 的最大值为 " & N3(maxH) & "（" & hZh & "）。", "The largest HTMT value was " & N3(maxH) & " (" & hEn & ").")
        Return t
    End Function

    ' ---- 诊断提示
    Public Shared Function Diagnostics(ByVal m As ModelData, ByVal facs As List(Of Factor)) As List(Of String)
        Dim d As New List(Of String)()
        If Not m.Admissible Then d.Add("AMOS 报告该解不可接受（Admissible = False）：模型可能有负方差等问题，结果请谨慎使用。")
        If Not m.Stable Then d.Add("AMOS 报告模型不稳定（Stable = False）：通常出现在含反馈环的非递归模型里。")
        For Each f As Factor In facs
            For q As Integer = 0 To f.Items.Count - 1
                If Math.Abs(f.Std(q)) > 1 Then d.Add("题项 " & f.Items(q) & " 的标准化载荷为 " & N3(f.Std(q)) & "，超过 1（Heywood 情形），其误差方差为负。")
                If f.Std(q) < 0 Then d.Add("题项 " & f.Items(q) & " 的标准化载荷为负（" & N3(f.Std(q)) & "），检查是否为反向题或设定有误。")
            Next
            If f.CR < 0.7 Then d.Add("构念 " & f.Name & " 的 CR = " & N3(f.CR) & "，低于常用参照线 0.70。")
            If f.AVE < 0.5 Then d.Add("构念 " & f.Name & " 的 AVE = " & N3(f.AVE) & "，低于常用参照线 0.50。")
            If f.AVE < f.MSV Then d.Add("构念 " & f.Name & " 的 AVE（" & N3(f.AVE) & "）小于 MSV（" & N3(f.MSV) & "）：区分效度存疑。")
        Next
        For a As Integer = 0 To facs.Count - 1
            For b As Integer = 0 To a - 1
                Dim r As Double = Corr(m, facs(a).Name, facs(b).Name)
                If Math.Abs(r) >= 0.85 Then d.Add("构念 " & facs(a).Name & " 与 " & facs(b).Name & " 的相关系数为 " & N3(r) & "，≥ 0.85，可能不是两个不同的构念。")
                Dim h As Double = Htmt(m, facs(a), facs(b))
                If Not Double.IsNaN(h) AndAlso h > 0.85 Then d.Add("构念 " & facs(a).Name & " 与 " & facs(b).Name & " 的 HTMT = " & N3(h) & "，高于 0.85。")
            Next
        Next
        If m.ErrorCovPairs.Count > 0 Then d.Add("模型中设了误差相关（" & String.Join("；", m.ErrorCovPairs.ToArray()) & "）：CR 与 AVE 按误差互相独立的标准公式计算，未做修正。")
        If m.NGroups > 1 Then d.Add("模型有 " & m.NGroups.ToString() & " 个组；本报告只报告第 1 组。")
        Return d
    End Function
End Class

' ---------------------------------------------------------------- HTML 输出：单文件、样式内联、三线表
Friend Class HtmlOut
    Public Shared Function H(ByVal s As String) As String
        Return System.Net.WebUtility.HtmlEncode(s)
    End Function

    ' 报告页眉里写明运行环境：AMOS 程序集版本与位数（便于跨版本核对）
    Public Shared Function EnvText() As String
        Return "AMOS 程序集 " & GetType(IPlugin).Assembly.GetName().Version.ToString() & "（" & (IntPtr.Size * 8).ToString() & " 位）"
    End Function

    ' 斜体标记：一对星号之间的文字排斜体（只用于表题、列名、论文表注、结果行文）
    Public Shared Function Mk(ByVal s As String) As String
        Return System.Text.RegularExpressions.Regex.Replace(H(s), "\*([^*<>]+)\*", "<i>$1</i>")
    End Function

    ' 中文、英文各一套，由页面顶部的按钮切换；两套相同时只出一套
    Public Shared Function Bi(ByVal key As String) As String
        Dim z As String = Tx.Zh(key)
        Dim e As String = Tx.En(key)
        If z = e Then Return Mk(z)
        Return "<span class=""zh"">" & Mk(z) & "</span><span class=""en"">" & Mk(e) & "</span>"
    End Function

    ' 几句话连成一段：中文直接相连，英文句间加空格
    Private Shared Function BiJoin(ByVal keys As List(Of String), ByVal zhLead As String, ByVal enLead As String) As String
        Dim z As New StringBuilder()
        Dim e As New StringBuilder()
        For Each k As String In keys
            z.Append(Mk(Tx.Zh(k)))
            If Tx.En(k) = "" Then Continue For
            If e.Length > 0 Then e.Append(" ")
            e.Append(Mk(Tx.En(k)))
        Next
        Dim res As String = ""
        If z.Length > 0 Then res &= "<span class=""zh"">" & zhLead & z.ToString() & "</span>"
        If e.Length > 0 Then res &= "<span class=""en"">" & enLead & e.ToString() & "</span>"
        Return res
    End Function

    ' 页面样式：学术论文的体例（衬线正文、黑体标题、三线表），内容靠左
    Private Shared Function Css() As String
        Dim sb As New StringBuilder()
        sb.AppendLine("body{margin:0;background:#fff;color:#111;font-family:'Times New Roman','Songti SC','SimSun',serif;font-size:16px;line-height:1.7}")
        sb.AppendLine(".doc{margin:0 34px 60px 34px}")
        sb.AppendLine(".bar{position:sticky;top:0;z-index:9;background:#fff;border-bottom:1px solid #d6d6d6;padding:7px 34px;display:flex;flex-wrap:wrap;align-items:center;gap:4px 18px;font:13px/1.6 'Microsoft YaHei','PingFang SC',sans-serif;color:#555}")
        sb.AppendLine(".seg .lab{margin-right:8px}")
        sb.AppendLine(".seg button{font:13px/1.4 'Microsoft YaHei','PingFang SC',sans-serif;padding:2px 12px;border:1px solid #999;background:#fff;color:#222;cursor:pointer;margin:0}")
        sb.AppendLine(".seg button+button{border-left:none}")
        sb.AppendLine(".seg button.on{background:#222;border-color:#222;color:#fff}")
        sb.AppendLine("h1{font-family:'Times New Roman','SimHei','Heiti SC',sans-serif;font-size:24px;line-height:1.35;margin:28px 0 10px 0}")
        sb.AppendLine(".meta{margin:0;padding:8px 0;border-top:1.5px solid #000;border-bottom:1px solid #000;font-size:13.5px;line-height:1.7;color:#333;max-width:900px}")
        sb.AppendLine(".meta span{display:inline-block;margin-right:1.6em}")
        sb.AppendLine("h2{font-family:'Times New Roman','SimHei','Heiti SC',sans-serif;font-size:18.5px;line-height:1.4;margin:40px 0 6px 0}")
        sb.AppendLine(".para{margin:8px 0 0 0;max-width:820px;text-align:justify}")
        sb.AppendLine(".sum,.diag{margin:4px 0 0 0;padding-left:1.4em;max-width:820px}")
        sb.AppendLine(".sum li,.diag li{margin:4px 0;text-align:justify}")
        sb.AppendLine(".tb{margin:26px 0 0 0}")
        sb.AppendLine(".cap{margin:0 0 6px 0;line-height:1.55}")
        sb.AppendLine(".cap.ck{font-weight:bold}")
        sb.AppendLine(".tag{font:12px/1.3 'Microsoft YaHei','PingFang SC',sans-serif;font-weight:normal;color:#777;margin-left:12px;padding:1px 7px;border:1px solid #ccc;border-radius:3px}")
        sb.AppendLine("table{border-collapse:collapse;font-size:15px;line-height:1.45}")
        sb.AppendLine("th,td{padding:4px 14px;text-align:center;white-space:nowrap;vertical-align:top}")
        sb.AppendLine("th{font-weight:normal;vertical-align:bottom}")
        sb.AppendLine("th:first-child,td:first-child{text-align:left;padding-left:3px}")
        sb.AppendLine("table.tc2 th:nth-child(2),table.tc2 td:nth-child(2),table.tc3 th:nth-child(2),table.tc3 td:nth-child(2),table.tc3 th:nth-child(3),table.tc3 td:nth-child(3){text-align:left}")
        sb.AppendLine("table.wrap th:last-child,table.wrap td:last-child{text-align:left;white-space:normal;min-width:260px;max-width:440px}")
        sb.AppendLine("thead th{border-top:1.5px solid #000;border-bottom:1px solid #000}")
        sb.AppendLine("tbody tr:last-child td{border-bottom:1.5px solid #000}")
        sb.AppendLine("th.x,td.x{background:#f4f1e8}")
        sb.AppendLine(".pn{margin:5px 0 0 0;font-size:14px;line-height:1.6;max-width:900px}")
        sb.AppendLine(".pr{margin:14px 0 0 0;padding:1px 0 1px 13px;border-left:2px solid #000;max-width:820px}")
        sb.AppendLine(".pr p{margin:0;text-align:justify}")
        sb.AppendLine(".lb{font:12px/1.9 'Microsoft YaHei','PingFang SC',sans-serif;color:#777;letter-spacing:.5px}")
        sb.AppendLine(".exp{margin:12px 0 0 0;max-width:900px;font-size:14px;line-height:1.65;color:#444}")
        sb.AppendLine(".exp p{margin:2px 0 0 0;text-align:justify}")
        sb.AppendLine("button.cp{font:12px/1.3 'Microsoft YaHei','PingFang SC',sans-serif;margin-left:12px;padding:2px 9px;border:1px solid #b5b5b5;border-radius:3px;background:#fafafa;color:#333;cursor:pointer;vertical-align:1px}")
        sb.AppendLine("button.cp:hover{background:#eee}")
        sb.AppendLine(".lang-zh .en{display:none}")
        sb.AppendLine(".lang-en .zh{display:none}")
        sb.Append("@media print{.bar,button{display:none}th.x,td.x{background:none}.doc{margin:0}}")
        Return sb.ToString()
    End Function

    ' 页面脚本：语言切换；把表格、行文按 Word 认得的行内样式写进剪贴板（三线表，只带当前语言，去掉浅底的列）
    Private Shared Function Js() As String
        Dim sb As New StringBuilder()
        sb.AppendLine("var L='zh',Q='\x22',F='font-family:Times New Roman,SimSun,serif;mso-fareast-font-family:SimSun;';")
        sb.AppendLine("function setL(l){L=(l=='en')?'en':'zh';document.body.className='lang-'+L;document.getElementById('lz').className=(L=='zh')?'on':'';document.getElementById('le').className=(L=='en')?'on':'';try{localStorage.setItem('amosReportLang',L)}catch(e){}}")
        sb.AppendLine("function vis(el){var c=el.cloneNode(true),k=c.querySelectorAll(L=='zh'?'.en,button,.mf-hidden,[hidden]':'.zh,button,.mf-hidden,[hidden]'),i;for(i=0;i<k.length;i++){k[i].parentNode.removeChild(k[i])}return c}")
        sb.AppendLine("function clean(el){return vis(el).innerHTML.replace(/<\/?span[^>]*>/g,'')}")
        sb.AppendLine("function para(sz,mt,mb){return '<p style='+Q+F+'font-size:'+sz+'pt;line-height:1.5;margin:'+mt+'pt 0 '+(mb||0)+'pt 0'+Q+'>'}")
        sb.AppendLine("function tblHtml(n){var b=document.getElementById('b'+n),t=document.getElementById('t'+n),h='',tx='',i,j;")
        sb.AppendLine("var cap=b.querySelector('.cap .'+L),tn=cap.querySelector('.tn'),tt=cap.querySelector('.tt');")
        sb.AppendLine("if(L=='en'){h+=para(12,0)+'<b>'+tn.innerHTML+'</b></p>'+para(12,0,3)+'<i>'+tt.innerHTML+'</i></p>'}else{h+=para(12,0,3)+'<b>'+tn.innerHTML+'</b>　'+tt.innerHTML+'</p>'}")
        sb.AppendLine("tx+=tn.textContent+(L=='en'?'\n':' ')+tt.textContent+'\n';")
        sb.AppendLine("h+='<table cellspacing='+Q+'0'+Q+' cellpadding='+Q+'0'+Q+' style='+Q+'border-collapse:collapse;'+F+'font-size:10.5pt'+Q+'>';")
        sb.AppendLine("var rows=[];for(i=0;i<t.rows.length;i++){if(!t.rows[i].hidden&&!t.rows[i].classList.contains('mf-hidden')){rows.push(t.rows[i])}}for(i=0;i<rows.length;i++){var head=rows[i].parentNode.tagName=='THEAD',last=(i==rows.length-1),cells=rows[i].cells,line=[];h+='<tr>';")
        sb.AppendLine("for(j=0;j<cells.length;j++){var c=cells[j];if(c.className=='x'){continue}var cs=window.getComputedStyle(c),st=F+'font-size:10.5pt;padding:2pt 5pt;text-align:'+(cs.textAlign=='center'?'center':'left')+';vertical-align:'+(head?'bottom':'top')+';';")
        sb.AppendLine("if(head){st+='border-top:1.5pt solid #000;border-bottom:.75pt solid #000;'}if(last){st+='border-bottom:1.5pt solid #000;'}")
        sb.AppendLine("var inner=clean(c);if(!head&&cs.textAlign=='center'){inner=inner.replace(/ (?!\[)/g,'&nbsp;')}h+='<td style='+Q+st+Q+'>'+(inner||'&nbsp;')+'</td>';line.push(vis(c).textContent)}h+='</tr>';tx+=line.join('\t')+'\n'}h+='</table>';")
        sb.AppendLine("var pn=b.querySelector('.pn');if(pn){h+=para(10.5,3)+clean(pn)+'</p>';tx+=vis(pn).textContent+'\n'}return {h:h,t:tx}}")
        sb.AppendLine("function put(o,btn,anchor){var done=false;function hd(e){e.clipboardData.setData('text/html',o.h);e.clipboardData.setData('text/plain',o.t);e.preventDefault();done=true}")
        sb.AppendLine("document.addEventListener('copy',hd);var s=window.getSelection(),r=document.createRange();r.selectNodeContents(anchor);s.removeAllRanges();s.addRange(r);try{document.execCommand('copy')}catch(e){}document.removeEventListener('copy',hd);s.removeAllRanges();")
        sb.AppendLine("if(!done&&navigator.clipboard&&window.ClipboardItem){try{navigator.clipboard.write([new ClipboardItem({'text/html':new Blob([o.h],{type:'text/html'}),'text/plain':new Blob([o.t],{type:'text/plain'})})]);done=true}catch(e){}}")
        sb.AppendLine("var old=btn.getAttribute('data-t')||btn.textContent;btn.setAttribute('data-t',old);btn.textContent=done?'已复制 ✓':'没有复制成功，请手动选中后复制';setTimeout(function(){btn.textContent=old},1600)}")
        sb.AppendLine("function cpT(n,btn){put(tblHtml(n),btn,document.getElementById('t'+n))}")
        sb.AppendLine("function cpP(n,btn){var p=document.getElementById('p'+n);put({h:para(12,0)+clean(p)+'</p>',t:vis(p).textContent},btn,p)}")
        sb.Append("(function(){var l='zh';try{l=localStorage.getItem('amosReportLang')||'zh'}catch(e){}setL(l)})();")
        Return sb.ToString()
    End Function

    Public Shared Function Page(ByVal title As String, ByVal subtitle As String, ByVal tables As List(Of RTable), ByVal diag As List(Of String), ByVal notes As List(Of String), Optional ByVal summary As List(Of String) = Nothing, Optional ByVal beforeTableId As String = "", Optional ByVal beforeTableHtml As String = "", Optional ByVal extraCss As String = "", Optional ByVal extraJs As String = "") As String
        Dim sb As New StringBuilder()
        sb.AppendLine("<!DOCTYPE html>")
        sb.AppendLine("<html lang=""zh-CN""><head><meta charset=""utf-8"">")
        sb.AppendLine("<title>" & H(title) & "</title>")
        sb.AppendLine("<style>")
        sb.AppendLine(Css())
        sb.AppendLine(extraCss)
        sb.AppendLine("</style></head><body class=""lang-zh"">")
        sb.AppendLine("<div class=""bar""><span class=""seg""><span class=""lab"">表格语言</span><button id=""lz"" class=""on"" onclick=""setL('zh')"">中文</button><button id=""le"" onclick=""setL('en')"">English</button></span><span class=""tip"">点「复制表格」得到 APA 格式的三线表，可直接粘贴进 Word；浅底的列和「说明」只供在本页阅读，不随表格复制。</span></div>")
        sb.AppendLine("<div class=""doc"">")
        sb.AppendLine("<h1>" & H(title) & "</h1>")
        sb.Append("<p class=""meta"">")
        For Each part As String In subtitle.Split("；"c)
            If part.Trim() <> "" Then sb.Append("<span>" & H(part.Trim()) & "</span>")
        Next
        sb.AppendLine("</p>")
        If summary IsNot Nothing AndAlso summary.Count > 0 Then
            sb.AppendLine("<h2>结果摘要</h2>")
            sb.AppendLine("<ul class=""sum"">")
            For Each s As String In summary
                sb.AppendLine("<li>" & H(s) & "</li>")
            Next
            sb.AppendLine("</ul>")
        End If
        Dim idx As Integer = 0
        Dim pno As Integer = 0          ' 表号只编给进论文的表；检查用的表不编号
        For Each t As RTable In tables
            idx += 1
            Dim n As String = idx.ToString()
            If t.Paper Then pno += 1
            Dim nc As Integer = t.Cols.Count
            If t.Id = beforeTableId AndAlso beforeTableHtml <> "" Then sb.AppendLine(beforeTableHtml)
            If t.Section <> "" Then sb.AppendLine("<h2>" & H(t.Section) & "</h2>")
            For Each s As String In t.Lead
                sb.AppendLine("<p class=""para"">" & H(s) & "</p>")
            Next
            sb.AppendLine("<div class=""tb"" id=""b" & n & """>")
            ' 表号与表题：中文「表 1　标题」；英文按 APA 第 7 版，表号加粗、表题另起一行排斜体
            If t.Paper Then
                sb.Append("<div class=""cap""><span class=""zh""><b class=""tn"">表 " & pno.ToString() & "</b>　<span class=""tt"">" & Mk(Tx.Zh(t.Title)) & "</span></span>")
                sb.Append("<span class=""en""><b class=""tn"">Table " & pno.ToString() & "</b><br><i class=""tt"">" & Mk(Tx.En(t.Title)) & "</i></span>")
                sb.AppendLine("<button class=""cp"" onclick=""cpT(" & n & ",this)"">复制表格</button></div>")
            Else
                ' 检查用的表：不编号、不分语言、不给复制按钮
                sb.AppendLine("<div class=""cap ck"">" & H(Tx.Zh(t.Title)) & "<span class=""tag"">供检查，不进论文</span></div>")
            End If
            Dim skip(nc) As Boolean
            For j As Integer = 0 To nc - 1
                skip(j) = t.Paper AndAlso t.NoCopy.Contains(t.Cols(j))
            Next
            sb.Append("<table id=""t" & n & """ data-key=""" & H(t.Id) & """" & TableClass(t))
            If t.Extra.Count > 0 Then
                Dim ex As New List(Of String)()
                For Each kv As String() In t.Extra
                    ex.Add(kv(0) & "=" & kv(1))
                Next
                sb.Append(" data-extra=""" & H(String.Join("|", ex.ToArray())) & """")
            End If
            sb.AppendLine("><thead><tr>")
            For j As Integer = 0 To nc - 1
                Dim key As String = t.Cols(j)
                If Not t.Paper Then
                    sb.Append("<th>" & H(key) & "</th>")
                ElseIf t.NameCols AndAlso j >= 1 Then
                    sb.Append("<th>" & H(key) & "</th>")
                Else
                    Dim shown As String = key
                    If key = "" Then shown = "构念"
                    Dim dk As String = " data-k=""" & H(key) & """"
                    sb.Append("<th" & If(skip(j), " class=""x""", "") & dk & ">" & Bi(shown) & "</th>")
                End If
            Next
            sb.AppendLine("</tr></thead><tbody>")
            Dim prevFirst As String = Nothing
            Dim ri As Integer = 0
            For Each r As String() In t.Rows
                sb.Append("<tr")
                If ri < t.RowMeta.Count Then
                    Dim rm As String() = t.RowMeta(ri)
                    sb.Append(" data-mf-group=""" & H(rm(0)) & """ data-mf-path=""" & H(rm(1)) & """ data-mf-kind=""" & H(rm(2)) & """")
                End If
                sb.Append(">")
                For j As Integer = 0 To r.Length - 1
                    Dim raw As String = r(j)
                    If Not t.Paper Then
                        sb.Append("<td>" & H(raw) & "</td>")
                        Continue For
                    End If
                    Dim isSkip As Boolean = (j < nc AndAlso skip(j))
                    Dim isText As Boolean = (j < t.TextCols) OrElse (t.WrapLast AndAlso j = nc - 1) OrElse isSkip
                    Dim dv As String = ""
                    Dim inner As String
                    If t.GroupFirst AndAlso j = 0 AndAlso ri > 0 AndAlso raw = prevFirst Then
                        inner = ""
                        dv = " data-v=""" & H(raw) & """"
                    ElseIf raw <> "" AndAlso Tx.HasRow(raw) Then
                        inner = "<span class=""zh"">" & H(Tx.RowZh(raw)) & "</span><span class=""en"">" & H(Tx.RowEn(raw)) & "</span>"
                        dv = " data-v=""" & H(raw) & """"
                    ElseIf isText Then
                        inner = H(raw)
                    Else
                        inner = H(Ap.Minus(raw))
                    End If
                    If t.BoldDiag AndAlso j = ri + 1 AndAlso inner <> "" Then inner = "<b>" & inner & "</b>"
                    sb.Append("<td" & If(isSkip, " class=""x""", "") & dv & ">" & inner & "</td>")
                Next
                If r.Length > 0 Then prevFirst = r(0)
                ri += 1
                sb.AppendLine("</tr>")
            Next
            sb.AppendLine("</tbody></table>")
            If t.PaperNotes.Count > 0 Then sb.AppendLine("<div class=""pn"">" & BiJoin(t.PaperNotes, "注：", "<i>Note.</i> ") & "</div>")
            If t.Prose.Count > 0 Then
                sb.AppendLine("<div class=""pr""><div class=""lb"">结果行文<button class=""cp"" onclick=""cpP(" & n & ",this)"">复制</button></div><p id=""p" & n & """>" & BiJoin(t.Prose, "", "") & "</p></div>")
            End If
            If t.ProseParts.Count > 0 Then
                sb.AppendLine("<div class=""mf-prose-source"" hidden data-for=""p" & n & """>")
                For Each pp As String() In t.ProseParts
                    sb.AppendLine("<span data-mf-group=""" & H(pp(0)) & """ data-mf-path=""" & H(pp(1)) & """>" & Bi(pp(2)) & "</span>")
                Next
                sb.AppendLine("</div>")
                sb.AppendLine("<p class=""mf-empty"" hidden>当前未选择此表中的中介效应。</p>")
            End If
            If t.Notes.Count > 0 Then
                sb.AppendLine("<div class=""exp""><div class=""lb"">说明</div>")
                For Each s As String In t.Notes
                    sb.AppendLine("<p>" & H(s) & "</p>")
                Next
                sb.AppendLine("</div>")
            End If
            sb.AppendLine("</div>")
            For Each s As String In t.Paras
                sb.AppendLine("<p class=""para"">" & H(s) & "</p>")
            Next
        Next
        If diag IsNot Nothing Then
            sb.AppendLine("<h2>诊断提示</h2>")
            If diag.Count = 0 Then
                sb.AppendLine("<p class=""para"">未发现需要提示的问题。</p>")
            Else
                sb.AppendLine("<ul class=""diag"">")
                For Each d As String In diag
                    sb.AppendLine("<li>" & H(d) & "</li>")
                Next
                sb.AppendLine("</ul>")
            End If
        End If
        If notes IsNot Nothing Then
            For Each s As String In notes
                sb.AppendLine("<p class=""para"">" & H(s) & "</p>")
            Next
        End If
        sb.AppendLine("</div>")
        sb.AppendLine("<script>")
        sb.AppendLine(Js())
        sb.AppendLine(extraJs)
        sb.AppendLine("</script>")
        sb.AppendLine("</body></html>")
        Return sb.ToString()
    End Function

    Private Shared Function TableClass(ByVal t As RTable) As String
        Dim c As String = ""
        If t.WrapLast Then c = "wrap"
        If t.TextCols = 2 Then c = (c & " tc2").Trim()
        If t.TextCols >= 3 Then c = (c & " tc3").Trim()
        If c = "" Then Return ""
        Return " class=""" & c & """"
    End Function

    ' 写文件并用默认浏览器打开；验收进程可显式设置AMOS_PAPER_NO_OPEN=1。
    Public Shared Function WriteAndOpen(ByVal preferredDir As String, ByVal baseName As String, ByVal html As String) As String
        Dim path1 As String = ""
        Try
            path1 = System.IO.Path.Combine(preferredDir, baseName & ".html")
            System.IO.File.WriteAllText(path1, html, New UTF8Encoding(True))
        Catch
            path1 = System.IO.Path.Combine(System.IO.Path.GetTempPath(), baseName & ".html")
            System.IO.File.WriteAllText(path1, html, New UTF8Encoding(True))
        End Try
        If Environment.GetEnvironmentVariable("AMOS_PAPER_NO_OPEN")<>"1" Then
            Dim psi As New System.Diagnostics.ProcessStartInfo(path1)
            psi.UseShellExecute = True
            System.Diagnostics.Process.Start(psi)
        End If
        Return path1
    End Function
End Class

' 论文报告共用层：只接收已选任务的整合表，诊断与运行配置独立保存。
Partial Friend Class Paper
    Public Const Version As String = "1.0.0"
    Private Shared Ready As Boolean=False
    Private Shared Sub Init()
        If Ready Then Return
        Ready=True
        For Each symbol As String In New String(){"SE","b","p","df","M","SD"} : Tx.Reg(symbol,"*" & symbol & "*","*" & symbol & "*") : Next
        Tx.Reg("SEboot","*SE*<sub>boot</sub>","*SE*<sub>boot</sub>")
        Tx.Reg("标准化载荷λ","标准化载荷λ","Standardized loading λ")
        Tx.Row("结构路径","Structural paths") : Tx.Row("总效应","Total effect") : Tx.Row("直接效应","Direct effect") : Tx.Row("总间接效应","Total indirect effect")
        Tx.Row("总效应（均为间接）","Total effect (all indirect)") : Tx.Row("不适用","Not applicable")
        Tx.Reg("效应或对比","效应或对比","Effect or contrast") : Tx.Reg("关系","关系","Relationship")
        Tx.Reg("占总效应","占总效应","% of total") : Tx.Reg("b或Δb","*b*或Δ*b*","*b* or Δ*b*")
        Tx.Reg("间接路径","间接路径","Indirect path") : Tx.Reg("检验项目","检验项目","Test")
        Tx.Reg("结果类型","结果类型","Result") : Tx.Reg("路径或调节值","路径或调节值","Path or moderator value")
        Tx.Reg("b或指数","*b*或指数","*b* or index")
        Tx.Reg("组别或对比","组别或对比","Group or contrast") : Tx.Reg("组别对比","组别对比","Group contrast")
        Tx.Reg("组间差异","组间差异","Between-group test") : Tx.Reg("差值","差值","Difference")
        Tx.Reg("Wald p","Wald *p*","Wald *p*") : Tx.Reg("LRT p","LRT *p*","LRT *p*")
        Tx.Reg("RMSEA (×√G)","RMSEA (× √*G*)","RMSEA (× √*G*)")
    End Sub
    Public Shared Function N(ByVal x As Double, Optional ByVal digits As Integer=3) As String
        If Double.IsNaN(x) OrElse Double.IsInfinity(x) Then Return "—"
        If Math.Abs(x)<0.5*Math.Pow(10,-digits) Then x=0
        Return x.ToString("F" & digits.ToString(),CultureInfo.InvariantCulture)
    End Function
    Public Shared Function P(ByVal x As Double) As String
        If Double.IsNaN(x) Then Return "—"
        If x<0.001 Then Return "< 0.001"
        Return N(x)
    End Function
    Public Shared Function CI(ByVal estimate As Double,ByVal se As Double) As String
        If Double.IsNaN(se) OrElse se<=0 Then Return "—"
        Return "[" & N(estimate-1.95996398454*se) & ", " & N(estimate+1.95996398454*se) & "]"
    End Function
    Public Shared Function Table(ByVal id As String,ByVal title As String,ByVal english As String,ByVal cols() As String,ByVal widths() As Double) As RTable
        Init()
        Dim t As New RTable() : t.Id=id : t.Title=Tx.T(title,english) : t.Cols.AddRange(cols) : t.Widths=widths
        Return t
    End Function
    Public Shared Sub FitColumns(ByVal t As RTable)
        t.Cols.AddRange(New String(){"模型","χ² (df)","χ²/df","CFI","TLI","RMSEA","SRMR"})
    End Sub
    Public Shared Function FitRow(ByVal m As ModelData,ByVal label As String) As String()
        Dim cfi As Double=Double.NaN,tli As Double=Double.NaN
        If m.BaseOK AndAlso m.BaseDf>0 Then
            Dim d As Double=Math.Max(Math.Max(m.BaseCmin-m.BaseDf,m.Cmin-m.Df),0)
            If d>0 Then cfi=1-Math.Max(m.Cmin-m.Df,0)/d
            tli=(m.BaseCmin/m.BaseDf-m.Cmin/m.Df)/(m.BaseCmin/m.BaseDf-1)
        End If
        Return New String(){label,N(m.Cmin,2) & " (" & m.Df.ToString() & ")",If(m.Df>0,N(m.Cmin/m.Df),"—"),N(cfi),N(tli),N(m.Rmsea),N(Calc.Srmr(m))}
    End Function
    Public Shared Function Fit(ByVal m As ModelData,ByVal label As String,ByVal english As String) As RTable
        Dim t As RTable=Table("fit","模型拟合","Model fit",New String(){"模型","χ²","df","p","χ²/df","CFI","TLI","RMSEA [90% CI]","SRMR"},New Double(){1.2,.65,.4,.65,.65,.55,.55,1.6,.6})
        Dim r() As String=FitRow(m,Tx.Row(label,english))
        t.Rows.Add(New String(){r(0),N(m.Cmin,2),m.Df.ToString(),P(m.PVal),r(2),r(3),r(4),r(5) & " [" & N(m.RmseaLo) & ", " & N(m.RmseaHi) & "]",r(6)})
        t.PN("*N* = " & m.NCases.ToString() & "。估计方法为" & If(m.HasMissing,"FIML","ML") & "；RMSEA区间为90% CI；χ²/df作描述。", "*N* = " & m.NCases.ToString() & ". " & If(m.HasMissing,"FIML","ML") & " estimation; RMSEA includes a 90% confidence interval. Chi-square/df is descriptive.")
        Return t
    End Function
    Public Shared Function Measurement(ByVal m As ModelData,ByVal facs As List(Of Factor),Optional ByVal fullCols As Boolean=False) As RTable
        Dim minCr As Double=Double.NaN,maxP As Double=Double.NaN
        For Each f As Factor In facs
            For j As Integer=0 To f.Items.Count-1
                If f.Se(j)>0.0000000001 Then
                    Dim z As Double=f.Est(j)/f.Se(j),az As Double=Math.Abs(z),pz As Double=Calc.PFromZ(z)
                    If Double.IsNaN(minCr) OrElse az<minCr Then minCr=az
                    If Double.IsNaN(maxP) OrElse pz>maxP Then maxP=pz
                End If
            Next
        Next
        Dim t As RTable
        If fullCols Then
            t=Table("measurement","测量模型的载荷与信度效度","Loadings, reliability, and validity",New String(){"构念","题项","b","SE","C.R.","p","标准化载荷λ","R²","α","CR","AVE"},New Double(){1.25,.95,.65,.65,.65,.7,.9,.6,.65,.65,.65})
            For Each f As Factor In facs
                Dim start As Integer=t.Rows.Count
                For j As Integer=0 To f.Items.Count-1
                    If f.Se(j)<=0.0000000001 Then
                        t.Rows.Add(New String(){f.Name,f.Items(j),N(f.Est(j)),"—","—","—",N(f.Std(j)),N(f.Std(j)*f.Std(j)),N(f.AlphaRaw),N(f.CR),N(f.AVE)})
                    Else
                        Dim z As Double=f.Est(j)/f.Se(j)
                        t.Rows.Add(New String(){f.Name,f.Items(j),N(f.Est(j)),N(f.Se(j)),N(z,2),P(Calc.PFromZ(z)),N(f.Std(j)),N(f.Std(j)*f.Std(j)),N(f.AlphaRaw),N(f.CR),N(f.AVE)})
                    End If
                Next
                For Each col As Integer In New Integer(){0,8,9,10}
                    If t.Rows.Count-start>1 Then t.Merges.Add(New Integer(){col,start,t.Rows.Count-1})
                Next
            Next
            t.PN("*N* = " & m.NCases.ToString() & "。*b*为非标准化载荷，*SE*为其标准误，C.R.为临界比（*b*/*SE*），*p*为双侧检验；标「—」的题项为参照指标（载荷固定为1）。λ为完全标准化载荷，*R*²为题项方差解释率；α为Cronbach系数，CR为组合信度（与C.R.不同），AVE为平均方差抽取量。", "*N* = " & m.NCases.ToString() & ". *b* = unstandardized loading; C.R. = critical ratio (*b*/*SE*); dashes indicate reference items with loadings fixed to 1. λ = fully standardized loading; *R*² = squared multiple correlation; α = Cronbach's alpha; CR = composite reliability (distinct from C.R.); AVE = average variance extracted.")
        Else
            t=Table("measurement","测量模型的载荷与信度效度","Loadings, reliability, and validity",New String(){"构念","题项","标准化载荷λ","α","CR","AVE"},New Double(){1.6,1.1,1.3,.8,.9,.9})
            For Each f As Factor In facs
                Dim start As Integer=t.Rows.Count
                For j As Integer=0 To f.Items.Count-1
                    t.Rows.Add(New String(){f.Name,f.Items(j),N(f.Std(j)),N(f.AlphaRaw),N(f.CR),N(f.AVE)})
                Next
                For Each col As Integer In New Integer(){0,3,4,5}
                    If t.Rows.Count-start>1 Then t.Merges.Add(New Integer(){col,start,t.Rows.Count-1})
                Next
            Next
            t.PN("*N* = " & m.NCases.ToString() & "。λ为完全标准化载荷；α为Cronbach系数，CR为组合信度，AVE为平均方差抽取量。", "*N* = " & m.NCases.ToString() & ". Fully standardized loadings; α = Cronbach's alpha; CR = composite reliability; AVE = average variance extracted.")
        End If
        If Not Double.IsNaN(minCr) Then t.SetExtra("min_cr_ratio",N(minCr,2))
        If Not Double.IsNaN(maxP) Then t.SetExtra("max_p",P(maxP))
        If m.ErrorCovPairs.Count>0 Then t.PN("残差相关按当前模型保留：" & String.Join("；",m.ErrorCovPairs.ToArray()) & "。CR/AVE按所列标准化载荷汇总。", "Residual covariances were retained as specified in the model. CR/AVE summarize the standardized loadings shown.")
        Return t
    End Function
    Public Shared Function Correlations(ByVal m As ModelData,ByVal facs As List(Of Factor)) As RTable
        Dim cols As New List(Of String)() : cols.Add("构念")
        Dim widths As New List(Of Double)() : widths.Add(1.3)
        For Each f As Factor In facs : cols.Add(f.Name) : widths.Add(0.9) : Next
        Dim t As RTable=Table("correlations","因子间相关与Fornell–Larcker检验","Factor correlations and the Fornell–Larcker criterion",cols.ToArray(),widths.ToArray()) : t.NameCols=True
        For i As Integer=0 To facs.Count-1
            Dim row(facs.Count) As String : row(0)=facs(i).Name
            For j As Integer=0 To facs.Count-1
                If j<i Then
                    Dim a As Integer=Calc.IndexOf(m.AllNames,facs(i).Name),b As Integer=Calc.IndexOf(m.AllNames,facs(j).Name)
                    row(j+1)=If(a>=0 AndAlso b>=0,N(m.AllCor(a,b)),"—")
                ElseIf j=i Then
                    row(j+1)=N(Math.Sqrt(facs(i).AVE)) : t.BoldCells.Add(New Integer(){i,j+1})
                Else
                    row(j+1)=""
                End If
            Next
            t.Rows.Add(row)
        Next
        t.PN("*N* = " & m.NCases.ToString() & "。粗体对角线为AVE的平方根，下三角为CFA潜变量相关。Fornell–Larcker准则比较AVE的平方根与相应相关系数的绝对值。", "*N* = " & m.NCases.ToString() & ". Bold diagonal entries are square roots of AVE; the lower triangle contains latent factor correlations. Compare diagonal entries with absolute factor correlations.")
        Return t
    End Function
    Public Shared Sub RequireModel(ByVal m As ModelData,Optional ByVal oneGroup As Boolean=True)
        If m.FitStatus<>0 Then Throw New InvalidOperationException(m.FitMessage)
        If Not m.Admissible Then Throw New InvalidOperationException("模型存在不当解，请先运行Model Check处理。")
        If Not m.Stable Then Throw New InvalidOperationException("当前非递归模型不稳定，请先处理模型。")
        If oneGroup AndAlso m.NGroups<>1 Then Throw New InvalidOperationException("当前为多群组模型，请使用CFA Invariance或SEM Multigroup。")
    End Sub
    Public Shared Sub RequireBoot(ByVal m As ModelData)
        If m.BootDirect Is Nothing OrElse m.BootN<5000 OrElse m.BootDirect.Count<>m.BootN Then Throw New InvalidOperationException("Bootstrap未完成，效应区间尚不可用。")
    End Sub
    Public Shared Function BootNote(ByVal m As ModelData) As String
        Return "*N* = " & m.NCases.ToString() & "；非标准化效应；" & m.BootN.ToString("#,0",CultureInfo.InvariantCulture) & "次个体Bootstrap，BC 95% CI，种子" & m.BootSeed.ToString() & "。"
    End Function
End Class

Friend Class PaperHtml
    Friend Shared Function Markup(ByVal text As String) As String
        If text Is Nothing Then Return ""
        Return System.Text.RegularExpressions.Regex.Replace(HtmlOut.H(text),"\*(N|n|p|df|b|SE|SD|M|R|z|r|t|F|q)\*","<i>$1</i>")
    End Function
    Friend Shared Function MarkupProse(ByVal text As String) As String
        If text Is Nothing Then Return ""
        Return Markup(Ap.Minus(text)).Replace("&lt;sub&gt;","<sub>").Replace("&lt;/sub&gt;","</sub>")
    End Function
    Private Shared Function Bi(ByVal key As String) As String
        Dim text As String="<span class=""zh"">" & Markup(Tx.Zh(key)) & "</span><span class=""en"">" & Markup(Tx.En(key)) & "</span>"
        Return text.Replace("&lt;sub&gt;","<sub>").Replace("&lt;/sub&gt;","</sub>")
    End Function
    Private Shared Function Cell(ByVal value As String) As String
        If value Is Nothing Then Return ""
        If Tx.HasRow(value) Then Return "<span class=""zh"">" & Markup(Tx.RowZh(value)) & "</span><span class=""en"">" & Markup(Tx.RowEn(value)) & "</span>"
        Dim result As String=HtmlOut.H(value).Replace(vbLf,"<br>")
        Dim stars As Integer=0
        For i As Integer=value.Length-1 To 0 Step -1
            If value(i)<>"*"c Then Exit For
            stars+=1
        Next
        If stars>0 AndAlso stars<=3 Then result=HtmlOut.H(value.Substring(0,value.Length-stars)) & "<sup>" & New String("*"c,stars) & "</sup>"
        Return result
    End Function
    Private Shared Function RenderTable(ByVal t As RTable,ByVal cssClass As String,ByVal isCheck As Boolean) As String
        If t.Cols.Count=0 OrElse t.Rows.Count=0 Then Return ""
        Dim n As Integer=t.Cols.Count,ws(n-1) As Double,total As Double=0
        For i As Integer=0 To n-1
            ws(i)=If(t.Widths IsNot Nothing AndAlso t.Widths.Length=n,t.Widths(i),1.0) : total+=ws(i)
        Next
        Dim sb As New StringBuilder("<div class=""table-wrap""><table class=""" & cssClass & """>")
        If Not isCheck Then
            sb.Append("<colgroup>")
            For Each w As Double In ws : sb.Append("<col style=""width:" & (w/total*100).ToString("0.####",CultureInfo.InvariantCulture) & "%"">") : Next
            sb.Append("</colgroup>")
        End If
        sb.Append("<thead><tr>")
        Dim grouped(n-1) As Boolean
        For Each span As Integer() In t.HeaderGroups
            For j As Integer=span(0) To span(1) : grouped(j)=True : Next
        Next
        Dim skip As Integer=-1
        For i As Integer=0 To n-1
            If i<=skip Then Continue For
            Dim spanEnd As Integer=i
            For Each span As Integer() In t.HeaderGroups
                If span(0)=i Then spanEnd=span(1)
            Next
            Dim attributes As String=""
            If spanEnd>i Then
                attributes=" colspan=""" & (spanEnd-i+1).ToString() & """" : skip=spanEnd
            ElseIf t.HeaderGroups.Count>0 Then
                attributes=" rowspan=""2"""
            End If
            Dim headHtml As String=If(isCheck,HtmlOut.H(t.Cols(i)),If(t.NameCols AndAlso i>0,HtmlOut.H(t.Cols(i)),Bi(t.Cols(i))))
            sb.Append("<th" & attributes & ">" & headHtml & "</th>")
        Next
        sb.Append("</tr>")
        If t.HeaderGroups.Count>0 Then
            If t.Header2 Is Nothing OrElse t.Header2.Length<>n Then Throw New InvalidOperationException("分组表头列数不一致。")
            sb.Append("<tr>")
            For i As Integer=0 To n-1
                If grouped(i) Then sb.Append("<th>" & If(isCheck,HtmlOut.H(t.Header2(i)),Bi(t.Header2(i))) & "</th>")
            Next
            sb.Append("</tr>")
        End If
        sb.Append("</thead><tbody>")
        For r As Integer=0 To t.Rows.Count-1
            If t.Rows(r).Length<>n Then Throw New InvalidOperationException("结果表列数不一致：" & t.Title)
            sb.Append("<tr>")
            For c As Integer=0 To n-1
                Dim hide As Boolean=False,rowspan As Integer=1,bold As Boolean=False
                For Each merge As Integer() In t.Merges
                    If merge(0)=c Then
                        If r>merge(1) AndAlso r<=merge(2) Then hide=True
                        If r=merge(1) Then rowspan=merge(2)-merge(1)+1
                    End If
                Next
                If hide Then Continue For
                For Each pos As Integer() In t.BoldCells
                    If pos(0)=r AndAlso pos(1)=c Then bold=True
                Next
                Dim rawVal As String=If(t.Rows(r)(c),"")
                Dim v As String=If(isCheck,HtmlOut.H(rawVal).Replace(vbLf,"<br>"),Cell(rawVal))
                If bold Then v="<strong>" & v & "</strong>"
                Dim cellAttr As String=If(rowspan>1," rowspan=""" & rowspan.ToString() & """","")
                If isCheck Then
                    If rawVal="必须改" Then
                        cellAttr &= " class=""lv-must"""
                    ElseIf rawVal="建议查看" Then
                        cellAttr &= " class=""lv-sug"""
                    ElseIf rawVal="通过" Then
                        cellAttr &= " class=""lv-pass"""
                    End If
                End If
                sb.Append("<td" & cellAttr & ">" & v & "</td>")
            Next
            sb.Append("</tr>")
        Next
        sb.Append("</tbody></table></div>")
        Return sb.ToString()
    End Function
    Public Shared Function Render(ByVal t As RTable) As String
        Return RenderTable(t,"paper",False)
    End Function
    Private Shared Function RenderInterpList(ByVal t As RTable) As String
        If t.Interp Is Nothing OrElse t.Interp.Count=0 Then Return ""
        Dim sb As New StringBuilder("<ul class=""interp-list"">")
        For Each item As String() In t.Interp
            If item Is Nothing OrElse item.Length<3 Then Continue For
            Dim lv As String=If(item(0),"info").Trim().ToLowerInvariant()
            If lv<>"ok" AndAlso lv<>"warn" AndAlso lv<>"info" Then lv="info"
            Dim bZh As String=If(lv="ok","达标",If(lv="warn","关注","提示"))
            Dim bEn As String=If(lv="ok","OK",If(lv="warn","Check","Info"))
            sb.Append("<li class=""interp-item""><span class=""badge badge-" & lv & """><span class=""zh"">" & bZh & "</span><span class=""en"">" & bEn & "</span></span><span class=""interp-text""><span class=""zh"">" & MarkupProse(item(1)) & "</span><span class=""en"">" & MarkupProse(item(2)) & "</span></span></li>")
        Next
        sb.Append("</ul>")
        Return sb.ToString()
    End Function
    Public Shared Function Page(ByVal title As String,ByVal subtitle As String,ByVal tables As List(Of RTable),Optional ByVal diagnostics As List(Of String)=Nothing,Optional ByVal extra As String="") As String
        If tables Is Nothing Then tables=New List(Of RTable)()
        For Each t As RTable In tables
            If t IsNot Nothing AndAlso t.Rows.Count>0 Then PaperInterp.Populate(t)
        Next
        Dim sb As New StringBuilder("<!doctype html><html lang=""zh-CN""><meta charset=""utf-8""><meta name=""viewport"" content=""width=device-width,initial-scale=1""><title>" & HtmlOut.H(title) & "</title><style>" & PaperAssets.Css & "</style><body class=""lang-zh""><div class=""bar""><button data-lang=""zh"" onclick=""paperSetLanguage('zh')"">中文</button><button data-lang=""en"" onclick=""paperSetLanguage('en')"">English</button><button onclick=""paperCopy('all')"">一键复制全部论文表</button><button onclick=""paperCopyAllProse()"">一键复制全部结果行文</button><button onclick=""paperToggleInterp(this)"">隐藏统计解读</button><span id=""copy-status-all""></span><button onclick=""window.print()"">打印</button></div><main class=""doc""><h1>" & HtmlOut.H(title) & "</h1><p class=""meta"">" & HtmlOut.H(subtitle) & "</p>")
        Dim number As Integer=0
        Dim checkTables As New List(Of RTable)()
        For Each t As RTable In tables
            If t Is Nothing OrElse t.Rows.Count=0 Then Continue For
            If Not t.Paper Then
                checkTables.Add(t)
                Continue For
            End If
            number+=1
            Dim numStr As String=number.ToString()
            sb.Append("<article class=""table-block"" id=""block-" & numStr & """ data-table-id=""" & HtmlOut.H(t.Id) & """>")
            sb.Append("<div class=""copy-tools""><button onclick=""paperCopy('" & numStr & "')"">复制此表</button>")
            If t.Prose.Count>0 Then sb.Append("<button onclick=""paperCopyProse('" & numStr & "')"">复制结果行文</button>")
            sb.Append("<span id=""copy-status-" & numStr & """></span></div>")
            sb.Append("<div class=""paper-content"" id=""paper-" & numStr & """><p class=""table-no""><span class=""zh"">表 " & numStr & "</span><span class=""en"">Table " & numStr & "</span></p><p class=""table-title"">" & Bi(t.Title) & "</p>" & Render(t))
            If t.PaperNotes.Count>0 Then
                sb.Append("<p class=""note""><span class=""zh""><i>注.</i> </span><span class=""en""><i>Note.</i> </span>")
                For Each note As String In t.PaperNotes : sb.Append(Bi(note) & " ") : Next
                sb.Append("</p>")
            End If
            sb.Append("</div>")
            If t.Interp.Count>0 OrElse t.Prose.Count>0 Then
                sb.Append("<div class=""interp-card"" id=""interp-" & numStr & """>")
                If t.Interp.Count>0 Then
                    sb.Append("<div class=""interp-head""><span class=""zh"">统计结果解读</span><span class=""en"">Statistical Interpretation</span></div>" & RenderInterpList(t))
                End If
                If t.Prose.Count>0 Then
                    Dim zhParts As New List(Of String)(),enParts As New List(Of String)()
                    For Each pr As String In t.Prose
                        Dim zText As String=Tx.Zh(pr),eText As String=Tx.En(pr)
                        If zText<>"" Then zhParts.Add(MarkupProse(zText))
                        If eText<>"" Then enParts.Add(MarkupProse(eText))
                    Next
                    sb.Append("<div class=""prose-box""><div class=""prose-label""><span class=""zh"">论文汇报参考</span><span class=""en"">Manuscript Text</span></div><p class=""prose-text"" id=""prose-" & numStr & """><span class=""zh"">" & String.Join("",zhParts.ToArray()) & "</span><span class=""en"">" & String.Join(" ",enParts.ToArray()) & "</span></p></div>")
                End If
                sb.Append("</div>")
            End If
            sb.Append("</article>")
        Next
        If number=0 Then
            sb.Replace("<button onclick=""paperCopy('all')"">一键复制全部论文表</button>","")
            sb.Replace("<button onclick=""paperCopyAllProse()"">一键复制全部结果行文</button>","")
            sb.Append("<p class=""status"">检查完成。当前任务没有需要复制到论文的统计表。</p>")
        End If
        If checkTables.Count>0 Then
            sb.Append("<section class=""check-section"" id=""check-section""><h2><span class=""zh"">模型诊断与检查详情（供检查，不进论文）</span><span class=""en"">Model Diagnostics &amp; Checks (Not for Manuscript)</span></h2>")
            For Each ct As RTable In checkTables
                sb.Append("<div class=""check-block"" data-check-id=""" & HtmlOut.H(ct.Id) & """><h3>" & Markup(Tx.Zh(ct.Title)) & "</h3>")
                For Each s As String In ct.Lead
                    sb.Append("<p class=""check-lead"">" & HtmlOut.H(s) & "</p>")
                Next
                If ct.Interp.Count>0 Then sb.Append(RenderInterpList(ct))
                sb.Append(RenderTable(ct,"check-table",True))
                If ct.Notes.Count>0 Then
                    sb.Append("<div class=""check-notes"">")
                    For Each s As String In ct.Notes
                        sb.Append("<p>" & HtmlOut.H(s) & "</p>")
                    Next
                    sb.Append("</div>")
                End If
                sb.Append("</div>")
            Next
            sb.Append("</section>")
        End If
        sb.Append(extra)
        If diagnostics IsNot Nothing AndAlso diagnostics.Count>0 Then
            sb.Append("<details><summary>计算说明</summary><ul>")
            For Each note As String In diagnostics : sb.Append("<li>" & HtmlOut.H(note) & "</li>") : Next
            sb.Append("</ul></details>")
        End If
        sb.Append("</main><script>" & PaperAssets.Js & "</script></body></html>")
        Return sb.ToString()
    End Function
    Public Shared Function Save(ByVal m As ModelData,ByVal plugin As String,ByVal title As String,ByVal tables As List(Of RTable),ByVal diagnostics As List(Of String),Optional ByVal extra As String="") As String
        Dim name As String=Path.GetFileNameWithoutExtension(m.AmwPath)
        If name="" Then name="Model"
        Dim meta As String=plugin & " " & Paper.Version & "；" & name & "；" & If(m.NGroups>1,m.NGroups.ToString() & "组", "N = " & m.NCases.ToString()) & "；" & HtmlOut.EnvText()
        Dim html As String=Page(title,meta,tables,diagnostics,extra)
        Dim outPath As String=HtmlOut.WriteAndOpen(Path.GetDirectoryName(m.AmwPath),name & "_" & plugin,html)
        File.WriteAllText(Path.ChangeExtension(outPath,"run.txt"),meta & vbCrLf & "model=" & m.AmwPath & vbCrLf & "data=" & m.FileName & vbCrLf & "bootstrap=" & m.BootPlanned.ToString() & "; usable=" & m.BootN.ToString() & "; seed=" & m.BootSeed.ToString() & "; BC 95%" & vbCrLf & DateTime.Now.ToString("s") & vbCrLf & If(diagnostics Is Nothing,"",String.Join(vbCrLf,diagnostics.ToArray())),New UTF8Encoding(True))
        File.WriteAllText(Path.Combine(Path.GetTempPath(),"AmosLastReport.txt"),outPath,New UTF8Encoding(False))
        Return outPath
    End Function
End Class

' ============================================================================
' PaperInterp.vb —— 自动统计结果解读与双语 APA 行文生成引擎
' 按 RTable.Id 解析表格与 Extra 元数据，生成带 ok/warn/info 徽章的解读与行文。
' ============================================================================

Friend Class PaperInterp
    Public Shared Sub Populate(ByVal t As RTable)
        If t Is Nothing OrElse t.Rows.Count = 0 Then Return
        Dim existing As New List(Of String())(t.Interp)
        Dim generated As New List(Of String())()
        Dim id As String = If(t.Id, "").Trim().ToLowerInvariant()
        Select Case id
            Case "fit"
                InterpFit(t, generated)
            Case "measurement"
                InterpMeasurement(t, generated)
            Case "correlations", "fl"
                InterpCorrelations(t, generated)
            Case "discriminant_ci", "cfax_ci"
                InterpDiscriminantCi(t, generated)
            Case "higher"
                InterpHigher(t, generated)
            Case "descriptives"
                InterpDescriptives(t, generated)
            Case "paths"
                InterpPaths(t, generated)
            Case "effects"
                InterpEffects(t, generated)
            Case "moderation"
                InterpModeration(t, generated)
            Case "conditional"
                InterpConditional(t, generated)
            Case "cmv"
                InterpCmv(t, generated)
            Case "invariance"
                InterpInvariance(t, generated)
            Case "latentmeans"
                InterpLatentMeans(t, generated)
            Case "multigroup"
                InterpMultigroup(t, generated)
            Case "multigroup_pairs", "pairwise"
                InterpMultigroupPairs(t, generated)
            Case "groupindirect"
                InterpGroupIndirect(t, generated)
            Case "cfax_mods"
                InterpMods(t, generated)
            Case "count"
                InterpCount(t, generated)
            Case "normality"
                InterpNormality(t, generated)
            Case "mahal"
                InterpMahal(t, generated)
            Case "check1", "check2", "check3"
                InterpCheckSection(t, generated)
            Case "missing"
                InterpMissing(t, generated)
            Case "unid"
                InterpUnid(t, generated)
            Case "measure"
                InterpMeasureSummary(t, generated)
        End Select

        t.Interp.Clear()
        t.Interp.AddRange(existing)
        For Each item As String() In generated
            If Not HasSameLead(t.Interp, item(1)) Then
                t.Interp.Add(item)
            End If
        Next
    End Sub

    Private Shared Function HasSameLead(ByVal items As List(Of String()), ByVal zh As String) As Boolean
        If zh = "" Then Return True
        Dim key As String = zh
        If key.Length > 10 Then key = key.Substring(0, 10)
        For Each ex As String() In items
            If ex IsNot Nothing AndAlso ex.Length >= 2 Then
                If ex(1) = zh OrElse (ex(1).Length >= 10 AndAlso ex(1).StartsWith(key, StringComparison.Ordinal)) Then Return True
            End If
        Next
        Return False
    End Function

    Private Shared Sub AddTo(ByVal list As List(Of String()), ByVal level As String, ByVal zh As String, ByVal en As String)
        list.Add(New String() {level, zh, en})
    End Sub

    ' ---------------------------------------------------------------- 通用解析工具
    Private Shared Function FindCol(ByVal t As RTable, ByVal ParamArray names() As String) As Integer
        For Each nm As String In names
            For i As Integer = 0 To t.Cols.Count - 1
                If String.Equals(t.Cols(i).Trim(), nm, StringComparison.OrdinalIgnoreCase) Then Return i
            Next
        Next
        For Each nm As String In names
            For i As Integer = 0 To t.Cols.Count - 1
                If t.Cols(i).IndexOf(nm, StringComparison.OrdinalIgnoreCase) >= 0 Then Return i
            Next
        Next
        Return -1
    End Function

    Private Shared Function CellText(ByVal row() As String, ByVal col As Integer) As String
        If row Is Nothing OrElse col < 0 OrElse col >= row.Length OrElse row(col) Is Nothing Then Return ""
        Return row(col).Trim()
    End Function

    Private Shared Function CleanNumStr(ByVal s As String) As String
        If s Is Nothing Then Return ""
        Dim t As String = s.Replace("−", "-").Replace("*", "").Replace("%", "").Trim()
        Return t
    End Function

    Private Shared Function ParseNum(ByVal s As String) As Double
        Dim t As String = CleanNumStr(s)
        If t = "" OrElse t = "—" OrElse t = "-" Then Return Double.NaN
        Dim v As Double
        If Double.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, v) Then Return v
        Return Double.NaN
    End Function

    Private Shared Function ParseFirstNum(ByVal s As String) As Double
        If s Is Nothing Then Return Double.NaN
        Dim t As String = s.Replace("−", "-").Trim()
        Dim m As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(t, "-?\d+(?:\.\d+)?")
        If Not m.Success Then Return Double.NaN
        Dim v As Double
        If Double.TryParse(m.Value, NumberStyles.Float, CultureInfo.InvariantCulture, v) Then Return v
        Return Double.NaN
    End Function

    Private Shared Function ParseParenInt(ByVal s As String) As Integer
        If s Is Nothing Then Return -1
        Dim m As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(s, "\(\s*(\d+)\s*\)")
        If Not m.Success Then Return -1
        Dim v As Integer
        If Integer.TryParse(m.Groups(1).Value, NumberStyles.Integer, CultureInfo.InvariantCulture, v) Then Return v
        Return -1
    End Function

    Private Shared Function ParsePVal(ByVal s As String, ByRef isSig05 As Boolean) As Double
        isSig05 = False
        If s Is Nothing Then Return Double.NaN
        Dim t As String = s.Trim()
        If t = "" OrElse t = "—" Then Return Double.NaN
        If t.StartsWith("<") Then
            Dim subNum As Double = ParseFirstNum(t)
            If Not Double.IsNaN(subNum) Then
                isSig05 = (subNum <= 0.05)
                Return subNum * 0.5
            End If
            isSig05 = True
            Return 0.0005
        End If
        Dim p As Double = ParseNum(t)
        If Not Double.IsNaN(p) Then isSig05 = (p < 0.05)
        Return p
    End Function

    Private Shared Function ParseCI(ByVal s As String, ByRef lo As Double, ByRef hi As Double) As Boolean
        lo = Double.NaN
        hi = Double.NaN
        If s Is Nothing Then Return False
        Dim t As String = s.Replace("−", "-").Trim()
        Dim ms As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(t, "-?\d+(?:\.\d+)?")
        If ms.Count < 2 Then Return False
        Dim ok1 As Boolean = Double.TryParse(ms(0).Value, NumberStyles.Float, CultureInfo.InvariantCulture, lo)
        Dim ok2 As Boolean = Double.TryParse(ms(1).Value, NumberStyles.Float, CultureInfo.InvariantCulture, hi)
        Return ok1 AndAlso ok2
    End Function

    Private Shared Function ExcludesZero(ByVal lo As Double, ByVal hi As Double) As Boolean
        If Double.IsNaN(lo) OrElse Double.IsNaN(hi) Then Return False
        Return (lo > 0.0 AndAlso hi > 0.0) OrElse (lo < 0.0 AndAlso hi < 0.0)
    End Function

    Private Shared Function Fmt3(ByVal x As Double) As String
        Return Ap.Minus(Paper.N(x, 3))
    End Function

    Private Shared Function Fmt2(ByVal x As Double) As String
        Return Ap.Minus(Paper.N(x, 2))
    End Function

    Private Shared Function RowLabel(ByVal raw As String, ByVal enLang As Boolean) As String
        If raw Is Nothing Then Return ""
        If Tx.HasRow(raw) Then Return If(enLang, Tx.RowEn(raw), Tx.RowZh(raw))
        Return raw
    End Function

    Private Shared Sub SetProseIfEmpty(ByVal t As RTable, ByVal zh As String, ByVal en As String)
        If t.Prose.Count = 0 AndAlso zh <> "" AndAlso en <> "" Then
            t.PR(zh, en)
        End If
    End Sub

    ' ---------------------------------------------------------------- 1. 拟合表 (fit)
    Private Shared Sub InterpFit(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cModel As Integer = FindCol(t, "模型", "Model")
        Dim cChiDf As Integer = FindCol(t, "χ² (df)")
        Dim cChi As Integer = FindCol(t, "χ²")
        Dim cDf As Integer = FindCol(t, "df")
        Dim cP As Integer = FindCol(t, "p")
        Dim cRatio As Integer = FindCol(t, "χ²/df")
        Dim cCfi As Integer = FindCol(t, "CFI")
        Dim cTli As Integer = FindCol(t, "TLI")
        Dim cRmsea As Integer = FindCol(t, "RMSEA [90% CI]", "RMSEA")
        Dim cSrmr As Integer = FindCol(t, "SRMR")
        Dim cAic As Integer = FindCol(t, "AIC")
        Dim cBic As Integer = FindCol(t, "BIC")
        Dim cDChi As Integer = FindCol(t, "Δχ² (Δdf)")

        If cCfi = cRatio Then cCfi = -1
        If cChi = cChiDf OrElse cChi = cRatio Then
            cChi = -1
            For i As Integer = 0 To t.Cols.Count - 1
                If t.Cols(i).Trim() = "χ²" Then cChi = i
            Next
        End If
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim r0() As String = t.Rows(0)
        Dim cfi As Double = ParseNum(CellText(r0, cCfi))
        Dim tli As Double = ParseNum(CellText(r0, cTli))
        Dim rmseaStr As String = CellText(r0, cRmsea)
        Dim rmsea As Double = ParseFirstNum(rmseaStr)
        Dim srmr As Double = ParseNum(CellText(r0, cSrmr))
        Dim ratio As Double = ParseNum(CellText(r0, cRatio))

        If t.Rows.Count = 1 Then
            ' 单模型整体拟合
            If Not Double.IsNaN(cfi) AndAlso Not Double.IsNaN(tli) Then
                If cfi >= 0.95 AndAlso tli >= 0.95 Then
                    AddTo(out, "ok", "增量拟合优良：CFI = " & Fmt3(cfi) & "，TLI = " & Fmt3(tli) & "，均达到 ≥ 0.95 的现代严格拟合标准。", "Good incremental fit: CFI = " & Fmt3(cfi) & " and TLI = " & Fmt3(tli) & ", both meeting the ≥ 0.95 criterion.")
                ElseIf cfi >= 0.90 AndAlso tli >= 0.90 Then
                    AddTo(out, "ok", "增量拟合可接受：CFI = " & Fmt3(cfi) & "，TLI = " & Fmt3(tli) & "，均达到 ≥ 0.90 传统标准（现代严格标准为 ≥ 0.95）。", "Acceptable incremental fit: CFI = " & Fmt3(cfi) & " and TLI = " & Fmt3(tli) & ", meeting the ≥ 0.90 threshold (strict benchmark ≥ 0.95).")
                Else
                    AddTo(out, "warn", "增量拟合偏低：CFI = " & Fmt3(cfi) & "，TLI = " & Fmt3(tli) & "，至少一项低于 0.90 参考线，建议检查测量或结构设定。", "Suboptimal incremental fit: CFI = " & Fmt3(cfi) & " and TLI = " & Fmt3(tli) & "; at least one index is below 0.90.")
                End If
            End If

            Dim absPartsZh As New List(Of String)()
            Dim absPartsEn As New List(Of String)()
            Dim absOk As Boolean = True
            Dim absGood As Boolean = True
            If Not Double.IsNaN(rmsea) Then
                absPartsZh.Add("RMSEA = " & Fmt3(rmsea))
                absPartsEn.Add("RMSEA = " & Fmt3(rmsea))
                If rmsea > 0.08 Then
                    absOk = False : absGood = False
                ElseIf rmsea > 0.06 Then
                    absGood = False
                End If
            End If
            If Not Double.IsNaN(srmr) Then
                absPartsZh.Add("SRMR = " & Fmt3(srmr))
                absPartsEn.Add("SRMR = " & Fmt3(srmr))
                If srmr > 0.08 Then absOk = False : absGood = False
            End If
            If absPartsZh.Count > 0 Then
                If absGood Then
                    AddTo(out, "ok", "绝对拟合优良：" & String.Join("，", absPartsZh.ToArray()) & "（满足 RMSEA ≤ 0.06 与 SRMR ≤ 0.08）。", "Good absolute fit: " & String.Join(", ", absPartsEn.ToArray()) & " (RMSEA ≤ 0.06, SRMR ≤ 0.08).")
                ElseIf absOk Then
                    AddTo(out, "ok", "绝对拟合可接受：" & String.Join("，", absPartsZh.ToArray()) & "（满足 RMSEA ≤ 0.08 与 SRMR ≤ 0.08）。", "Acceptable absolute fit: " & String.Join(", ", absPartsEn.ToArray()) & " (RMSEA ≤ 0.08, SRMR ≤ 0.08).")
                Else
                    AddTo(out, "warn", "绝对拟合欠佳：" & String.Join("，", absPartsZh.ToArray()) & "（超出 RMSEA ≤ 0.08 或 SRMR ≤ 0.08 参考线）。", "Weak absolute fit: " & String.Join(", ", absPartsEn.ToArray()) & " (exceeds RMSEA ≤ 0.08 or SRMR ≤ 0.08).")
                End If
            End If

            If Not Double.IsNaN(ratio) Then
                Dim pSig As Boolean = False
                Dim pVal As Double = ParsePVal(CellText(r0, cP), pSig)
                If ratio <= 3.0 Then
                    AddTo(out, "info", "χ²/*df* = " & Fmt3(ratio) & "（≤ 3.0）" & If(pSig AndAlso Not Double.IsNaN(pVal), "；卡方检验受样本量影响显著（*p* " & If(CellText(r0, cP).StartsWith("<"), CellText(r0, cP), "= " & CellText(r0, cP)) & "），模型评估应结合 CFI、TLI、RMSEA 与 SRMR。", "。"), "χ²/*df* = " & Fmt3(ratio) & " (≤ 3.0)" & If(pSig AndAlso Not Double.IsNaN(pVal), "; χ² significance is sensitive to sample size (*p* " & If(CellText(r0, cP).StartsWith("<"), CellText(r0, cP), "= " & CellText(r0, cP)) & "), so evaluate fit primarily via CFI, TLI, RMSEA, and SRMR.", "."))
                ElseIf ratio <= 5.0 Then
                    AddTo(out, "info", "χ²/*df* = " & Fmt3(ratio) & "（介于 3.0 与 5.0 之间，需结合样本量与其余指标综合判断）。", "χ²/*df* = " & Fmt3(ratio) & " (between 3.0 and 5.0; interpret alongside sample size and approximate fit indices).")
                Else
                    AddTo(out, "warn", "χ²/*df* = " & Fmt3(ratio) & "（> 5.0），卡方与自由度比值偏高。", "χ²/*df* = " & Fmt3(ratio) & " (> 5.0), indicating elevated model misfit.")
                End If
            End If

            If t.Prose.Count = 0 Then
                Dim chiStr As String = CellText(r0, cChi)
                Dim dfStr As String = CellText(r0, cDf)
                Dim pStr As String = CellText(r0, cP)
                Dim mZh As String = RowLabel(CellText(r0, cModel), False)
                Dim mEn As String = RowLabel(CellText(r0, cModel), True)
                Dim partsZh As New List(Of String)()
                Dim partsEn As New List(Of String)()
                If chiStr <> "" AndAlso dfStr <> "" Then
                    partsZh.Add("χ²(" & dfStr & ") = " & chiStr)
                    partsEn.Add("χ²(" & dfStr & ") = " & chiStr)
                End If
                If pStr <> "" AndAlso pStr <> "—" Then
                    partsZh.Add(Ap.PEq(pStr))
                    partsEn.Add(Ap.PEq(pStr))
                End If
                If Not Double.IsNaN(ratio) Then
                    partsZh.Add("χ²/*df* = " & Fmt3(ratio))
                    partsEn.Add("χ²/*df* = " & Fmt3(ratio))
                End If
                If Not Double.IsNaN(cfi) Then
                    partsZh.Add("CFI = " & Fmt3(cfi))
                    partsEn.Add("CFI = " & Fmt3(cfi))
                End If
                If Not Double.IsNaN(tli) Then
                    partsZh.Add("TLI = " & Fmt3(tli))
                    partsEn.Add("TLI = " & Fmt3(tli))
                End If
                If Not Double.IsNaN(rmsea) Then
                    Dim rlo As Double, rhi As Double
                    If ParseCI(rmseaStr.Substring(Math.Max(0, rmseaStr.IndexOf("["))), rlo, rhi) Then
                        partsZh.Add("RMSEA = " & Fmt3(rmsea) & "（90% CI [" & Fmt3(rlo) & ", " & Fmt3(rhi) & "]）")
                        partsEn.Add("RMSEA = " & Fmt3(rmsea) & " (90% CI [" & Fmt3(rlo) & ", " & Fmt3(rhi) & "])")
                    Else
                        partsZh.Add("RMSEA = " & Fmt3(rmsea))
                        partsEn.Add("RMSEA = " & Fmt3(rmsea))
                    End If
                End If
                If Not Double.IsNaN(srmr) Then
                    partsZh.Add("SRMR = " & Fmt3(srmr))
                    partsEn.Add("SRMR = " & Fmt3(srmr))
                End If
                SetProseIfEmpty(t, mZh & "的拟合指标为：" & String.Join("，", partsZh.ToArray()) & "。", "The " & mEn.ToLowerInvariant() & " showed " & String.Join(", ", partsEn.ToArray()) & ".")
            End If
        Else
            ' 多行竞争模型比较
            Dim m0Zh As String = RowLabel(CellText(r0, cModel), False)
            Dim m0En As String = RowLabel(CellText(r0, cModel), True)
            If Not Double.IsNaN(cfi) AndAlso Not Double.IsNaN(rmsea) Then
                Dim ok0 As Boolean = (cfi >= 0.90 AndAlso (Double.IsNaN(tli) OrElse tli >= 0.90) AndAlso rmsea <= 0.08 AndAlso (Double.IsNaN(srmr) OrElse srmr <= 0.08))
                AddTo(out, If(ok0, "ok", "warn"), m0Zh & "拟合" & If(ok0, "达标", "有待改善") & "：CFI = " & Fmt3(cfi) & "，TLI = " & Fmt3(tli) & "，RMSEA = " & Fmt3(rmsea) & If(Double.IsNaN(srmr), "", "，SRMR = " & Fmt3(srmr)) & "。", m0En & " fit was " & If(ok0, "acceptable", "suboptimal") & ": CFI = " & Fmt3(cfi) & ", TLI = " & Fmt3(tli) & ", RMSEA = " & Fmt3(rmsea) & If(Double.IsNaN(srmr), "", ", SRMR = " & Fmt3(srmr)) & ".")
            End If

            If cAic >= 0 OrElse cBic >= 0 Then
                Dim bestAicIdx As Integer = -1, bestAic As Double = Double.MaxValue
                Dim bestBicIdx As Integer = -1, bestBic As Double = Double.MaxValue
                For i As Integer = 0 To t.Rows.Count - 1
                    Dim aic As Double = ParseNum(CellText(t.Rows(i), cAic))
                    Dim bic As Double = ParseNum(CellText(t.Rows(i), cBic))
                    If Not Double.IsNaN(aic) AndAlso aic < bestAic Then bestAic = aic : bestAicIdx = i
                    If Not Double.IsNaN(bic) AndAlso bic < bestBic Then bestBic = bic : bestBicIdx = i
                Next
                If bestAicIdx >= 0 Then
                    Dim aZh As String = RowLabel(CellText(t.Rows(bestAicIdx), cModel), False)
                    Dim aEn As String = RowLabel(CellText(t.Rows(bestAicIdx), cModel), True)
                    Dim bZh As String = If(bestBicIdx >= 0, RowLabel(CellText(t.Rows(bestBicIdx), cModel), False), "")
                    Dim bEn As String = If(bestBicIdx >= 0, RowLabel(CellText(t.Rows(bestBicIdx), cModel), True), "")
                    Dim isFirstBest As Boolean = (bestAicIdx = 0 AndAlso (bestBicIdx < 0 OrElse bestBicIdx = 0))
                    If bestBicIdx = bestAicIdx OrElse bestBicIdx < 0 Then
                        AddTo(out, If(isFirstBest, "ok", "warn"), "信息准则比较：" & aZh & "取得最小 AIC（" & Fmt2(bestAic) & "）" & If(bestBicIdx >= 0, "与最小 BIC（" & Fmt2(bestBic) & "）", "") & "，模型相对更优。", "Information criteria: " & aEn & " achieved the lowest AIC (" & Fmt2(bestAic) & ")" & If(bestBicIdx >= 0, " and BIC (" & Fmt2(bestBic) & ")", "") & ".")
                    Else
                        AddTo(out, "info", "信息准则比较：AIC 最小为 " & aZh & "（" & Fmt2(bestAic) & "），BIC 最小为 " & bZh & "（" & Fmt2(bestBic) & "）。", "Information criteria: lowest AIC for " & aEn & " (" & Fmt2(bestAic) & ") and lowest BIC for " & bEn & " (" & Fmt2(bestBic) & ").")
                    End If
                End If
            End If

            If cDChi >= 0 Then
                Dim nCmp As Integer = 0, nSig As Integer = 0
                For i As Integer = 0 To t.Rows.Count - 1
                    Dim dcStr As String = CellText(t.Rows(i), cDChi)
                    If dcStr = "" OrElse dcStr = "—" Then Continue For
                    nCmp += 1
                    Dim sig As Boolean = False
                    ParsePVal(CellText(t.Rows(i), cP), sig)
                    If sig Then nSig += 1
                Next
                If nCmp > 0 Then
                    AddTo(out, If(nSig = nCmp, "ok", "info"), "嵌套模型 χ² 差异检验：共 " & nCmp.ToString() & " 项比较，其中 " & nSig.ToString() & " 项拟合差异显著（*p* < 0.05）。", "Nested χ² difference tests: " & nSig.ToString() & " of " & nCmp.ToString() & " comparisons showed significant fit differences (*p* < 0.05).")
                End If
            End If

            If t.Prose.Count = 0 Then
                Dim pZh As String = "竞争模型比较中，" & m0Zh & "的拟合为 " & If(cChiDf >= 0, "χ²(*df*) = " & CellText(r0, cChiDf) & "，", "") & "CFI = " & Fmt3(cfi) & "，TLI = " & Fmt3(tli) & "，RMSEA = " & Fmt3(rmsea) & If(Double.IsNaN(srmr), "", "，SRMR = " & Fmt3(srmr)) & "。"
                Dim pEn As String = "In competing-model comparisons, the " & m0En.ToLowerInvariant() & " yielded " & If(cChiDf >= 0, "χ²(*df*) = " & CellText(r0, cChiDf) & ", ", "") & "CFI = " & Fmt3(cfi) & ", TLI = " & Fmt3(tli) & ", RMSEA = " & Fmt3(rmsea) & If(Double.IsNaN(srmr), "", ", SRMR = " & Fmt3(srmr)) & "."
                SetProseIfEmpty(t, pZh, pEn)
            End If
        End If
    End Sub

    ' ---------------------------------------------------------------- 2. 测量模型 (measurement)
    Private Shared Sub InterpMeasurement(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cCon As Integer = FindCol(t, "构念", "Construct")
        Dim cItem As Integer = FindCol(t, "题项", "Item")
        Dim cLam As Integer = FindCol(t, "标准化载荷λ", "λ")
        Dim cAlpha As Integer = FindCol(t, "α")
        Dim cCr As Integer = FindCol(t, "CR")
        Dim cAve As Integer = FindCol(t, "AVE")
        Dim cP As Integer = FindCol(t, "p")
        If cCr >= 0 AndAlso t.Cols(cCr).Trim() = "C.R." Then
            cCr = -1
            For i As Integer = 0 To t.Cols.Count - 1
                If t.Cols(i).Trim() = "CR" Then cCr = i
            Next
        End If
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim lams As New List(Of Double)()
        Dim low50 As New List(Of String)(), low70 As New List(Of String)(), negItems As New List(Of String)()
        Dim seenCon As New List(Of String)()
        Dim alphas As New List(Of Double)(), crs As New List(Of Double)(), aves As New List(Of Double)()
        Dim lowAlpha As New List(Of String)(), lowCr As New List(Of String)(), lowAve As New List(Of String)()
        Dim nFree As Integer = 0, nNonSig As Integer = 0

        For Each r As String() In t.Rows
            Dim con As String = CellText(r, cCon)
            Dim item As String = CellText(r, cItem)
            Dim lam As Double = ParseNum(CellText(r, cLam))
            If Not Double.IsNaN(lam) Then
                lams.Add(lam)
                If lam < 0 Then negItems.Add(item)
                If Math.Abs(lam) < 0.50 Then
                    low50.Add(item & "(" & Fmt3(lam) & ")")
                ElseIf Math.Abs(lam) < 0.70 Then
                    low70.Add(item & "(" & Fmt3(lam) & ")")
                End If
            End If
            If cP >= 0 Then
                Dim ps As String = CellText(r, cP)
                If ps <> "" AndAlso ps <> "—" Then
                    nFree += 1
                    Dim sig As Boolean = False
                    ParsePVal(ps, sig)
                    If Not sig Then nNonSig += 1
                End If
            End If
            If con <> "" AndAlso Not seenCon.Contains(con) Then
                seenCon.Add(con)
                Dim al As Double = ParseNum(CellText(r, cAlpha))
                Dim cr As Double = ParseNum(CellText(r, cCr))
                Dim ave As Double = ParseNum(CellText(r, cAve))
                If Not Double.IsNaN(al) Then
                    alphas.Add(al)
                    If al < 0.70 Then lowAlpha.Add(con & "(" & Fmt3(al) & ")")
                End If
                If Not Double.IsNaN(cr) Then
                    crs.Add(cr)
                    If cr < 0.70 Then lowCr.Add(con & "(" & Fmt3(cr) & ")")
                End If
                If Not Double.IsNaN(ave) Then
                    aves.Add(ave)
                    If ave < 0.50 Then lowAve.Add(con & "(" & Fmt3(ave) & ")")
                End If
            End If
        Next

        Dim lLo As Double, lHi As Double
        Ap.Range(lams, lLo, lHi)
        If lams.Count > 0 Then
            If negItems.Count > 0 OrElse low50.Count > 0 Then
                AddTo(out, "warn", "标准化因子载荷范围为 " & Fmt3(lLo) & "–" & Fmt3(lHi) & "，存在偏低题项（< 0.50）：" & String.Join("、", low50.ToArray()) & If(negItems.Count > 0, "；负载荷：" & String.Join("、", negItems.ToArray()), "") & "。", "Standardized loadings ranged from " & Fmt3(lLo) & " to " & Fmt3(lHi) & "; low loadings (< 0.50) found for: " & String.Join(", ", low50.ToArray()) & ".")
            ElseIf low70.Count > 0 Then
                AddTo(out, "info", "标准化因子载荷范围为 " & Fmt3(lLo) & "–" & Fmt3(lHi) & "（均 ≥ 0.50），其中 " & String.Join("、", low70.ToArray()) & " 低于 0.70 理想线，可结合 CR 与 AVE 决定是否保留。", "Standardized loadings ranged from " & Fmt3(lLo) & " to " & Fmt3(lHi) & " (all ≥ 0.50); items below 0.70: " & String.Join(", ", low70.ToArray()) & ".")
            Else
                AddTo(out, "ok", "全部 " & lams.Count.ToString() & " 个题项的标准化载荷介于 " & Fmt3(lLo) & "–" & Fmt3(lHi) & "，均 ≥ 0.70。", "All " & lams.Count.ToString() & " standardized item loadings ranged from " & Fmt3(lLo) & " to " & Fmt3(lHi) & " (all ≥ 0.70).")
            End If
        End If

        Dim minCrStr As String = t.GetExtra("min_cr_ratio")
        Dim maxPStr As String = t.GetExtra("max_p")
        Dim sigZh As String = "", sigEn As String = ""
        If nFree > 0 Then
            If nNonSig = 0 Then
                AddTo(out, "ok", "全部 " & nFree.ToString() & " 个自由估计载荷在 *p* < 0.05 水平上显著" & If(maxPStr <> "", "（最大 *p* " & If(maxPStr.StartsWith("<"), maxPStr, "= " & maxPStr) & "）", "") & "。", "All " & nFree.ToString() & " freely estimated loadings were statistically significant (*p* < 0.05" & If(maxPStr <> "", ", max *p* " & If(maxPStr.StartsWith("<"), maxPStr, "= " & maxPStr), "") & ").")
            Else
                AddTo(out, "warn", "有 " & nNonSig.ToString() & " 个自由估计载荷未达 *p* < 0.05 显著性水平。", nNonSig.ToString() & " freely estimated loading(s) did not reach *p* < 0.05.")
            End If
        ElseIf minCrStr <> "" AndAlso maxPStr <> "" Then
            Dim crNum As Double = ParseNum(minCrStr)
            AddTo(out, If(crNum >= 1.96, "ok", "warn"), "自由载荷最小临界比 |C.R.| = " & Ap.Minus(minCrStr) & "（最大 " & Ap.PEq(maxPStr) & "），" & If(crNum >= 1.96, "全部载荷统计显著。", "部分载荷显著性不足。"), "Minimum |C.R.| for free loadings = " & Ap.Minus(minCrStr) & " (max " & Ap.PEq(maxPStr) & "); " & If(crNum >= 1.96, "all free loadings are statistically significant.", "some loadings are non-significant."))
        End If

        If maxPStr <> "" Then
            If maxPStr.StartsWith("<") Then
                sigZh = "（自由载荷均 *p* " & maxPStr & "）" : sigEn = " (all free loadings *p* " & maxPStr & ")"
            Else
                sigZh = "（自由载荷 *p* ≤ " & maxPStr & "）" : sigEn = " (free loadings *p* ≤ " & maxPStr & ")"
            End If
        End If

        Dim aLo As Double, aHi As Double, cLo As Double, cHi As Double, vLo As Double, vHi As Double
        Ap.Range(alphas, aLo, aHi)
        Ap.Range(crs, cLo, cHi)
        Ap.Range(aves, vLo, vHi)
        If crs.Count > 0 Then
            If lowAlpha.Count = 0 AndAlso lowCr.Count = 0 Then
                AddTo(out, "ok", "内部一致性信度良好：" & If(alphas.Count > 0, "Cronbach α = " & Fmt3(aLo) & "–" & Fmt3(aHi) & "，", "") & "CR = " & Fmt3(cLo) & "–" & Fmt3(cHi) & "，均 ≥ 0.70。", "Good internal consistency: " & If(alphas.Count > 0, "Cronbach's α = " & Fmt3(aLo) & "–" & Fmt3(aHi) & ", ", "") & "CR = " & Fmt3(cLo) & "–" & Fmt3(cHi) & " (all ≥ 0.70).")
            Else
                Dim wParts As New List(Of String)()
                If lowAlpha.Count > 0 Then wParts.Add("α < 0.70：" & String.Join("、", lowAlpha.ToArray()))
                If lowCr.Count > 0 Then wParts.Add("CR < 0.70：" & String.Join("、", lowCr.ToArray()))
                AddTo(out, "warn", "部分构念信度低于 0.70 阈值（" & String.Join("；", wParts.ToArray()) & "）。", "Some constructs scored below the 0.70 reliability threshold.")
            End If
        End If
        If aves.Count > 0 Then
            If lowAve.Count = 0 Then
                AddTo(out, "ok", "聚合效度达标：各构念 AVE = " & Fmt3(vLo) & "–" & Fmt3(vHi) & "，均 ≥ 0.50。", "Convergent validity supported: construct AVE ranged from " & Fmt3(vLo) & " to " & Fmt3(vHi) & " (all ≥ 0.50).")
            Else
                AddTo(out, "warn", "聚合效度不足：以下构念 AVE < 0.50：" & String.Join("、", lowAve.ToArray()) & "。", "Convergent validity concern (AVE < 0.50): " & String.Join(", ", lowAve.ToArray()) & ".")
            End If
        End If

        If t.Prose.Count = 0 AndAlso lams.Count > 0 Then
            Dim pZh As String = "测量模型共 " & seenCon.Count.ToString() & " 个构念、" & lams.Count.ToString() & " 个题项，标准化载荷介于 " & Fmt3(lLo) & " 至 " & Fmt3(lHi) & " 之间" & sigZh & "；" & If(alphas.Count > 0, "Cronbach α 为 " & Fmt3(aLo) & "–" & Fmt3(aHi) & "，", "") & "CR 为 " & Fmt3(cLo) & "–" & Fmt3(cHi) & "，AVE 为 " & Fmt3(vLo) & "–" & Fmt3(vHi) & "。"
            Dim pEn As String = "Across the " & seenCon.Count.ToString() & " constructs (" & lams.Count.ToString() & " items), standardized loadings ranged from " & Fmt3(lLo) & " to " & Fmt3(lHi) & sigEn & "; " & If(alphas.Count > 0, "Cronbach's α ranged from " & Fmt3(aLo) & " to " & Fmt3(aHi) & ", ", "") & "CR from " & Fmt3(cLo) & " to " & Fmt3(cHi) & ", and AVE from " & Fmt3(vLo) & " to " & Fmt3(vHi) & "."
            SetProseIfEmpty(t, pZh, pEn)
        End If
    End Sub

    ' ---------------------------------------------------------------- 3. 相关与 Fornell-Larcker (correlations / fl)
    Private Shared Sub InterpCorrelations(ByVal t As RTable, ByVal out As List(Of String()))
        Dim k As Integer = t.Rows.Count
        If k < 2 Then Return
        Dim diags As New List(Of Double)()
        Dim names As New List(Of String)()
        Dim violations As New List(Of String)()
        Dim maxAbsR As Double = -1.0, maxR As Double = 0.0
        Dim maxPairZh As String = "", maxPairEn As String = ""

        For i As Integer = 0 To k - 1
            Dim nm As String = CellText(t.Rows(i), 0)
            names.Add(nm)
            diags.Add(ParseNum(CellText(t.Rows(i), i + 1)))
        Next

        For i As Integer = 0 To k - 1
            Dim d As Double = diags(i)
            Dim maxRel As Double = 0.0
            For j As Integer = 0 To k - 1
                If i = j Then Continue For
                Dim r As Double = If(j < i, ParseNum(CellText(t.Rows(i), j + 1)), ParseNum(CellText(t.Rows(j), i + 1)))
                If Double.IsNaN(r) Then Continue For
                If Math.Abs(r) > maxRel Then maxRel = Math.Abs(r)
                If j < i AndAlso Math.Abs(r) > maxAbsR Then
                    maxAbsR = Math.Abs(r)
                    maxR = r
                    maxPairZh = names(j) & " 与 " & names(i)
                    maxPairEn = names(j) & " and " & names(i)
                End If
            Next
            If Not Double.IsNaN(d) AndAlso maxRel >= d Then
                violations.Add(names(i) & "(√AVE=" & Fmt3(d) & " ≤ |r|=" & Fmt3(maxRel) & ")")
            End If
        Next

        Dim dLo As Double, dHi As Double
        Ap.Range(diags, dLo, dHi)
        If violations.Count = 0 Then
            AddTo(out, "ok", "Fornell–Larcker 检验通过：各构念 √AVE（" & Fmt3(dLo) & "–" & Fmt3(dHi) & "）均大于其与其他构念的相关系数绝对值。", "Fornell–Larcker criterion satisfied: all √AVE values (" & Fmt3(dLo) & "–" & Fmt3(dHi) & ") exceeded the corresponding inter-construct |r|.")
        Else
            AddTo(out, "warn", "Fornell–Larcker 区分效度存疑：" & String.Join("、", violations.ToArray()) & "。", "Fornell–Larcker violation(s): " & String.Join(", ", violations.ToArray()) & ".")
        End If

        If maxAbsR >= 0 Then
            If maxAbsR < 0.85 Then
                AddTo(out, "ok", "潜变量最大相关为 " & maxPairZh & "（*r* = " & Fmt3(maxR) & "），绝对值低于 0.85 冗余参考线。", "Largest factor correlation was between " & maxPairEn & " (*r* = " & Fmt3(maxR) & "), below the 0.85 threshold.")
            Else
                AddTo(out, "warn", "潜变量相关偏高：" & maxPairZh & " 的 *r* = " & Fmt3(maxR) & "（|r| ≥ 0.85），建议进一步检查竞争模型或区间上限。", "High factor correlation: " & maxPairEn & " (*r* = " & Fmt3(maxR) & ", |r| ≥ 0.85); inspect competing models and CI upper limits.")
            End If
            SetProseIfEmpty(t, "各构念 AVE 平方根介于 " & Fmt3(dLo) & " 至 " & Fmt3(dHi) & " 之间；构念间绝对值最大的相关为 " & maxPairZh & "（*r* = " & Fmt3(maxR) & "），" & If(violations.Count = 0, "满足", "未完全满足") & " Fornell–Larcker 区分效度准则。", "Square roots of AVE ranged from " & Fmt3(dLo) & " to " & Fmt3(dHi) & "; the largest absolute factor correlation was between " & maxPairEn & " (*r* = " & Fmt3(maxR) & "), " & If(violations.Count = 0, "supporting", "showing violations of") & " the Fornell–Larcker criterion.")
        End If
    End Sub

    ' ---------------------------------------------------------------- 4. 因子相关区间区分效度 (discriminant_ci / cfax_ci)
    Private Shared Sub InterpDiscriminantCi(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cPair As Integer = FindCol(t, "因子对", "构念对")
        Dim cR As Integer = FindCol(t, "相关 r", "r")
        Dim cWald As Integer = FindCol(t, "Wald 95% CI", "Wald 95% 区间")
        Dim cBc As Integer = FindCol(t, "BC 95% CI", "BC 95% 区间")
        Dim cP As Integer = FindCol(t, "p")
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim rs As New List(Of Double)()
        Dim tier(3) As Integer
        Dim worstPair As String = "", worstUl As Double = Double.NaN
        Dim nLrt As Integer = 0, nSig As Integer = 0

        For Each row As String() In t.Rows
            Dim pair As String = CellText(row, cPair)
            Dim r As Double = ParseNum(CellText(row, cR))
            If Double.IsNaN(r) Then Continue For
            rs.Add(r)
            Dim lo As Double, hi As Double
            Dim hasCi As Boolean = False
            If cBc >= 0 AndAlso ParseCI(CellText(row, cBc), lo, hi) Then
                hasCi = True
            ElseIf cWald >= 0 AndAlso ParseCI(CellText(row, cWald), lo, hi) Then
                hasCi = True
            End If
            If hasCi Then
                Dim ul As Double = If(r >= 0, hi, -lo)
                Dim cls As Integer = If(ul < 0.80, 0, If(ul < 0.90, 1, If(ul < 1.0, 2, 3)))
                tier(cls) += 1
                If Double.IsNaN(worstUl) OrElse ul > worstUl Then
                    worstUl = ul
                    worstPair = pair
                End If
            End If
            If cP >= 0 Then
                Dim ps As String = CellText(row, cP)
                If ps <> "" AndAlso ps <> "—" Then
                    nLrt += 1
                    Dim sig As Boolean = False
                    ParsePVal(ps, sig)
                    If sig Then nSig += 1
                End If
            End If
        Next

        If Not Double.IsNaN(worstUl) Then
            Dim tot As Integer = tier(0) + tier(1) + tier(2) + tier(3)
            If tier(2) = 0 AndAlso tier(3) = 0 AndAlso tier(1) = 0 Then
                AddTo(out, "ok", "按 Rönkkö & Cho (2022) 四档标准，全部 " & tot.ToString() & " 对因子相关的 95% CI 上限均 < 0.80（最大上限 " & Fmt3(worstUl) & "，" & worstPair & "），属「无问题」档。", "Under Rönkkö & Cho (2022), all " & tot.ToString() & " factor pairs had 95% CI upper limits < 0.80 (highest = " & Fmt3(worstUl) & " for " & worstPair & "), indicating no discriminant-validity concern.")
            ElseIf tier(2) = 0 AndAlso tier(3) = 0 Then
                AddTo(out, "info", "按 Rönkkö & Cho (2022) 四档标准：" & tier(0).ToString() & " 对无问题（< 0.80），" & tier(1).ToString() & " 对处于边缘档（0.80–0.90；最大上限 " & Fmt3(worstUl) & "，" & worstPair & "），宜说明偏高原因。", "Under Rönkkö & Cho (2022): " & tier(0).ToString() & " pair(s) < 0.80 (no problem) and " & tier(1).ToString() & " marginal (0.80–0.90; highest = " & Fmt3(worstUl) & " for " & worstPair & ").")
            Else
                AddTo(out, "warn", "按 Rönkkö & Cho (2022) 标准存在高相关警告：中等问题（0.90–1.00）" & tier(2).ToString() & " 对、严重问题（≥ 1.00）" & tier(3).ToString() & " 对；最大上限为 " & worstPair & "（" & Fmt3(worstUl) & "）。", "Discriminant-validity warning (Rönkkö & Cho, 2022): " & tier(2).ToString() & " moderate (0.90–1.00) and " & tier(3).ToString() & " severe (≥ 1.00) pair(s); highest upper limit = " & Fmt3(worstUl) & " (" & worstPair & ").")
            End If
        End If

        If nLrt > 0 Then
            If nSig = nLrt Then
                AddTo(out, "ok", "将因子相关逐对固定为 1 的 Δχ²(1) 检验全部显著（" & nSig.ToString() & "/" & nLrt.ToString() & " 对 *p* < 0.05），均显著区别于完全相关。", "Constraining each factor correlation to 1 yielded significant Δχ²(1) worsening for all " & nLrt.ToString() & " pairs (*p* < 0.05).")
            Else
                AddTo(out, "warn", "有 " & (nLrt - nSig).ToString() & "/" & nLrt.ToString() & " 对因子在相关固定为 1 时 Δχ²(1) 未达显著（*p* ≥ 0.05），无法在统计上与单构念区分。", (nLrt - nSig).ToString() & " of " & nLrt.ToString() & " pairs failed to show significant Δχ²(1) when fixed to 1 (*p* ≥ 0.05).")
            End If
        End If

        If rs.Count > 0 AndAlso Not Double.IsNaN(worstUl) Then
            Dim rLo As Double, rHi As Double
            Ap.Range(rs, rLo, rHi)
            SetProseIfEmpty(t, "各构念间因子相关介于 " & Fmt3(rLo) & " 至 " & Fmt3(rHi) & " 之间；95% 置信区间上限最高为 " & worstPair & "（上限 = " & Fmt3(worstUl) & "）" & If(nLrt > 0, "，且 " & nSig.ToString() & "/" & nLrt.ToString() & " 对相关的 Δχ²(1) 检验达 *p* < 0.05", "") & "。", "Factor correlations ranged from " & Fmt3(rLo) & " to " & Fmt3(rHi) & "; the highest 95% CI upper limit was " & Fmt3(worstUl) & " (" & worstPair & ")" & If(nLrt > 0, ", with " & nSig.ToString() & "/" & nLrt.ToString() & " Δχ²(1) tests significant at *p* < 0.05", "") & ".")
        End If
    End Sub

    ' ---------------------------------------------------------------- 5. 高阶因子 (higher)
    Private Shared Sub InterpHigher(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cHi As Integer = FindCol(t, "高阶因子")
        Dim cLam As Integer = FindCol(t, "标准化载荷λ", "λ")
        Dim cR2 As Integer = FindCol(t, "R²")
        Dim cCr As Integer = FindCol(t, "CR")
        Dim cAve As Integer = FindCol(t, "AVE")
        Dim lams As New List(Of Double)(), r2s As New List(Of Double)(), crs As New List(Of Double)(), aves As New List(Of Double)()
        Dim seen As New List(Of String)()

        For Each r As String() In t.Rows
            Dim lam As Double = ParseNum(CellText(r, cLam))
            Dim r2 As Double = ParseNum(CellText(r, cR2))
            If Not Double.IsNaN(lam) Then lams.Add(lam)
            If Not Double.IsNaN(r2) Then r2s.Add(r2)
            Dim hiName As String = CellText(r, cHi)
            If hiName <> "" AndAlso Not seen.Contains(hiName) Then
                seen.Add(hiName)
                Dim cr As Double = ParseNum(CellText(r, cCr))
                Dim ave As Double = ParseNum(CellText(r, cAve))
                If Not Double.IsNaN(cr) Then crs.Add(cr)
                If Not Double.IsNaN(ave) Then aves.Add(ave)
            End If
        Next
        If lams.Count > 0 Then
            Dim lLo As Double, lHi As Double, rLo As Double, rHi As Double
            Ap.Range(lams, lLo, lHi)
            Ap.Range(r2s, rLo, rHi)
            AddTo(out, If(lLo >= 0.70, "ok", If(lLo >= 0.50, "info", "warn")), "高阶到一阶因子标准化载荷 λ = " & Fmt3(lLo) & "–" & Fmt3(lHi) & "，方差解释率 *R*² = " & Fmt3(rLo) & "–" & Fmt3(rHi) & "。", "Higher-order standardized loadings ranged from " & Fmt3(lLo) & " to " & Fmt3(lHi) & " (*R*² = " & Fmt3(rLo) & "–" & Fmt3(rHi) & ").")
            If crs.Count > 0 AndAlso aves.Count > 0 Then
                Dim cLo As Double, cHi2 As Double, aLo As Double, aHi As Double
                Ap.Range(crs, cLo, cHi2)
                Ap.Range(aves, aLo, aHi)
                Dim ok As Boolean = (cLo >= 0.70 AndAlso aLo >= 0.50)
                AddTo(out, If(ok, "ok", "warn"), "高阶构念 CR = " & Fmt3(cLo) & If(cHi2 > cLo, "–" & Fmt3(cHi2), "") & "，AVE = " & Fmt3(aLo) & If(aHi > aLo, "–" & Fmt3(aHi), "") & "，" & If(ok, "均达到 CR ≥ 0.70 与 AVE ≥ 0.50 标准。", "未完全达到 CR ≥ 0.70 或 AVE ≥ 0.50 标准。"), "Higher-order CR = " & Fmt3(cLo) & If(cHi2 > cLo, "–" & Fmt3(cHi2), "") & " and AVE = " & Fmt3(aLo) & If(aHi > aLo, "–" & Fmt3(aHi), "") & " (" & If(ok, "meets CR ≥ 0.70 and AVE ≥ 0.50", "below CR ≥ 0.70 or AVE ≥ 0.50") & ").")
                SetProseIfEmpty(t, "高阶因子到一阶因子的标准化载荷介于 " & Fmt3(lLo) & " 与 " & Fmt3(lHi) & " 之间（*R*² = " & Fmt3(rLo) & "–" & Fmt3(rHi) & "），高阶层面的 CR = " & Fmt3(cLo) & "，AVE = " & Fmt3(aLo) & "。", "Higher-order factor loadings ranged from " & Fmt3(lLo) & " to " & Fmt3(lHi) & " (*R*² = " & Fmt3(rLo) & "–" & Fmt3(rHi) & "), with higher-order CR = " & Fmt3(cLo) & " and AVE = " & Fmt3(aLo) & ".")
            End If
        End If
    End Sub

    ' ---------------------------------------------------------------- 6. 描述统计与相关 (descriptives)
    Private Shared Sub InterpDescriptives(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cM As Integer = FindCol(t, "M")
        Dim cSd As Integer = FindCol(t, "SD")
        Dim ms As New List(Of Double)(), sds As New List(Of Double)(), rs As New List(Of Double)()
        Dim nPairs As Integer = 0, nSig As Integer = 0

        For i As Integer = 0 To t.Rows.Count - 1
            Dim mv As Double = ParseNum(CellText(t.Rows(i), cM))
            Dim sv As Double = ParseNum(CellText(t.Rows(i), cSd))
            If Not Double.IsNaN(mv) Then ms.Add(mv)
            If Not Double.IsNaN(sv) Then sds.Add(sv)
            For j As Integer = 0 To i - 1
                Dim cell As String = CellText(t.Rows(i), j + 3)
                Dim rv As Double = ParseNum(cell)
                If Not Double.IsNaN(rv) Then
                    rs.Add(rv)
                    nPairs += 1
                    If cell.Contains("*") Then nSig += 1
                End If
            Next
        Next
        If ms.Count > 0 AndAlso sds.Count > 0 Then
            Dim mLo As Double, mHi As Double, sLo As Double, sHi As Double
            Ap.Range(ms, mLo, mHi)
            Ap.Range(sds, sLo, sHi)
            AddTo(out, "info", "各构念均分均值 *M* 介于 " & Fmt3(mLo) & "–" & Fmt3(mHi) & "，标准差 *SD* 介于 " & Fmt3(sLo) & "–" & Fmt3(sHi) & "。", "Construct means (*M*) ranged from " & Fmt3(mLo) & " to " & Fmt3(mHi) & ", and *SD* from " & Fmt3(sLo) & " to " & Fmt3(sHi) & ".")
            If rs.Count > 0 Then
                Dim rLo As Double, rHi As Double
                Ap.Range(rs, rLo, rHi)
                AddTo(out, If(nSig > 0, "ok", "info"), "构念间 Pearson 相关 *r* 范围为 " & Fmt3(rLo) & "–" & Fmt3(rHi) & "，共 " & nSig.ToString() & "/" & nPairs.ToString() & " 对在 *p* < 0.05 水平上显著相关。", "Pearson correlations (*r*) ranged from " & Fmt3(rLo) & " to " & Fmt3(rHi) & ", with " & nSig.ToString() & " of " & nPairs.ToString() & " pairs significant at *p* < 0.05.")
                SetProseIfEmpty(t, "描述统计显示，各构念均分 *M* 为 " & Fmt3(mLo) & "–" & Fmt3(mHi) & "（*SD* = " & Fmt3(sLo) & "–" & Fmt3(sHi) & "），构念间 Pearson 相关系数介于 " & Fmt3(rLo) & " 至 " & Fmt3(rHi) & " 之间（" & nSig.ToString() & "/" & nPairs.ToString() & " 对 *p* < 0.05）。", "Construct score means ranged from " & Fmt3(mLo) & " to " & Fmt3(mHi) & " (*SD* = " & Fmt3(sLo) & "–" & Fmt3(sHi) & "), and Pearson correlations ranged from " & Fmt3(rLo) & " to " & Fmt3(rHi) & " (" & nSig.ToString() & " of " & nPairs.ToString() & " pairs *p* < 0.05).")
            End If
        End If
    End Sub

    ' ---------------------------------------------------------------- 7. 结构路径 (paths)
    Private Shared Sub InterpPaths(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cPath As Integer = FindCol(t, "路径", "Path")
        Dim cB As Integer = FindCol(t, "b")
        Dim cBeta As Integer = FindCol(t, "β", "标准化系数 β")
        Dim cP As Integer = FindCol(t, "p")
        Dim cR2 As Integer = FindCol(t, "R²")
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim nTotal As Integer = 0, nSig As Integer = 0, nNonSig As Integer = 0
        Dim maxPosPath As String = "", maxPosBeta As Double = -1.0, maxPosP As String = ""
        Dim minNegPath As String = "", minNegBeta As Double = 1.0, minNegP As String = ""
        Dim nonSigNames As New List(Of String)()
        Dim r2s As New List(Of Double)(), r2PartsZh As New List(Of String)(), r2PartsEn As New List(Of String)()
        Dim seenOutcomes As New List(Of String)()
        Dim proseItems As New List(Of String)()

        For Each row As String() In t.Rows
            Dim pathStr As String = CellText(row, cPath)
            Dim bVal As Double = ParseNum(CellText(row, cB))
            Dim betaVal As Double = ParseNum(CellText(row, cBeta))
            Dim pStr As String = CellText(row, cP)
            Dim sig As Boolean = False
            Dim pVal As Double = ParsePVal(pStr, sig)
            If Not Double.IsNaN(pVal) Then
                nTotal += 1
                If sig Then nSig += 1 Else nNonSig += 1 : nonSigNames.Add(pathStr)
            End If
            If Not Double.IsNaN(betaVal) Then
                If sig AndAlso betaVal > 0 AndAlso betaVal > maxPosBeta Then
                    maxPosBeta = betaVal : maxPosPath = pathStr : maxPosP = pStr
                End If
                If sig AndAlso betaVal < 0 AndAlso betaVal < minNegBeta Then
                    minNegBeta = betaVal : minNegPath = pathStr : minNegP = pStr
                End If
            End If
            Dim arrowIdx As Integer = pathStr.IndexOf("→")
            If arrowIdx >= 0 Then
                Dim outcome As String = pathStr.Substring(arrowIdx + 1).Trim()
                If outcome <> "" AndAlso Not seenOutcomes.Contains(outcome) Then
                    seenOutcomes.Add(outcome)
                    Dim r2Val As Double = ParseNum(CellText(row, cR2))
                    If Not Double.IsNaN(r2Val) Then
                        r2s.Add(r2Val)
                        r2PartsZh.Add(outcome & " (*R*² = " & Fmt3(r2Val) & ")")
                        r2PartsEn.Add(outcome & " (*R*² = " & Fmt3(r2Val) & ")")
                    End If
                End If
            End If
            If Not Double.IsNaN(betaVal) AndAlso pStr <> "" AndAlso pStr <> "—" Then
                proseItems.Add(pathStr & " (β = " & Fmt3(betaVal) & ", *b* = " & Fmt3(bVal) & ", " & Ap.PEq(pStr) & ")")
            End If
        Next

        If nTotal > 0 Then
            If nNonSig = 0 Then
                AddTo(out, "ok", "全部 " & nTotal.ToString() & " 条检验路径均达到统计显著（*p* < 0.05）。", "All " & nTotal.ToString() & " tested structural paths were statistically significant (*p* < 0.05).")
            ElseIf nSig > 0 Then
                AddTo(out, "info", "共 " & nSig.ToString() & "/" & nTotal.ToString() & " 条路径显著（*p* < 0.05）；" & nNonSig.ToString() & " 条不显著：" & String.Join("、", nonSigNames.ToArray()) & "。", nSig.ToString() & " of " & nTotal.ToString() & " paths were significant (*p* < 0.05); non-significant: " & String.Join(", ", nonSigNames.ToArray()) & ".")
            Else
                AddTo(out, "warn", "全部 " & nTotal.ToString() & " 条结构路径均未达到统计显著（*p* ≥ 0.05）。", "None of the " & nTotal.ToString() & " structural paths reached significance (*p* ≥ 0.05).")
            End If
        End If

        If maxPosPath <> "" OrElse minNegPath <> "" Then
            Dim sZh As New List(Of String)(), sEn As New List(Of String)()
            If maxPosPath <> "" Then
                sZh.Add("最强正向路径为 " & maxPosPath & "（β = " & Fmt3(maxPosBeta) & "，" & Ap.PEq(maxPosP) & "）")
                sEn.Add("strongest positive path: " & maxPosPath & " (β = " & Fmt3(maxPosBeta) & ", " & Ap.PEq(maxPosP) & ")")
            End If
            If minNegPath <> "" Then
                sZh.Add("最强负向路径为 " & minNegPath & "（β = " & Fmt3(minNegBeta) & "，" & Ap.PEq(minNegP) & "）")
                sEn.Add("strongest negative path: " & minNegPath & " (β = " & Fmt3(minNegBeta) & ", " & Ap.PEq(minNegP) & ")")
            End If
            AddTo(out, "info", String.Join("；", sZh.ToArray()) & "。", "Notable effects — " & String.Join("; ", sEn.ToArray()) & ".")
        End If

        If r2s.Count > 0 Then
            Dim rLo As Double, rHi As Double
            Ap.Range(r2s, rLo, rHi)
            AddTo(out, "info", "内生变量方差解释率 *R*² 范围为 " & Fmt3(rLo) & If(rHi > rLo, "–" & Fmt3(rHi), "") & "：" & String.Join("、", r2PartsZh.ToArray()) & "。", "Endogenous *R*² ranged from " & Fmt3(rLo) & If(rHi > rLo, " to " & Fmt3(rHi), "") & ": " & String.Join(", ", r2PartsEn.ToArray()) & ".")
        End If

        If t.GetExtra("has_observed_iv") = "1" Then
            AddTo(out, "info", "模型含外生观测变量/二分类预测变量，建议优先解释非标准化系数 *b* 与 95% CI。", "Model includes observed/binary exogenous predictors; prioritize unstandardized *b* and its 95% CI over β.")
        End If

        If t.Prose.Count = 0 AndAlso proseItems.Count > 0 Then
            SetProseIfEmpty(t, "结构路径估计显示：" & String.Join("；", proseItems.ToArray()) & If(r2PartsZh.Count > 0, "；内生变量解释率为 " & String.Join("、", r2PartsZh.ToArray()), "") & "。", "Structural path estimates showed: " & String.Join("; ", proseItems.ToArray()) & If(r2PartsEn.Count > 0, "; endogenous variance explained: " & String.Join(", ", r2PartsEn.ToArray()), "") & ".")
        End If
    End Sub

    ' ---------------------------------------------------------------- 8. 效应分解 (effects)
    Private Shared Sub InterpEffects(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cRel As Integer = FindCol(t, "关系", "Path")
        Dim cKind As Integer = FindCol(t, "效应或对比", "Effect")
        Dim cB As Integer = FindCol(t, "b或Δb", "b")
        Dim cCi As Integer = FindCol(t, "BC 95% CI")
        Dim cPct As Integer = FindCol(t, "占总效应")

        Dim relOrder As New List(Of String)()
        Dim relRows As New Dictionary(Of String, List(Of String()))()
        For Each r As String() In t.Rows
            Dim rel As String = CellText(r, cRel)
            If Not relRows.ContainsKey(rel) Then
                relOrder.Add(rel)
                relRows(rel) = New List(Of String())()
            End If
            relRows(rel).Add(r)
        Next

        Dim proseZh As New List(Of String)(), proseEn As New List(Of String)()
        For Each rel As String In relOrder
            Dim rows As List(Of String()) = relRows(rel)
            Dim totRow() As String = Nothing, dirRow() As String = Nothing, indRow() As String = Nothing
            Dim specRows As New List(Of String())(), cmpRows As New List(Of String())()
            For Each r As String() In rows
                Dim k As String = CellText(r, cKind)
                If k.StartsWith("总效应") OrElse k.StartsWith("Total effect") Then
                    totRow = r
                ElseIf k = "直接效应" OrElse k = "Direct effect" Then
                    dirRow = r
                ElseIf k = "总间接效应" OrElse k = "Total indirect effect" Then
                    indRow = r
                ElseIf CellText(r, cPct) = "—" AndAlso (k.Contains(" − ") OrElse k.Contains(" - ")) Then
                    cmpRows.Add(r)
                Else
                    specRows.Add(r)
                End If
            Next

            Dim effIndRow() As String = indRow
            If effIndRow Is Nothing AndAlso specRows.Count = 1 Then effIndRow = specRows(0)
            If effIndRow Is Nothing AndAlso dirRow Is Nothing Then effIndRow = totRow

            Dim indB As Double = Double.NaN, indLo As Double = Double.NaN, indHi As Double = Double.NaN, indSig As Boolean = False
            Dim indPct As String = ""
            If effIndRow IsNot Nothing Then
                indB = ParseNum(CellText(effIndRow, cB))
                If ParseCI(CellText(effIndRow, cCi), indLo, indHi) Then indSig = ExcludesZero(indLo, indHi)
                indPct = CellText(effIndRow, cPct)
            End If

            Dim dirB As Double = Double.NaN, dirLo As Double = Double.NaN, dirHi As Double = Double.NaN, dirSig As Boolean = False
            If dirRow IsNot Nothing Then
                dirB = ParseNum(CellText(dirRow, cB))
                If ParseCI(CellText(dirRow, cCi), dirLo, dirHi) Then dirSig = ExcludesZero(dirLo, dirHi)
            End If

            Dim ciTxt As String = If(effIndRow IsNot Nothing, Ap.Minus(CellText(effIndRow, cCi)), "—")
            Dim pctZh As String = If(indPct <> "" AndAlso indPct <> "不适用" AndAlso indPct <> "—" AndAlso indPct <> "Not applicable", "（占总效应 " & indPct & "）", "")
            Dim pctEn As String = If(indPct <> "" AndAlso indPct <> "不适用" AndAlso indPct <> "—" AndAlso indPct <> "Not applicable", " (" & indPct & " of total)", "")

            If indSig Then
                If dirRow Is Nothing Then
                    AddTo(out, "ok", rel & "：仅存在显著间接效应（*b* = " & Fmt3(indB) & "，BC 95% CI " & ciTxt & "），无直接路径。", rel & ": significant indirect-only mediation (*b* = " & Fmt3(indB) & ", BC 95% CI " & ciTxt & "); no direct path specified.")
                ElseIf Not dirSig Then
                    AddTo(out, "ok", rel & "：总间接效应显著（*b* = " & Fmt3(indB) & "，BC 95% CI " & ciTxt & "）" & pctZh & "，直接效应不显著（*b* = " & Fmt3(dirB) & "），属完全中介。", rel & ": full mediation — significant indirect effect (*b* = " & Fmt3(indB) & ", BC 95% CI " & ciTxt & ")" & pctEn & " with non-significant direct effect (*b* = " & Fmt3(dirB) & ").")
                ElseIf indB * dirB >= 0 Then
                    AddTo(out, "ok", rel & "：总间接效应（*b* = " & Fmt3(indB) & "，BC 95% CI " & ciTxt & "）" & pctZh & "与直接效应（*b* = " & Fmt3(dirB) & "）均显著且同向，属同向部分中介。", rel & ": complementary partial mediation — both indirect (*b* = " & Fmt3(indB) & ", BC 95% CI " & ciTxt & ")" & pctEn & " and direct (*b* = " & Fmt3(dirB) & ") effects were significant in the same direction.")
                Else
                    AddTo(out, "warn", rel & "：间接效应（*b* = " & Fmt3(indB) & "，BC 95% CI " & ciTxt & "）与直接效应（*b* = " & Fmt3(dirB) & "）均显著但方向相反，存在遮掩/竞争性中介。", rel & ": competitive/suppression mediation — indirect (*b* = " & Fmt3(indB) & ", BC 95% CI " & ciTxt & ") and direct (*b* = " & Fmt3(dirB) & ") effects had opposite signs.")
                End If
            ElseIf effIndRow IsNot Nothing Then
                AddTo(out, "warn", rel & "：间接效应 BC 95% CI " & ciTxt & " 包含 0（*b* = " & Fmt3(indB) & "），总体间接效应不显著。", rel & ": total indirect effect non-significant (*b* = " & Fmt3(indB) & ", BC 95% CI " & ciTxt & " includes 0).")
            End If

            For Each cr As String() In cmpRows
                Dim clo As Double, chi As Double
                Dim db As Double = ParseNum(CellText(cr, cB))
                Dim cText As String = Ap.Minus(CellText(cr, cCi))
                If ParseCI(CellText(cr, cCi), clo, chi) Then
                    Dim cSig As Boolean = ExcludesZero(clo, chi)
                    AddTo(out, If(cSig, "ok", "info"), "路径比较（" & CellText(cr, cKind) & "）：Δ*b* = " & Fmt3(db) & "，BC 95% CI " & cText & "，" & If(cSig, "差异显著（区间不含 0）。", "两条路径强度差异不显著（区间含 0）。"), "Path contrast (" & CellText(cr, cKind) & "): Δ*b* = " & Fmt3(db) & ", BC 95% CI " & cText & " (" & If(cSig, "significant difference", "no significant difference") & ").")
                End If
            Next

            Dim totB As Double = If(totRow IsNot Nothing, ParseNum(CellText(totRow, cB)), Double.NaN)
            Dim totCi As String = If(totRow IsNot Nothing, Ap.Minus(CellText(totRow, cCi)), "—")
            proseZh.Add(rel & " 的总效应为 *b* = " & Fmt3(totB) & "（BC 95% CI " & totCi & "），总间接效应为 *b* = " & Fmt3(indB) & "（BC 95% CI " & ciTxt & "）" & pctZh)
            proseEn.Add("for " & rel & ", total effect *b* = " & Fmt3(totB) & " (BC 95% CI " & totCi & ") and indirect effect *b* = " & Fmt3(indB) & " (BC 95% CI " & ciTxt & ")" & pctEn)
        Next

        If t.Prose.Count = 0 AndAlso proseZh.Count > 0 Then
            SetProseIfEmpty(t, "Bootstrap 效应分解结果显示：" & String.Join("；", proseZh.ToArray()) & "。", "Bootstrap mediation analyses showed that " & String.Join("; ", proseEn.ToArray()) & ".")
        End If
    End Sub

    ' ---------------------------------------------------------------- 9. 调节效应 (moderation)
    Private Shared Sub InterpModeration(ByVal t As RTable, ByVal out As List(Of String()))
        Dim colType As Integer = FindCol(t, "结果类型")
        Dim cPath As Integer = FindCol(t, "路径或调节值")
        Dim cB As Integer = FindCol(t, "b")
        Dim cBeta As Integer = FindCol(t, "β")
        Dim cCi As Integer = FindCol(t, "Wald 95% CI")
        Dim cP As Integer = FindCol(t, "p")
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim xName As String = "", targetName As String = "", wName As String = ""
        Dim pathRows As New List(Of String())(), slopeRows As New List(Of String())()

        For Each row As String() In t.Rows
            Dim tp As String = CellText(row, colType)
            If tp = "结构路径" OrElse tp = "Structural paths" Then
                pathRows.Add(row)
            Else
                slopeRows.Add(row)
                If xName = "" AndAlso tp.Contains("→") Then
                    Dim aIdx As Integer = tp.IndexOf("→")
                    xName = tp.Substring(0, aIdx).Trim()
                    Dim rest As String = tp.Substring(aIdx + 1).Trim()
                    rest = rest.Replace("简单斜率", "").Replace("simple slopes", "").Trim()
                    targetName = rest
                End If
                If wName = "" Then
                    Dim cond As String = RowLabel(CellText(row, cPath), False)
                    Dim eqIdx As Integer = cond.IndexOf("=")
                    If eqIdx > 0 Then
                        Dim lhs As String = cond.Substring(0, eqIdx).Trim()
                        If lhs.StartsWith("低") OrElse lhs.StartsWith("中") OrElse lhs.StartsWith("高") Then lhs = lhs.Substring(1).Trim()
                        wName = lhs
                    End If
                End If
            End If
        Next

        ' 查找交互项路径：指向 targetName 且起点既不是 xName 也不是 wName
        Dim intRow() As String = Nothing
        For Each row As String() In pathRows
            Dim pr As String = CellText(row, cPath)
            Dim aIdx As Integer = pr.IndexOf("→")
            If aIdx < 0 Then Continue For
            Dim iv As String = pr.Substring(0, aIdx).Trim()
            Dim dv As String = pr.Substring(aIdx + 1).Trim()
            If targetName <> "" AndAlso dv = targetName AndAlso iv <> xName AndAlso iv <> wName Then
                intRow = row
                Exit For
            End If
        Next
        If intRow Is Nothing Then
            For Each row As String() In pathRows
                Dim pr As String = CellText(row, cPath)
                If pr.Contains("x") OrElse pr.Contains("×") OrElse pr.Contains("*") OrElse pr.IndexOf("int", StringComparison.OrdinalIgnoreCase) >= 0 Then
                    intRow = row
                    Exit For
                End If
            Next
        End If

        Dim properBeta As String = t.GetExtra("proper_beta")
        Dim intSig As Boolean = False, intB As Double = Double.NaN, intBeta As Double = Double.NaN
        Dim intPStr As String = "", intCiStr As String = ""
        If intRow IsNot Nothing Then
            intB = ParseNum(CellText(intRow, cB))
            intBeta = ParseNum(CellText(intRow, cBeta))
            intPStr = CellText(intRow, cP)
            intCiStr = Ap.Minus(CellText(intRow, cCi))
            ParsePVal(intPStr, intSig)
            Dim dirZh As String = If(intB >= 0, "正向调节", "负向调节")
            Dim dirEn As String = If(intB >= 0, "positive moderation", "negative moderation")
            Dim bTag As String = If(properBeta <> "", "，恰当标准化 β<sub>proper</sub> = " & Ap.Minus(properBeta) & "（表内 β = " & Fmt3(intBeta) & " 为乘积构念默认标准化值）", "，β = " & Fmt3(intBeta))
            Dim bTagEn As String = If(properBeta <> "", ", β<sub>proper</sub> = " & Ap.Minus(properBeta) & " (default β = " & Fmt3(intBeta) & ")", ", β = " & Fmt3(intBeta))
            If intSig Then
                AddTo(out, "ok", "交互项 " & CellText(intRow, cPath) & " 显著（*b* = " & Fmt3(intB) & "，95% CI " & intCiStr & "，" & Ap.PEq(intPStr) & bTag & "），表明存在" & dirZh & "效应。", "Significant interaction " & CellText(intRow, cPath) & " (*b* = " & Fmt3(intB) & ", 95% CI " & intCiStr & ", " & Ap.PEq(intPStr) & bTagEn & "), indicating " & dirEn & ".")
            Else
                AddTo(out, "warn", "交互项 " & CellText(intRow, cPath) & " 不显著（*b* = " & Fmt3(intB) & "，95% CI " & intCiStr & "，" & Ap.PEq(intPStr) & bTag & "），调节假设未获支持。", "Interaction " & CellText(intRow, cPath) & " was non-significant (*b* = " & Fmt3(intB) & ", 95% CI " & intCiStr & ", " & Ap.PEq(intPStr) & bTagEn & ").")
            End If
        ElseIf properBeta <> "" Then
            AddTo(out, "info", "潜变量交互项恰当标准化系数 β<sub>proper</sub> = " & Ap.Minus(properBeta) & "。", "Proper standardized interaction coefficient β<sub>proper</sub> = " & Ap.Minus(properBeta) & ".")
        End If

        If slopeRows.Count > 0 Then
            Dim sPartsZh As New List(Of String)(), sPartsEn As New List(Of String)()
            Dim sigCnt As Integer = 0
            For Each sr As String() In slopeRows
                Dim condZh As String = RowLabel(CellText(sr, cPath), False)
                Dim condEn As String = RowLabel(CellText(sr, cPath), True)
                Dim sbVal As Double = ParseNum(CellText(sr, cB))
                Dim spStr As String = CellText(sr, cP)
                Dim sSig As Boolean = False
                ParsePVal(spStr, sSig)
                If sSig Then sigCnt += 1
                sPartsZh.Add(condZh & " 时 *b* = " & Fmt3(sbVal) & "（" & Ap.PEq(spStr) & "）")
                sPartsEn.Add(condEn & ": *b* = " & Fmt3(sbVal) & " (" & Ap.PEq(spStr) & ")")
            Next
            AddTo(out, If(sigCnt > 0, "info", "warn"), "简单斜率检验（" & sigCnt.ToString() & "/" & slopeRows.Count.ToString() & " 档显著）：" & String.Join("；", sPartsZh.ToArray()) & "。", "Simple slopes (" & sigCnt.ToString() & "/" & slopeRows.Count.ToString() & " significant): " & String.Join("; ", sPartsEn.ToArray()) & ".")
        End If

        For Each pn As String In t.PaperNotes
            Dim zhNote As String = Tx.Zh(pn)
            If zhNote.Contains("Johnson–Neyman") Then
                AddTo(out, "info", "Johnson–Neyman 显著区间：" & zhNote, "Johnson–Neyman regions: " & Tx.En(pn))
                Exit For
            End If
        Next

        If t.Prose.Count = 0 AndAlso intRow IsNot Nothing Then
            Dim pTagZh As String = If(properBeta <> "", "，β<sub>proper</sub> = " & Ap.Minus(properBeta), "")
            Dim pTagEn As String = If(properBeta <> "", ", β<sub>proper</sub> = " & Ap.Minus(properBeta), "")
            SetProseIfEmpty(t, "调节检验表明，交互项 " & CellText(intRow, cPath) & " 的路径系数为 *b* = " & Fmt3(intB) & "（95% CI " & intCiStr & "，" & Ap.PEq(intPStr) & pTagZh & "）。", "Moderation analysis showed that the interaction path " & CellText(intRow, cPath) & " was *b* = " & Fmt3(intB) & " (95% CI " & intCiStr & ", " & Ap.PEq(intPStr) & pTagEn & ").")
        End If
    End Sub

    ' ---------------------------------------------------------------- 10. 条件间接效应 (conditional)
    Private Shared Sub InterpConditional(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cPath As Integer = FindCol(t, "间接路径")
        Dim cItem As Integer = FindCol(t, "检验项目")
        Dim cB As Integer = FindCol(t, "b或指数")
        Dim cCi As Integer = FindCol(t, "BC 95% CI")

        Dim condSig As Integer = 0, condTot As Integer = 0
        Dim condPartsZh As New List(Of String)(), condPartsEn As New List(Of String)()
        Dim diffRow() As String = Nothing, idxRow() As String = Nothing
        Dim pathName As String = If(t.Rows.Count > 0, CellText(t.Rows(0), cPath), "")

        For Each row As String() In t.Rows
            Dim itemKey As String = CellText(row, cItem)
            Dim itemZh As String = RowLabel(itemKey, False)
            Dim itemEn As String = RowLabel(itemKey, True)
            If itemZh.Contains("调节中介指数") OrElse itemEn.IndexOf("Index of moderated mediation", StringComparison.OrdinalIgnoreCase) >= 0 Then
                idxRow = row
            ElseIf itemZh.Contains(" − ") OrElse itemZh.Contains(" - ") Then
                diffRow = row
            Else
                condTot += 1
                Dim b As Double = ParseNum(CellText(row, cB))
                Dim lo As Double, hi As Double
                Dim sig As Boolean = ParseCI(CellText(row, cCi), lo, hi) AndAlso ExcludesZero(lo, hi)
                If sig Then condSig += 1
                Dim ciStr As String = Ap.Minus(CellText(row, cCi))
                condPartsZh.Add(itemZh & " 时 *b* = " & Fmt3(b) & "（BC 95% CI " & ciStr & "）")
                condPartsEn.Add(itemEn & ": *b* = " & Fmt3(b) & " (BC 95% CI " & ciStr & ")")
            End If
        Next

        If condTot > 0 Then
            AddTo(out, If(condSig > 0, "info", "warn"), "路径 " & pathName & " 在 " & condSig.ToString() & "/" & condTot.ToString() & " 个调节水平上条件间接效应显著：" & String.Join("；", condPartsZh.ToArray()) & "。", "Conditional indirect effects for " & pathName & " were significant at " & condSig.ToString() & " of " & condTot.ToString() & " levels: " & String.Join("; ", condPartsEn.ToArray()) & ".")
        End If

        If diffRow IsNot Nothing Then
            Dim db As Double = ParseNum(CellText(diffRow, cB))
            Dim lo As Double, hi As Double
            Dim dSig As Boolean = ParseCI(CellText(diffRow, cCi), lo, hi) AndAlso ExcludesZero(lo, hi)
            Dim dCi As String = Ap.Minus(CellText(diffRow, cCi))
            AddTo(out, If(dSig, "ok", "info"), "高低调节水平间接效应差值：" & RowLabel(CellText(diffRow, cItem), False) & " = " & Fmt3(db) & "，BC 95% CI " & dCi & "（" & If(dSig, "不含 0，高低差异显著", "包含 0") & "）。", "High–low conditional indirect contrast: Δ*b* = " & Fmt3(db) & ", BC 95% CI " & dCi & " (" & If(dSig, "excludes 0", "includes 0") & ").")
        End If

        Dim idxTextZh As String = "", idxTextEn As String = ""
        If idxRow IsNot Nothing Then
            Dim ib As Double = ParseNum(CellText(idxRow, cB))
            Dim lo As Double, hi As Double
            Dim iSig As Boolean = ParseCI(CellText(idxRow, cCi), lo, hi) AndAlso ExcludesZero(lo, hi)
            Dim iCi As String = Ap.Minus(CellText(idxRow, cCi))
            idxTextZh = "调节中介指数为 " & Fmt3(ib) & "（BC 95% CI " & iCi & "）"
            idxTextEn = "index of moderated mediation = " & Fmt3(ib) & " (BC 95% CI " & iCi & ")"
            AddTo(out, If(iSig, "ok", "warn"), "调节中介指数（IMM）= " & Fmt3(ib) & "，BC 95% CI " & iCi & "，" & If(iSig, "区间不含 0，有调节的中介效应成立。", "区间包含 0，线性调节中介指数不显著。"), "Index of moderated mediation = " & Fmt3(ib) & ", BC 95% CI " & iCi & " (" & If(iSig, "significant moderated mediation", "includes 0; not significant") & ").")
        End If

        If t.Prose.Count = 0 AndAlso condPartsZh.Count > 0 Then
            SetProseIfEmpty(t, "条件间接效应检验显示，" & String.Join("，", condPartsZh.ToArray()) & If(idxTextZh <> "", "；" & idxTextZh, "") & "。", "Conditional indirect effect tests for " & pathName & " showed " & String.Join(", ", condPartsEn.ToArray()) & If(idxTextEn <> "", "; " & idxTextEn, "") & ".")
        End If
    End Sub

    ' ---------------------------------------------------------------- 11. 共同方法偏差 (cmv)
    Private Shared Sub InterpCmv(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cModel As Integer = FindCol(t, "模型", "Model")
        Dim cCfi As Integer = FindCol(t, "CFI")
        Dim cRmsea As Integer = FindCol(t, "RMSEA")
        Dim cCmp As Integer = FindCol(t, "比较")
        Dim cDChi As Integer = FindCol(t, "Δχ² (Δdf)")
        Dim cP As Integer = FindCol(t, "p")
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim isMarker As Boolean = False, isUlmc As Boolean = False, isSingle As Boolean = False
        For Each r As String() In t.Rows
            Dim mEn As String = RowLabel(CellText(r, cModel), True)
            Dim mZh As String = RowLabel(CellText(r, cModel), False)
            If mEn.Contains("Method-C") OrElse mZh.Contains("Method-C") Then isMarker = True
            If mEn.Contains("Equal method") OrElse mZh.Contains("载荷相等") Then isUlmc = True
            If mEn.Contains("Single factor") OrElse mZh.Contains("单因子") Then isSingle = True
        Next

        If isMarker Then
            Dim pCStr As String = "", pUStr As String = "", pRStr As String = ""
            Dim sigC As Boolean = False, sigU As Boolean = False, sigR As Boolean = False
            Dim dcC As String = "", dcU As String = "", dcR As String = ""
            For Each r As String() In t.Rows
                Dim cmp As String = CellText(r, cCmp)
                Dim ps As String = CellText(r, cP)
                Dim dcs As String = CellText(r, cDChi)
                If cmp.Contains("Baseline") AndAlso cmp.Contains("Method-C") Then
                    pCStr = ps : dcC = dcs : ParsePVal(ps, sigC)
                ElseIf cmp.Contains("Method-C") AndAlso cmp.Contains("Method-U") Then
                    pUStr = ps : dcU = dcs : ParsePVal(ps, sigU)
                ElseIf cmp.Contains("Method-R") Then
                    pRStr = ps : dcR = dcs : ParsePVal(ps, sigR)
                End If
            Next
            If pCStr <> "" Then
                AddTo(out, If(sigC, "info", "ok"), "Baseline 对 Method-C：Δχ²(Δ*df*) = " & dcC & "，" & Ap.PEq(pCStr) & "，" & If(sigC, "提示存在可检出的共同方法方差。", "未检出显著共同方法方差。"), "Baseline vs. Method-C: Δχ²(Δ*df*) = " & dcC & ", " & Ap.PEq(pCStr) & " (" & If(sigC, "presence of shared method variance", "no significant shared method variance") & ").")
            End If
            If pUStr <> "" Then
                AddTo(out, "info", "Method-C 对 Method-U：Δχ²(Δ*df*) = " & dcU & "，" & Ap.PEq(pUStr) & "，支持保留" & If(sigU, "非等值方法载荷模型（Method-U）。", "等值方法载荷模型（Method-C）。"), "Method-C vs. Method-U: Δχ²(Δ*df*) = " & dcU & ", " & Ap.PEq(pUStr) & ", favoring " & If(sigU, "Method-U (unequal method loadings).", "Method-C (equal method loadings)."))
            End If
            If pRStr <> "" Then
                AddTo(out, If(sigR, "warn", "ok"), "Method-R 检验（固定实质因子相关）：Δχ²(Δ*df*) = " & dcR & "，" & Ap.PEq(pRStr) & "，" & If(sigR, "说明共同方法偏差显著影响了构念间相关估计，解释需谨慎。", "说明共同方法偏差未实质性扭曲构念间相关（无严重偏差）。"), "Method-R test: Δχ²(Δ*df*) = " & dcR & ", " & Ap.PEq(pRStr) & " (" & If(sigR, "CMV significantly biases substantive factor correlations", "substantive factor correlations are not significantly biased by CMV") & ").")
            End If
            SetProseIfEmpty(t, "CFA 标记技术检验显示：Baseline 与 Method-C 比较 Δχ²(Δ*df*) = " & dcC & "（" & Ap.PEq(pCStr) & "），Method-C 与 Method-U 比较 Δχ²(Δ*df*) = " & dcU & "（" & Ap.PEq(pUStr) & "），Method-R 检验 Δχ²(Δ*df*) = " & dcR & "（" & Ap.PEq(pRStr) & "）。", "CFA marker tests yielded Δχ²(Δ*df*) = " & dcC & " (" & Ap.PEq(pCStr) & ") for Baseline vs. Method-C, Δχ²(Δ*df*) = " & dcU & " (" & Ap.PEq(pUStr) & ") for Method-C vs. Method-U, and Δχ²(Δ*df*) = " & dcR & " (" & Ap.PEq(pRStr) & ") for Method-R.")
        ElseIf isUlmc AndAlso t.Rows.Count >= 2 Then
            Dim cfi0 As Double = ParseNum(CellText(t.Rows(0), cCfi))
            Dim cfiLast As Double = ParseNum(CellText(t.Rows(t.Rows.Count - 1), cCfi))
            Dim rm0 As Double = ParseNum(CellText(t.Rows(0), cRmsea))
            Dim rmLast As Double = ParseNum(CellText(t.Rows(t.Rows.Count - 1), cRmsea))
            Dim dCfi As Double = cfiLast - cfi0
            Dim ok As Boolean = (Math.Abs(dCfi) <= 0.02 AndAlso (Double.IsNaN(rm0) OrElse Double.IsNaN(rmLast) OrElse Math.Abs(rmLast - rm0) <= 0.02))
            AddTo(out, If(ok, "ok", "warn"), "潜变量方法因子（ULMC）加入前后，ΔCFI = " & Fmt3(dCfi) & "，ΔRMSEA = " & Fmt3(rmLast - rm0) & "，" & If(ok, "拟合改善幅度有限，提示不存在严重共同方法偏差。", "拟合改善较明显，需关注共同方法偏差影响。"), "Adding the ULMC method factor yielded ΔCFI = " & Fmt3(dCfi) & " and ΔRMSEA = " & Fmt3(rmLast - rm0) & " (" & If(ok, "no severe CMV indicated", "noticeable fit change; check CMV impact") & ").")
            SetProseIfEmpty(t, "采用未测量潜方法因子（ULMC）检验共同方法偏差，模型加入方法因子前后 ΔCFI = " & Fmt3(dCfi) & "，ΔRMSEA = " & Fmt3(rmLast - rm0) & "。", "Under the ULMC test, adding a common method factor resulted in ΔCFI = " & Fmt3(dCfi) & " and ΔRMSEA = " & Fmt3(rmLast - rm0) & ".")
        ElseIf isSingle AndAlso t.Rows.Count >= 2 Then
            Dim cfi0 As Double = ParseNum(CellText(t.Rows(0), cCfi))
            Dim cfi1 As Double = ParseNum(CellText(t.Rows(1), cCfi))
            Dim rm1 As Double = ParseNum(CellText(t.Rows(1), cRmsea))
            Dim poorSingle As Boolean = (cfi1 < 0.90 AndAlso (Double.IsNaN(rm1) OrElse rm1 > 0.08))
            AddTo(out, If(poorSingle, "ok", "warn"), "单因子验证性模型拟合明显恶化（CFI = " & Fmt3(cfi1) & "，RMSEA = " & Fmt3(rm1) & "，相对原测量模型 ΔCFI = " & Fmt3(cfi1 - cfi0) & "），" & If(poorSingle, "单因子无法解释全部共变，未见严重共同方法偏差。", "单因子拟合尚可，建议改用 CFA 标记技术进一步检验。"), "The single-factor CFA fit poorly (CFI = " & Fmt3(cfi1) & ", RMSEA = " & Fmt3(rm1) & ", ΔCFI = " & Fmt3(cfi1 - cfi0) & "), indicating " & If(poorSingle, "no severe single-factor CMV.", "potential CMV concern.") )
            SetProseIfEmpty(t, "单因子模型比较显示，单因子模型拟合极差（CFI = " & Fmt3(cfi1) & "，RMSEA = " & Fmt3(rm1) & "），明显劣于理论测量模型（CFI = " & Fmt3(cfi0) & "）。", "A single-factor CFA fit substantially worse (CFI = " & Fmt3(cfi1) & ", RMSEA = " & Fmt3(rm1) & ") than the hypothesized measurement model (CFI = " & Fmt3(cfi0) & ").")
        End If
    End Sub

    ' ---------------------------------------------------------------- 12. 测量等值 (invariance)
    Private Shared Sub InterpInvariance(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cModel As Integer = FindCol(t, "模型", "Model")
        Dim cCfi As Integer = FindCol(t, "CFI")
        Dim cRmsea As Integer = FindCol(t, "RMSEA")
        Dim cRmseaG As Integer = FindCol(t, "RMSEA (×√G)")
        Dim cDChi As Integer = FindCol(t, "Δχ² (Δdf)")
        Dim cP As Integer = FindCol(t, "p")
        Dim cDCfi As Integer = FindCol(t, "ΔCFI")
        Dim cDRmsea As Integer = FindCol(t, "ΔRMSEA")
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim cfgIdx As Integer = -1
        For i As Integer = 0 To t.Rows.Count - 1
            Dim mEn As String = RowLabel(CellText(t.Rows(i), cModel), True)
            Dim mZh As String = RowLabel(CellText(t.Rows(i), cModel), False)
            If mEn.IndexOf("Configural", StringComparison.OrdinalIgnoreCase) >= 0 OrElse mZh.Contains("构型") Then
                cfgIdx = i : Exit For
            End If
        Next
        If cfgIdx < 0 Then cfgIdx = 0

        Dim cfgCfi As Double = ParseNum(CellText(t.Rows(cfgIdx), cCfi))
        Dim cfgRmsea As Double = ParseNum(CellText(t.Rows(cfgIdx), cRmsea))
        Dim cfgOk As Boolean = (Not Double.IsNaN(cfgCfi) AndAlso cfgCfi >= 0.90)
        AddTo(out, If(cfgOk, "ok", "warn"), "构型等值基准模型 CFI = " & Fmt3(cfgCfi) & "，RMSEA = " & Fmt3(cfgRmsea) & "，" & If(cfgOk, "跨组因子结构形态成立。", "构型模型拟合偏低。"), "Configural invariance baseline: CFI = " & Fmt3(cfgCfi) & ", RMSEA = " & Fmt3(cfgRmsea) & " (" & If(cfgOk, "baseline structure supported", "suboptimal baseline fit") & ").")

        Dim highestZh As String = "构型等值", highestEn As String = "configural invariance"
        Dim failedLevels As New List(Of String)()
        Dim stepProseZh As New List(Of String)(), stepProseEn As New List(Of String)()
        For i As Integer = cfgIdx + 1 To t.Rows.Count - 1
            Dim mZh As String = RowLabel(CellText(t.Rows(i), cModel), False)
            Dim mEn As String = RowLabel(CellText(t.Rows(i), cModel), True)
            Dim dcfi As Double = ParseNum(CellText(t.Rows(i), cDCfi))
            Dim drm As Double = ParseNum(CellText(t.Rows(i), cDRmsea))
            Dim dcStr As String = CellText(t.Rows(i), cDChi)
            Dim pStr As String = CellText(t.Rows(i), cP)
            If Not Double.IsNaN(dcfi) Then
                Dim passCfi As Boolean = (Math.Abs(dcfi) <= 0.010)
                If passCfi Then
                    highestZh = mZh : highestEn = mEn.ToLowerInvariant()
                Else
                    failedLevels.Add(mZh & "(ΔCFI=" & Fmt3(dcfi) & ")")
                End If
                stepProseZh.Add(mZh & "（Δχ² = " & dcStr & "，" & Ap.PEq(pStr) & "，ΔCFI = " & Fmt3(dcfi) & If(Double.IsNaN(drm), "", "，ΔRMSEA = " & Fmt3(drm)) & "）")
                stepProseEn.Add(mEn & " (Δχ² = " & dcStr & ", " & Ap.PEq(pStr) & ", ΔCFI = " & Fmt3(dcfi) & If(Double.IsNaN(drm), "", ", ΔRMSEA = " & Fmt3(drm)) & ")")
            End If
        Next

        If t.Rows.Count > cfgIdx + 1 Then
            If failedLevels.Count = 0 Then
                AddTo(out, "ok", "按 |ΔCFI| ≤ 0.010 标准，等值检验逐级通过至「" & highestZh & "」。", "Using |ΔCFI| ≤ 0.010, invariance held up through " & highestEn & ".")
            Else
                AddTo(out, "warn", "按 |ΔCFI| ≤ 0.010 标准，已达成「" & highestZh & "」；未通过层级：" & String.Join("、", failedLevels.ToArray()) & "。", "Using |ΔCFI| ≤ 0.010, invariance reached " & highestEn & "; failed step(s): " & String.Join(", ", failedLevels.ToArray()) & ".")
            End If
        End If

        Dim extraRmseaG As String = t.GetExtra("rmsea_g")
        Dim extraDRmsea As String = t.GetExtra("drmsea")
        If cRmseaG >= 0 OrElse extraRmseaG <> "" Then
            AddTo(out, "info", "RMSEA 口径说明：AMOS 按多组平均输出 RMSEA，Mplus 等价多组总体口径为 RMSEA × √G" & If(extraRmseaG <> "", "（" & Ap.Minus(extraRmseaG) & "）", "") & If(extraDRmsea <> "", "；ΔRMSEA：" & Ap.Minus(extraDRmsea), "") & "。", "RMSEA conventions: AMOS reports unscaled multi-group RMSEA, whereas Mplus scales by √G" & If(extraRmseaG <> "", " (" & Ap.Minus(extraRmseaG) & ")", "") & If(extraDRmsea <> "", "; ΔRMSEA: " & Ap.Minus(extraDRmsea), "") & ".")
        End If

        If t.Prose.Count = 0 Then
            SetProseIfEmpty(t, "测量等值检验中，构型等值模型拟合为 CFI = " & Fmt3(cfgCfi) & "、RMSEA = " & Fmt3(cfgRmsea) & If(stepProseZh.Count > 0, "；随后依次检验：" & String.Join("，", stepProseZh.ToArray()), "") & "，按 |ΔCFI| ≤ 0.010 标准支持「" & highestZh & "」。", "In measurement invariance testing, the configural model showed CFI = " & Fmt3(cfgCfi) & " and RMSEA = " & Fmt3(cfgRmsea) & If(stepProseEn.Count > 0, "; subsequent steps yielded " & String.Join(", ", stepProseEn.ToArray()), "") & ", supporting " & highestEn & " (|ΔCFI| ≤ 0.010).")
        End If
    End Sub

    ' ---------------------------------------------------------------- 13. 潜均值差异 (latentmeans)
    Private Shared Sub InterpLatentMeans(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cCon As Integer = FindCol(t, "构念")
        Dim cCmp As Integer = FindCol(t, "组别对比")
        Dim cDiff As Integer = FindCol(t, "差值")
        Dim cCi As Integer = FindCol(t, "Wald 95% CI")
        Dim cP As Integer = FindCol(t, "p")
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim sigListZh As New List(Of String)(), sigListEn As New List(Of String)()
        Dim nTot As Integer = 0
        For Each r As String() In t.Rows
            nTot += 1
            Dim con As String = CellText(r, cCon)
            Dim cmp As String = CellText(r, cCmp)
            Dim d As Double = ParseNum(CellText(r, cDiff))
            Dim ps As String = CellText(r, cP)
            Dim ci As String = Ap.Minus(CellText(r, cCi))
            Dim sig As Boolean = False
            ParsePVal(ps, sig)
            If sig Then
                sigListZh.Add(con & "（" & cmp & "，Δ*M* = " & Fmt3(d) & "，" & Ap.PEq(ps) & "）")
                sigListEn.Add(con & " (" & cmp & ", Δ*M* = " & Fmt3(d) & ", 95% CI " & ci & ", " & Ap.PEq(ps) & ")")
            End If
        Next

        If sigListZh.Count > 0 Then
            AddTo(out, "info", "潜均值差异检验中，有 " & sigListZh.Count.ToString() & "/" & nTot.ToString() & " 项对比显著：" & String.Join("；", sigListZh.ToArray()) & "。", sigListEn.Count.ToString() & " of " & nTot.ToString() & " latent mean comparisons were significant: " & String.Join("; ", sigListEn.ToArray()) & ".")
        Else
            AddTo(out, "ok", "全部 " & nTot.ToString() & " 项潜均值组间对比均未达到统计显著（*p* ≥ 0.05）。", "None of the " & nTot.ToString() & " latent mean comparisons reached statistical significance (*p* ≥ 0.05).")
        End If

        Dim basis As String = t.GetExtra("means_basis")
        If basis <> "" Then
            AddTo(out, "info", "潜均值比较基准：" & basis & "。", "Latent means basis: " & basis & ".")
        End If

        If t.Prose.Count = 0 Then
            If sigListZh.Count > 0 Then
                SetProseIfEmpty(t, "以参照组潜均值为 0，组间潜均值比较显示显著差异：" & String.Join("；", sigListZh.ToArray()) & "。", "With the reference group's latent means fixed to zero, significant differences emerged for " & String.Join("; ", sigListEn.ToArray()) & ".")
            Else
                SetProseIfEmpty(t, "以参照组潜均值为 0，各构念潜均值在组间均未见显著差异（*p* ≥ 0.05）。", "With reference latent means fixed to zero, no significant latent mean differences were found across groups (*p* ≥ 0.05).")
            End If
        End If
    End Sub

    ' ---------------------------------------------------------------- 14a. 多组路径比较 (multigroup)
    Private Shared Sub InterpMultigroup(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cPath As Integer = FindCol(t, "结构路径", "路径")
        Dim cDiff As Integer = FindCol(t, "组间差异")
        Dim cP As Integer = FindCol(t, "p")
        If cP >= 0 AndAlso t.Cols(cP).Trim() <> "p" Then cP = -1

        Dim oDc As String = t.GetExtra("overall_dchi2")
        Dim oDf As String = t.GetExtra("overall_df")
        Dim oP As String = t.GetExtra("overall_p")
        If oDc <> "" AndAlso oDf <> "" AndAlso oP <> "" Then
            Dim oSig As Boolean = False
            ParsePVal(oP, oSig)
            AddTo(out, If(oSig, "ok", "info"), "全部结构路径跨组相等的整体检验：Δχ²(" & oDf & ") = " & Ap.Minus(oDc) & "，" & Ap.PEq(oP) & "，" & If(oSig, "表明组别对整体结构路径具有调节作用。", "整体路径结构未呈现显著跨组差异。"), "Omnibus test constraining all structural paths equal across groups: Δχ²(" & oDf & ") = " & Ap.Minus(oDc) & ", " & Ap.PEq(oP) & " (" & If(oSig, "significant overall group moderation", "overall structural equivalence") & ").")
        End If

        Dim sigPathsZh As New List(Of String)(), sigPathsEn As New List(Of String)()
        For Each r As String() In t.Rows
            Dim ps As String = CellText(r, cP)
            Dim sig As Boolean = False
            ParsePVal(ps, sig)
            If sig Then
                Dim pName As String = CellText(r, cPath)
                Dim dc As String = CellText(r, cDiff)
                sigPathsZh.Add(pName & "（Δχ² = " & dc & "，" & Ap.PEq(ps) & "）")
                sigPathsEn.Add(pName & " (Δχ² = " & dc & ", " & Ap.PEq(ps) & ")")
            End If
        Next
        If sigPathsZh.Count > 0 Then
            AddTo(out, "ok", "逐路径检验中，" & sigPathsZh.Count.ToString() & "/" & t.Rows.Count.ToString() & " 条路径存在显著跨组差异：" & String.Join("；", sigPathsZh.ToArray()) & "。", sigPathsEn.Count.ToString() & " of " & t.Rows.Count.ToString() & " structural paths differed significantly across groups: " & String.Join("; ", sigPathsEn.ToArray()) & ".")
        Else
            AddTo(out, "info", "全部 " & t.Rows.Count.ToString() & " 条结构路径的跨组单路径等值检验均未达显著（*p* ≥ 0.05）。", "None of the " & t.Rows.Count.ToString() & " single-path equality tests differed significantly across groups (*p* ≥ 0.05).")
        End If

        If t.Prose.Count = 0 Then
            Dim ombZh As String = If(oDc <> "", "整体路径等值检验结果为 Δχ²(" & oDf & ") = " & Ap.Minus(oDc) & "（" & Ap.PEq(oP) & "）；", "")
            Dim ombEn As String = If(oDc <> "", "The omnibus structural-invariance test yielded Δχ²(" & oDf & ") = " & Ap.Minus(oDc) & " (" & Ap.PEq(oP) & "); ", "")
            If sigPathsZh.Count > 0 Then
                SetProseIfEmpty(t, ombZh & "逐路径比较显示，" & String.Join("；", sigPathsZh.ToArray()) & " 在不同组间存在显著差异。", ombEn & "path-by-path tests indicated significant group differences for " & String.Join("; ", sigPathsEn.ToArray()) & ".")
            Else
                SetProseIfEmpty(t, ombZh & "各条结构路径在组间均未见显著差异（*p* ≥ 0.05）。", ombEn & "no individual structural path differed significantly across groups (*p* ≥ 0.05).")
            End If
        End If
    End Sub

    ' ---------------------------------------------------------------- 14b. 多组两两路径比较 (multigroup_pairs)
    Private Shared Sub InterpMultigroupPairs(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cPath As Integer = FindCol(t, "路径")
        Dim cCmp As Integer = FindCol(t, "组别对比")
        Dim cDb As Integer = FindCol(t, "Δb")
        Dim cWaldP As Integer = FindCol(t, "Wald p")
        Dim cLrtP As Integer = FindCol(t, "LRT p")

        Dim sigListZh As New List(Of String)(), sigListEn As New List(Of String)()
        For Each r As String() In t.Rows
            Dim pCol As Integer = If(cLrtP >= 0, cLrtP, cWaldP)
            Dim ps As String = CellText(r, pCol)
            Dim sig As Boolean = False
            ParsePVal(ps, sig)
            If sig Then
                Dim pName As String = CellText(r, cPath)
                Dim cmp As String = CellText(r, cCmp)
                Dim db As Double = ParseNum(CellText(r, cDb))
                sigListZh.Add(pName & " [" & cmp & "]（Δ*b* = " & Fmt3(db) & "，" & Ap.PEq(ps) & "）")
                sigListEn.Add(pName & " [" & cmp & "] (Δ*b* = " & Fmt3(db) & ", " & Ap.PEq(ps) & ")")
            End If
        Next
        If sigListZh.Count > 0 Then
            AddTo(out, "ok", "两两群体比较中，共 " & sigListZh.Count.ToString() & "/" & t.Rows.Count.ToString() & " 项差异显著（未校正多重比较）：" & String.Join("；", sigListZh.ToArray()) & "。", sigListEn.Count.ToString() & " of " & t.Rows.Count.ToString() & " pairwise group contrasts were significant (unadjusted): " & String.Join("; ", sigListEn.ToArray()) & ".")
        Else
            AddTo(out, "info", "全部 " & t.Rows.Count.ToString() & " 项两两群体路径比较均未达到显著（*p* ≥ 0.05）。", "None of the " & t.Rows.Count.ToString() & " pairwise group comparisons reached significance (*p* ≥ 0.05).")
        End If
        If t.Prose.Count = 0 Then
            If sigListZh.Count > 0 Then
                SetProseIfEmpty(t, "多组两两路径差异检验（未校正多重比较）发现以下显著差异：" & String.Join("；", sigListZh.ToArray()) & "。", "Pairwise multigroup path comparisons (unadjusted) revealed significant differences for " & String.Join("; ", sigListEn.ToArray()) & ".")
            Else
                SetProseIfEmpty(t, "三组及以上的两两路径对比中，各组别间均未检出显著系数差异（*p* ≥ 0.05）。", "Pairwise path comparisons across groups showed no statistically significant differences (*p* ≥ 0.05).")
            End If
        End If
    End Sub

    ' ---------------------------------------------------------------- 14c. 多组间接效应 (groupindirect)
    Private Shared Sub InterpGroupIndirect(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cPath As Integer = FindCol(t, "间接路径")
        Dim cGrp As Integer = FindCol(t, "组别或对比")
        Dim cB As Integer = FindCol(t, "b或Δb")
        Dim cCi As Integer = FindCol(t, "BC 95% CI")

        Dim order As New List(Of String)()
        Dim groups As New Dictionary(Of String, List(Of String()))()
        For Each r As String() In t.Rows
            Dim p As String = CellText(r, cPath)
            If Not groups.ContainsKey(p) Then order.Add(p) : groups(p) = New List(Of String())()
            groups(p).Add(r)
        Next

        Dim proseZh As New List(Of String)(), proseEn As New List(Of String)()
        For Each p As String In order
            Dim sigGrps As New List(Of String)(), diffTextZh As String = "", diffTextEn As String = "", diffSig As Boolean = False
            For Each r As String() In groups(p)
                Dim g As String = CellText(r, cGrp)
                Dim b As Double = ParseNum(CellText(r, cB))
                Dim lo As Double, hi As Double
                Dim sig As Boolean = ParseCI(CellText(r, cCi), lo, hi) AndAlso ExcludesZero(lo, hi)
                Dim ciStr As String = Ap.Minus(CellText(r, cCi))
                If g.Contains(" − ") OrElse g.Contains(" - ") Then
                    diffSig = sig
                    diffTextZh = g & " 的差值 Δ*b* = " & Fmt3(b) & "（BC 95% CI " & ciStr & "）"
                    diffTextEn = g & " contrast Δ*b* = " & Fmt3(b) & " (BC 95% CI " & ciStr & ")"
                ElseIf sig Then
                    sigGrps.Add(g & "(*b* = " & Fmt3(b) & ", " & ciStr & ")")
                End If
            Next
            AddTo(out, If(diffSig, "ok", "info"), "路径 " & p & "：组内显著有 " & If(sigGrps.Count > 0, String.Join("、", sigGrps.ToArray()), "无") & If(diffTextZh <> "", "；组间差值 " & diffTextZh & If(diffSig, "，显著差异（不含 0）。", "，差异不显著（含 0）。"), "。"), "Path " & p & ": significant within " & If(sigGrps.Count > 0, String.Join(", ", sigGrps.ToArray()), "none") & If(diffTextEn <> "", "; " & diffTextEn & If(diffSig, " (significant difference).", " (non-significant difference)."), "."))
            If diffTextZh <> "" Then proseZh.Add(p & " 的组间" & diffTextZh) : proseEn.Add(p & " (" & diffTextEn & ")")
        Next
        If t.Prose.Count = 0 AndAlso proseZh.Count > 0 Then
            SetProseIfEmpty(t, "多组 Bootstrap 间接效应比较显示：" & String.Join("；", proseZh.ToArray()) & "。", "Multigroup bootstrap indirect-effect comparisons showed " & String.Join("; ", proseEn.ToArray()) & ".")
        End If
    End Sub

    ' ---------------------------------------------------------------- 15. 非论文检查表
    Private Shared Sub InterpMods(ByVal t As RTable, ByVal out As List(Of String()))
        If t.Cols.Count <= 2 Then
            AddTo(out, "info", CellText(t.Rows(0), t.Cols.Count - 1), CellText(t.Rows(0), t.Cols.Count - 1))
            Return
        End If
        Dim cParam As Integer = 0
        Dim colType As Integer = 1
        Dim cMi As Integer = FindCol(t, "M.I.")
        Dim cPc As Integer = FindCol(t, "Par Change")
        Dim topParam As String = CellText(t.Rows(0), cParam)
        Dim topType As String = CellText(t.Rows(0), colType)
        Dim topMi As Double = ParseNum(CellText(t.Rows(0), cMi))
        Dim topPc As Double = ParseNum(CellText(t.Rows(0), cPc))
        AddTo(out, "warn", "共检出 " & t.Rows.Count.ToString() & " 项高修正指数；最高为 " & topParam & "（" & topType & "，M.I. = " & Fmt3(topMi) & "，Par Change = " & Fmt3(topPc) & "）。", "Found " & t.Rows.Count.ToString() & " modification indices above threshold; highest: " & topParam & " (M.I. = " & Fmt3(topMi) & ", Par Change = " & Fmt3(topPc) & ").")
        AddTo(out, "info", "修正原则：仅允许在同一构念近义/反向题项且具充分理论依据时逐项放开残差相关，切勿仅凭数据驱动盲目加线。", "Only free residual covariances within the same construct with strong theoretical justification, one parameter at a time.")
    End Sub

    Private Shared Sub InterpCount(ByVal t As RTable, ByVal out As List(Of String()))
        Dim dfVal As Double = Double.NaN, nparVal As Double = Double.NaN
        Dim mismatch As Boolean = False
        For Each r As String() In t.Rows
            Dim item As String = CellText(r, 0)
            Dim vSelf As String = CellText(r, 1)
            Dim vEng As String = If(t.Cols.Count >= 3, CellText(r, 2), "—")
            If item.Contains("自由度") Then
                dfVal = ParseNum(vEng)
                If Double.IsNaN(dfVal) Then dfVal = ParseNum(vSelf)
                If vEng <> "—" AndAlso vSelf <> "—" AndAlso vEng <> vSelf Then mismatch = True
            ElseIf item.Contains("待估参数") Then
                nparVal = ParseNum(vEng)
                If Double.IsNaN(nparVal) Then nparVal = ParseNum(vSelf)
            End If
        Next
        If Not Double.IsNaN(dfVal) Then
            If dfVal > 0 Then
                AddTo(out, "ok", "自由度 *df* = " & CInt(dfVal).ToString() & " > 0，模型处于过度识别状态（待估参数 " & If(Double.IsNaN(nparVal), "—", CInt(nparVal).ToString()) & " 个），可检验整体拟合。", "*df* = " & CInt(dfVal).ToString() & " > 0 (over-identified model; " & If(Double.IsNaN(nparVal), "—", CInt(nparVal).ToString()) & " parameters), allowing fit evaluation.")
            ElseIf dfVal = 0 Then
                AddTo(out, "warn", "自由度 *df* = 0（恰好识别/饱和模型），卡方恒为 0，无法检验模型拟合优度。", "*df* = 0 (just-identified model); global fit cannot be tested.")
            Else
                AddTo(out, "warn", "自由度 *df* = " & CInt(dfVal).ToString() & " < 0（欠识别），须增加约束或简化路径。", "*df* = " & CInt(dfVal).ToString() & " < 0 (under-identified); add constraints or simplify paths.")
            End If
        End If
        If mismatch Then
            AddTo(out, "info", "路径图自计数与 AMOS 引擎计数存在差异（常见于均值/截距设定），以 AMOS 引擎栏为准。", "Diagram count differs from AMOS engine output (often due to mean/intercept settings); follow AMOS engine values.")
        End If
    End Sub

    Private Shared Sub InterpNormality(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cSkew As Integer = FindCol(t, "偏度")
        Dim cKurt As Integer = FindCol(t, "峰度")
        Dim maxSkew As Double = 0, maxKurt As Double = 0
        Dim mvKurt As Double = Double.NaN, mvCr As Double = Double.NaN
        Dim nOff As Integer = 0

        For Each r As String() In t.Rows
            Dim nm As String = CellText(r, 0)
            If nm.Contains("Mardia") OrElse nm.Contains("多元") Then
                mvKurt = ParseNum(CellText(r, cKurt))
                mvCr = ParseNum(CellText(r, cKurt + 1))
            Else
                Dim sk As Double = Math.Abs(ParseNum(CellText(r, cSkew)))
                Dim ku As Double = Math.Abs(ParseNum(CellText(r, cKurt)))
                If Not Double.IsNaN(sk) AndAlso sk > maxSkew Then maxSkew = sk
                If Not Double.IsNaN(ku) AndAlso ku > maxKurt Then maxKurt = ku
                If (Not Double.IsNaN(sk) AndAlso sk >= 2.0) OrElse (Not Double.IsNaN(ku) AndAlso ku >= 7.0) Then nOff += 1
            End If
        Next
        AddTo(out, If(nOff = 0, "ok", "warn"), "单变量最大 |偏度| = " & Fmt3(maxSkew) & "，最大 |峰度| = " & Fmt3(maxKurt) & "，" & If(nOff = 0, "均未超偏度 ≥ 2 或峰度 ≥ 7 参考线。", "有 " & nOff.ToString() & " 个变量偏离正态参照线。"), "Max univariate |skewness| = " & Fmt3(maxSkew) & ", max |kurtosis| = " & Fmt3(maxKurt) & " (" & If(nOff = 0, "within |skew| < 2 and |kurtosis| < 7", nOff.ToString() & " variable(s) exceeded reference lines") & ").")
        If Not Double.IsNaN(mvCr) Then
            Dim mvOk As Boolean = (mvCr <= 5.0)
            AddTo(out, If(mvOk, "ok", "warn"), "多元正态 Mardia 峰度 = " & Fmt3(mvKurt) & "，临界比 C.R. = " & Fmt3(mvCr) & "（" & If(mvOk, "≤ 5.0，未明显违背多元正态", "> 5.0，提示偏离多元正态，建议结合 Bootstrap 检验区间") & "）。", "Multivariate Mardia kurtosis = " & Fmt3(mvKurt) & ", C.R. = " & Fmt3(mvCr) & " (" & If(mvOk, "≤ 5.0", "> 5.0; consider Bootstrap CIs") & ").")
        End If
    End Sub

    Private Shared Sub InterpMahal(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cD2 As Integer = FindCol(t, "马氏距离平方 d²", "d²")
        Dim cP1 As Integer = FindCol(t, "p1")
        Dim nOut As Integer = 0, maxD2 As Double = 0
        Dim cases As New List(Of String)()
        For Each r As String() In t.Rows
            Dim d2 As Double = ParseNum(CellText(r, cD2))
            Dim p1 As Double = ParseNum(CellText(r, cP1))
            If Not Double.IsNaN(d2) AndAlso d2 > maxD2 Then maxD2 = d2
            If Not Double.IsNaN(p1) AndAlso p1 < 0.001 Then
                nOut += 1
                cases.Add(CellText(r, 0))
            End If
        Next
        If nOut = 0 Then
            AddTo(out, "ok", "前 " & t.Rows.Count.ToString() & " 个最远案例中无 *p*1 < 0.001 的极端多元离群值（最大 d² = " & Fmt3(maxD2) & "）。", "No extreme multivariate outliers (*p*1 < 0.001) among top cases (max d² = " & Fmt3(maxD2) & ").")
        Else
            AddTo(out, "warn", "发现 " & nOut.ToString() & " 个案例 *p*1 < 0.001（案例号：" & String.Join("、", cases.ToArray()) & "；最大 d² = " & Fmt3(maxD2) & "），建议核查异常作答并做敏感性对比。", "Detected " & nOut.ToString() & " potential multivariate outlier(s) with *p*1 < 0.001 (case(s): " & String.Join(", ", cases.ToArray()) & "; max d² = " & Fmt3(maxD2) & ").")
        End If
    End Sub

    Private Shared Sub InterpCheckSection(ByVal t As RTable, ByVal out As List(Of String()))
        Dim nMust As Integer = 0, nSug As Integer = 0, nPass As Integer = 0
        For Each r As String() In t.Rows
            Dim lv As String = CellText(r, 2)
            If lv = "必须改" Then
                nMust += 1
            ElseIf lv = "建议查看" Then
                nSug += 1
            ElseIf lv = "通过" Then
                nPass += 1
            End If
        Next
        If nMust > 0 Then
            AddTo(out, "warn", "本节检出 " & nMust.ToString() & " 项「必须改」问题、" & nSug.ToString() & " 项「建议查看」（通过 " & nPass.ToString() & " 项），请先修复「必须改」项。", nMust.ToString() & " critical ('必须改') and " & nSug.ToString() & " advisory ('建议查看') item(s) found (" & nPass.ToString() & " passed).")
        ElseIf nSug > 0 Then
            AddTo(out, "info", "本节无「必须改」问题；有 " & nSug.ToString() & " 项「建议查看」、" & nPass.ToString() & " 项通过。", "No critical issues; " & nSug.ToString() & " advisory item(s) and " & nPass.ToString() & " passed.")
        Else
            AddTo(out, "ok", "本节全部 " & nPass.ToString() & " 项检查均通过。", "All " & nPass.ToString() & " checks in this section passed.")
        End If
    End Sub

    Private Shared Sub InterpMissing(ByVal t As RTable, ByVal out As List(Of String()))
        Dim withMiss As New List(Of String)()
        For Each r As String() In t.Rows
            If CellText(r, 1) = "有" Then withMiss.Add(CellText(r, 0))
        Next
        If withMiss.Count > 0 Then
            AddTo(out, "warn", "共 " & withMiss.Count.ToString() & " 个变量含缺失值（" & String.Join("、", withMiss.ToArray()) & "），须启用 Estimate means and intercepts (FIML)。", withMiss.Count.ToString() & " variable(s) contain missing values; enable FIML (Estimate means and intercepts).")
        Else
            AddTo(out, "ok", "所列变量均无缺失值。", "No missing values detected in listed variables.")
        End If
    End Sub

    Private Shared Sub InterpUnid(ByVal t As RTable, ByVal out As List(Of String()))
        AddTo(out, "warn", "AMOS 点名 " & t.Rows.Count.ToString() & " 个不可识别参数，需固定其中参照载荷或约束方差后再试估。", "AMOS flagged " & t.Rows.Count.ToString() & " unidentified parameter(s); fix reference loadings or variances.")
    End Sub

    Private Shared Sub InterpMeasureSummary(ByVal t As RTable, ByVal out As List(Of String()))
        Dim cCr As Integer = FindCol(t, "CR")
        Dim cAve As Integer = FindCol(t, "AVE")
        Dim crs As New List(Of Double)(), aves As New List(Of Double)()
        For Each r As String() In t.Rows
            Dim cr As Double = ParseNum(CellText(r, cCr))
            Dim ave As Double = ParseNum(CellText(r, cAve))
            If Not Double.IsNaN(cr) Then crs.Add(cr)
            If Not Double.IsNaN(ave) Then aves.Add(ave)
        Next
        If crs.Count > 0 AndAlso aves.Count > 0 Then
            Dim cLo As Double, cHi As Double, aLo As Double, aHi As Double
            Ap.Range(crs, cLo, cHi)
            Ap.Range(aves, aLo, aHi)
            Dim ok As Boolean = (cLo >= 0.70 AndAlso aLo >= 0.50)
            AddTo(out, If(ok, "ok", "warn"), "各构念 CR = " & Fmt3(cLo) & "–" & Fmt3(cHi) & "，AVE = " & Fmt3(aLo) & "–" & Fmt3(aHi) & "。", "Construct CR = " & Fmt3(cLo) & "–" & Fmt3(cHi) & ", AVE = " & Fmt3(aLo) & "–" & Fmt3(aHi) & ".")
        End If
    End Sub
End Class

Partial Friend Class PaperOptions
    Public Shared Function ReadTestOptions(ByVal plugin As String) As Dictionary(Of String,String)
        Dim filename As String=Environment.GetEnvironmentVariable("AMOS_PAPER_TEST_CONFIG")
        If filename Is Nothing OrElse filename="" OrElse Not File.Exists(filename) Then Return Nothing
        Dim values As New Dictionary(Of String,String)(StringComparer.OrdinalIgnoreCase)
        For Each line As String In File.ReadAllLines(filename,Encoding.UTF8)
            Dim k As Integer=line.IndexOf("="c)
            If k>0 Then values(line.Substring(0,k).Trim())=line.Substring(k+1).Trim()
        Next
        If Not values.ContainsKey("plugin") OrElse values("plugin")<>plugin Then Return Nothing
        Return values
    End Function
    Public Shared Function GetValue(ByVal values As Dictionary(Of String,String),ByVal key As String,Optional ByVal fallback As String="") As String
        If values IsNot Nothing AndAlso values.ContainsKey(key) Then Return values(key)
        Return fallback
    End Function
    Public Shared Function IntegerValue(ByVal values As Dictionary(Of String,String),ByVal key As String,ByVal fallback As Integer,ByVal minimum As Integer,ByVal maximum As Integer) As Integer
        Dim text As String=GetValue(values,key,fallback.ToString()),n As Integer
        If Not Integer.TryParse(text,n) OrElse n<minimum OrElse n>maximum Then Throw New ArgumentException(key & "超出范围：" & text)
        Return n
    End Function
    Public Shared Function Flag(ByVal values As Dictionary(Of String,String),ByVal key As String,Optional ByVal fallback As Boolean=False) As Boolean
        Return GetValue(values,key,If(fallback,"1","0"))="1"
    End Function
    Public Shared Function Split(ByVal text As String) As List(Of String)
        Dim values As New List(Of String)()
        For Each s As String In text.Split(New Char(){";"c,ChrW(10),ChrW(13)},StringSplitOptions.RemoveEmptyEntries)
            If s.Trim()<>"" AndAlso Not values.Contains(s.Trim()) Then values.Add(s.Trim())
        Next
        Return values
    End Function
End Class

Friend Class PaperDialog
    Inherits Form
    Protected Body As New FlowLayoutPanel()
    Public Sub New(ByVal title As String)
        Me.Text=title : Me.Font=New System.Drawing.Font("Microsoft YaHei UI",9.0F)
        Me.StartPosition=FormStartPosition.CenterScreen : Me.FormBorderStyle=FormBorderStyle.FixedDialog
        Me.MaximizeBox=False : Me.MinimizeBox=False : Me.AutoScaleMode=AutoScaleMode.None
        Me.ClientSize=New System.Drawing.Size(590,610)
        Body.Dock=DockStyle.Fill : Body.FlowDirection=FlowDirection.TopDown : Body.WrapContents=False : Body.AutoScroll=True : Body.Padding=New Padding(16,10,16,10)
        Dim footer As New FlowLayoutPanel() : footer.Dock=DockStyle.Bottom : footer.Height=52 : footer.FlowDirection=FlowDirection.RightToLeft : footer.Padding=New Padding(10,8,10,8)
        Dim cancel As New Button() : cancel.Text="取消" : cancel.DialogResult=DialogResult.Cancel : cancel.Size=New System.Drawing.Size(90,32)
        Dim ok As New Button() : ok.Text="开始" : ok.Size=New System.Drawing.Size(90,32)
        AddHandler ok.Click,Sub(sender As Object,e As EventArgs)
                                Dim why As String=ValidateInput()
                                If why<>"" Then
                                    MessageBox.Show(why,Me.Text) : Return
                                End If
                                Me.DialogResult=DialogResult.OK : Me.Close()
                            End Sub
        footer.Controls.Add(cancel) : footer.Controls.Add(ok)
        Me.Controls.Add(Body) : Me.Controls.Add(footer) : Me.AcceptButton=ok : Me.CancelButton=cancel
    End Sub
    Protected Overridable Function ValidateInput() As String
        Return ""
    End Function
    Public Sub Finish()
        UiScale.Fit(Me)
    End Sub
    Public Sub Help(ByVal text As String)
        Dim label As New Label() : label.AutoSize=False : label.Width=535 : label.Height=48 : label.Text=text
        Body.Controls.Add(label)
    End Sub
    Public Function Check(ByVal text As String,Optional ByVal initial As Boolean=False) As CheckBox
        Dim c As New CheckBox() : c.Text=text : c.Checked=initial : c.AutoSize=False : c.Size=New System.Drawing.Size(535,30)
        Body.Controls.Add(c) : Return c
    End Function
    Private Function Row(ByVal text As String,ByVal control As Control) As Panel
        Dim panel As New Panel() : panel.Size=New System.Drawing.Size(535,40)
        Dim label As New Label() : label.Text=text : label.SetBounds(0,4,160,32) : label.TextAlign=System.Drawing.ContentAlignment.MiddleLeft
        control.SetBounds(165,4,355,30) : panel.Controls.Add(label) : panel.Controls.Add(control)
        Body.Controls.Add(panel) : Return panel
    End Function
    Public Function Choice(ByVal text As String,ByVal names As List(Of String),Optional ByVal blank As Boolean=True) As ComboBox
        Dim c As New ComboBox() : c.DropDownStyle=ComboBoxStyle.DropDownList
        If blank Then c.Items.Add("")
        For Each name As String In names : c.Items.Add(name) : Next
        If c.Items.Count>0 Then c.SelectedIndex=0
        Row(text,c) : Return c
    End Function
    Public Function Number(ByVal text As String,ByVal initial As Decimal,ByVal minimum As Decimal,ByVal maximum As Decimal,Optional ByVal digits As Integer=0) As NumericUpDown
        Dim c As New NumericUpDown() : c.Minimum=minimum : c.Maximum=maximum : c.DecimalPlaces=digits : c.Value=initial
        Row(text,c) : Return c
    End Function
    Public Function TextEntry(ByVal text As String,Optional ByVal initial As String="") As TextBox
        Dim c As New TextBox() : c.Text=initial : Row(text,c) : Return c
    End Function
End Class

Friend Class PaperData
    Public Shared Function Describe(ByVal m As ModelData,ByVal facs As List(Of Factor)) As RTable
        Paper.RequireModel(m)
        If m.HasMissing Then Throw New InvalidOperationException("构念得分的描述统计需要已完成缺失处理的数据。")
        If facs.Count=0 Then Throw New ArgumentException("请选择要描述的构念或观测变量。")
        Dim sem As New AmosEngine(),means() As Double=Nothing,cov(,) As Double=Nothing,names() As String=Nothing,meanNames() As String=Nothing
        Dim obs As New List(Of String)()
        For Each f As Factor In facs
            For Each item As String In f.Items
                If Not obs.Contains(item) Then obs.Add(item)
            Next
        Next
        Try
            sem.ModelMeansAndIntercepts()
            sem.NeedEstimates(ImpliedMeans) : sem.NeedEstimates(ImpliedCovariances)
            sem.GenerateDefaultCovariances(True)
            If m.GroupVar<>"" Then sem.BeginGroupEx(m.Fmt,m.FileName,m.TableName,m.GroupVar,m.GroupVal) Else sem.BeginGroupEx(m.Fmt,m.FileName,m.TableName)
            For Each v As String In obs : sem.Var(v) : sem.Mean(v) : Next
            If sem.FitModel()<>0 Then Throw New InvalidOperationException("描述统计的饱和均值模型未估计成功。")
            sem.GetEstimates(ImpliedMeans,means) : sem.RowNames(ImpliedMeans,meanNames)
            If Calc.IndexOf(meanNames,obs(0))<0 Then sem.ColumnNames(ImpliedMeans,meanNames)
            sem.GetEstimates(ImpliedCovariances,cov) : sem.RowNames(ImpliedCovariances,names)
        Finally
            sem.Dispose()
        End Try
        Dim n As Integer=facs.Count,mu(n-1) As Double,vc(n-1,n-1) As Double
        For i As Integer=0 To n-1
            If facs(i).Items.Count=0 Then Throw New ArgumentException("计分规则为空。")
            For Each item As String In facs(i).Items
                Dim index As Integer=Calc.IndexOf(meanNames,item)
                If index<0 Then Throw New InvalidOperationException("未取得题项均值：" & item)
                mu(i)+=means(index)/facs(i).Items.Count
            Next
            For j As Integer=0 To n-1
                For Each a As String In facs(i).Items
                    For Each b As String In facs(j).Items
                        vc(i,j)+=cov(Calc.IndexOf(names,a),Calc.IndexOf(names,b))/facs(i).Items.Count/facs(j).Items.Count
                    Next
                Next
            Next
        Next
        Dim cols As New List(Of String)(New String(){"变量","M","SD"}),widths As New List(Of Double)(New Double(){1.5,.7,.7})
        For i As Integer=1 To n : cols.Add(i.ToString()) : widths.Add(0.7) : Next
        Dim t As RTable=Paper.Table("descriptives","构念得分的描述统计与相关","Descriptive statistics and correlations of construct scores",cols.ToArray(),widths.ToArray()) : t.NameCols=True
        For i As Integer=0 To n-1
            Dim row(n+2) As String : row(0)=(i+1).ToString() & " " & facs(i).Name : row(1)=Paper.N(mu(i)) : row(2)=Paper.N(Math.Sqrt(vc(i,i)*m.NCases/(m.NCases-1)))
            For j As Integer=0 To n-1
                If j<i Then
                    Dim r As Double=vc(i,j)/Math.Sqrt(vc(i,i)*vc(j,j)),pval As Double=CorrelationP(r,m.NCases)
                    row(j+3)=Paper.N(r) & If(pval<0.001,"***",If(pval<0.01,"**",If(pval<0.05,"*","")))
                Else
                    row(j+3)=If(j=i,"—","")
                End If
            Next
            t.Rows.Add(row)
        Next
        Dim rules As New List(Of String)()
        For Each f As Factor In facs : rules.Add(f.Name & " = mean(" & String.Join(", ",f.Items.ToArray()) & ")") : Next
        t.PN("*N* = " & m.NCases.ToString() & "。计分规则：" & String.Join("；",rules.ToArray()) & "。*M*与*SD*使用原始量尺；*SD*采用n−1分母。下三角为同一有效样本的Pearson相关，对角线为—。*p*为双侧；* p < 0.05，** p < 0.01，*** p < 0.001。", "*N* = " & m.NCases.ToString() & ". Scoring: " & String.Join("; ",rules.ToArray()) & ". *M* and sample *SD* use the original scale. Lower triangle: Pearson correlations in the same complete analysis sample. Two-sided tests: * p < 0.05, ** p < 0.01, *** p < 0.001.")
        Return t
    End Function
    Public Shared Function CorrelationP(ByVal r As Double,ByVal n As Integer) As Double
        If n<3 Then Return Double.NaN
        If Math.Abs(r)>=1 Then Return 0
        Return Beta((n-2)/2.0,0.5,1-r*r)
    End Function
    Private Shared Function Lg(ByVal x As Double) As Double
        Dim cs() As Double={76.18009172947146,-86.50532032941677,24.01409824083091,-1.231739572450155,0.001208650973866179,-0.000005395239384953}
        Dim y As Double=x,tmp As Double=x+5.5,acc As Double=1.000000000190015
        tmp-=(x+0.5)*Math.Log(tmp)
        For Each c As Double In cs : y+=1 : acc+=c/y : Next
        Return -tmp+Math.Log(2.5066282746310007*acc/x)
    End Function
    Private Shared Function Fraction(ByVal a As Double,ByVal b As Double,ByVal x As Double) As Double
        Dim c As Double=1,d As Double=1-(a+b)*x/(a+1)
        If Math.Abs(d)<1.0E-300 Then d=1.0E-300
        d=1/d
        Dim h As Double=d
        For m As Integer=1 To 300
            Dim mm As Double=2*m,aa As Double=m*(b-m)*x/((a+mm-1)*(a+mm))
            d=1+aa*d : If Math.Abs(d)<1.0E-300 Then d=1.0E-300
            c=1+aa/c : If Math.Abs(c)<1.0E-300 Then c=1.0E-300
            d=1/d : h*=d*c
            aa=-(a+m)*(a+b+m)*x/((a+mm)*(a+mm+1))
            d=1+aa*d : If Math.Abs(d)<1.0E-300 Then d=1.0E-300
            c=1+aa/c : If Math.Abs(c)<1.0E-300 Then c=1.0E-300
            d=1/d
            Dim delta As Double=d*c : h*=delta
            If Math.Abs(delta-1)<0.00000000000003 Then Exit For
        Next
        Return h
    End Function
    Private Shared Function Beta(ByVal a As Double,ByVal b As Double,ByVal x As Double) As Double
        If x<=0 Then Return 0
        If x>=1 Then Return 1
        Dim bt As Double=Math.Exp(Lg(a+b)-Lg(a)-Lg(b)+a*Math.Log(x)+b*Math.Log(1-x))
        If x<(a+1)/(a+b+2) Then Return bt*Fraction(a,b,x)/a
        Return 1-bt*Fraction(b,a,1-x)/b
    End Function
End Class

' ============================================================================
' SemCalc.vb —— 「SEM 报告」专用的计算与表格（路径、R²、效应分解、特定间接效应）。
' 与 Core.vb 一起拼进 SEM报告.vb；CFA 报告不含本文件。
' ============================================================================

Friend Class SemPath
    Public ToName As String = ""
    Public FromName As String = ""
    Public Row As Integer
    Public Col As Integer
    Public Est As Double, Std As Double
    Public Se As Double = 0
    Public FromObserved As Boolean
End Class

Friend Class Chain
    Public Nodes As New List(Of String)()
    Public Est As Double, Std As Double
    Public Boot As New List(Of Double)()
End Class

Friend Class SemCalc
    ' ---- 标准正态分布函数与反函数（Acklam 算法，相对误差 < 1.2e-9）
    Public Shared Function Phi(ByVal z As Double) As Double
        If z >= 0 Then Return 1 - Calc.PFromZ(z) / 2
        Return Calc.PFromZ(-z) / 2
    End Function

    Public Shared Function PhiInv(ByVal p As Double) As Double
        If p <= 0 Then Return -8
        If p >= 1 Then Return 8
        Dim a() As Double = {-39.69683028665376, 220.9460984245205, -275.9285104469687, 138.357751867269, -30.66479806614716, 2.506628277459239}
        Dim b() As Double = {-54.47609879822406, 161.5858368580409, -155.6989798598866, 66.80131188771972, -13.28068155288572}
        Dim c() As Double = {-0.007784894002430293, -0.3223964580411365, -2.400758277161838, -2.549732539343734, 4.374664141464968, 2.938163982698783}
        Dim d() As Double = {0.007784695709041462, 0.3224671290700398, 2.445134137142996, 3.754408661907416}
        Dim plow As Double = 0.02425
        Dim q As Double, r As Double
        If p < plow Then
            q = Math.Sqrt(-2 * Math.Log(p))
            Return (((((c(0) * q + c(1)) * q + c(2)) * q + c(3)) * q + c(4)) * q + c(5)) / ((((d(0) * q + d(1)) * q + d(2)) * q + d(3)) * q + 1)
        ElseIf p <= 1 - plow Then
            q = p - 0.5
            r = q * q
            Return (((((a(0) * r + a(1)) * r + a(2)) * r + a(3)) * r + a(4)) * r + a(5)) * q / (((((b(0) * r + b(1)) * r + b(2)) * r + b(3)) * r + b(4)) * r + 1)
        Else
            q = Math.Sqrt(-2 * Math.Log(1 - p))
            Return -(((((c(0) * q + c(1)) * q + c(2)) * q + c(3)) * q + c(4)) * q + c(5)) / ((((d(0) * q + d(1)) * q + d(2)) * q + d(3)) * q + 1)
        End If
    End Function

    ' bootstrap 值的偏差校正（BC）95% 区间
    Public Shared Sub BcInterval(ByVal vals As List(Of Double), ByVal est As Double, ByRef lo As Double, ByRef hi As Double)
        Dim n As Integer = vals.Count
        Dim sorted As New List(Of Double)(vals)
        sorted.Sort()
        Dim below As Integer = 0
        For Each v As Double In sorted
            If v < est Then below += 1
        Next
        Dim z0 As Double = PhiInv((below + 0.0) / n)
        Dim pl As Double = Phi(2 * z0 - 1.959964)
        Dim pu As Double = Phi(2 * z0 + 1.959964)
        lo = Quantile(sorted, pl)
        hi = Quantile(sorted, pu)
    End Sub

    Private Shared Function Quantile(ByVal sorted As List(Of Double), ByVal p As Double) As Double
        Dim n As Integer = sorted.Count
        Dim pos As Double = p * (n - 1)
        Dim i As Integer = CInt(Math.Floor(pos))
        If i < 0 Then i = 0
        If i >= n - 1 Then Return sorted(n - 1)
        Dim f As Double = pos - i
        Return sorted(i) * (1 - f) + sorted(i + 1) * f
    End Function

    Public Shared Function SdOf(ByVal vals As List(Of Double)) As Double
        Dim n As Integer = vals.Count
        If n < 2 Then Return Double.NaN
        Dim mean As Double = 0
        For Each v As Double In vals
            mean += v
        Next
        mean /= n
        Dim ss As Double = 0
        For Each v As Double In vals
            ss += (v - mean) * (v - mean)
        Next
        Return Math.Sqrt(ss / (n - 1))
    End Function

    Public Shared Function PairKey(ByVal x As String, ByVal y As String) As String
        Return Convert.ToBase64String(Encoding.UTF8.GetBytes(x)) & "." & Convert.ToBase64String(Encoding.UTF8.GetBytes(y))
    End Function

    ' ---- 结构路径：剔除观测变量←潜变量的测量项；存在参数的零估计仍保留
    Public Shared Function Paths(ByVal m As ModelData) As List(Of SemPath)
        Dim res As New List(Of SemPath)()
        For j As Integer = 0 To m.ColNames.Length - 1
            Dim colObs As Boolean = Calc.IndexOf(m.Obs, m.ColNames(j)) >= 0
            For i As Integer = 0 To m.RowNames.Length - 1
                If Math.Abs(m.Dir(i, j)) < 0.000000000001 AndAlso Math.Abs(m.StdDir(i, j)) < 0.000000000001 AndAlso Not m.ParamEst.ContainsKey(m.RowNames(i) & "|" & m.ColNames(j)) Then Continue For
                Dim rowObs As Boolean = Calc.IndexOf(m.Obs, m.RowNames(i)) >= 0
                If rowObs AndAlso Not colObs Then Continue For
                Dim p As New SemPath()
                p.ToName = m.RowNames(i)
                p.FromName = m.ColNames(j)
                p.Row = i
                p.Col = j
                p.Est = m.Dir(i, j)
                p.Std = m.StdDir(i, j)
                p.FromObserved = colObs
                Dim key As String = p.ToName & "|" & p.FromName
                If m.ParamSe.ContainsKey(key) Then p.Se = m.ParamSe(key)
                res.Add(p)
            Next
        Next
        Return res
    End Function

    Private Shared Function Ord(ByVal m As ModelData, ByVal name As String) As Integer
        Dim i As Integer = m.DiagramOrder.IndexOf(name)
        If i < 0 Then Return 100000
        Return i
    End Function

    Public Shared Sub SortPaths(ByVal m As ModelData, ByVal ps As List(Of SemPath))
        ps.Sort(Function(x As SemPath, y As SemPath)
                    Dim c As Integer = Ord(m, x.ToName).CompareTo(Ord(m, y.ToName))
                    If c <> 0 Then Return c
                    Return Ord(m, x.FromName).CompareTo(Ord(m, y.FromName))
                End Function)
    End Sub

    Public Shared Function PathTable(ByVal m As ModelData, ByVal ps As List(Of SemPath), ByVal controls As Boolean) As RTable
        Dim t As New RTable()
        If controls Then
            t.Id = "controls"
            t.Title = Tx.T("控制变量的路径系数", "Path Coefficients for the Control Variables")
        Else
            t.Id = "paths"
            t.Title = Tx.T("结构模型的路径系数", "Path Coefficients for the Structural Model")
        End If
        Dim pz As New List(Of String)()
        t.Cols.AddRange(New String() {"路径", "非标准化估计 b", "S.E.", "C.R.", "p", "标准化系数 β"})
        Dim n As Integer = 0
        For Each p As SemPath In ps
            If p.FromObserved <> controls Then Continue For
            n += 1
            Dim lab As String = p.FromName & " → " & p.ToName
            If p.Se > 0.0000000001 Then
                Dim z As Double = p.Est / p.Se
                t.Rows.Add(New String() {lab, Calc.N3(p.Est), Calc.N3(p.Se), Calc.N2(z), Calc.PText(Calc.PFromZ(z)), Calc.N3(p.Std)})
                pz.Add(lab & "|β = " & Ap.Minus(Calc.N3(p.Std)) & "|" & Ap.PVal(Calc.PFromZ(z)))
            Else
                t.Rows.Add(New String() {lab, Calc.N3(p.Est), "—", "—", "—", Calc.N3(p.Std)})
            End If
        Next
        If n = 0 Then Return Nothing
        t.PN("*b* 为非标准化路径系数，*SE* 为其标准误，C.R. 为临界比（*b*／*SE*），β 为标准化路径系数。", "*b* = unstandardized path coefficient; C.R. = critical ratio (*b*/*SE*); β = standardized path coefficient.")
        t.Notes.Add("SE、C.R.、p 取自 AMOS 的参数估计（p 为 C.R. 的双侧正态检验），与 AMOS 输出表一致；SE 为「—」的是固定参数。")
        If pz.Count > 0 Then
            t.PR(If(controls, "控制变量的标准化路径系数：", "标准化路径系数：") & JoinTriples(pz, "，", "；") & "。", If(controls, "Standardized path coefficients for the control variables: ", "Standardized path coefficients: ") & JoinTriples(pz, ", ", "; ") & ".")
        End If
        Return t
    End Function

    ' ---- R²：递归模型里 R² = β′ R β（β 为标准化直接效应，R 为含潜变量的隐含相关矩阵）
    Public Shared Function RSquareTable(ByVal m As ModelData, ByVal ps As List(Of SemPath)) As RTable
        Dim t As New RTable()
        t.Id = "r2"
        t.Title = Tx.T("内生变量被解释的方差", "Variance Explained in the Endogenous Variables")
        Dim rz As New List(Of String)()
        t.Cols.AddRange(New String() {"变量", "R²"})
        Dim done As New List(Of String)()
        For Each p As SemPath In ps
            If done.Contains(p.ToName) Then Continue For
            done.Add(p.ToName)
            Dim preds As New List(Of SemPath)()
            For Each q As SemPath In ps
                If q.ToName = p.ToName Then preds.Add(q)
            Next
            Dim r2 As Double = 0
            For Each a As SemPath In preds
                For Each b As SemPath In preds
                    Dim ia As Integer = Calc.IndexOf(m.AllNames, a.FromName)
                    Dim ib As Integer = Calc.IndexOf(m.AllNames, b.FromName)
                    If ia < 0 OrElse ib < 0 Then Return Nothing
                    r2 += a.Std * b.Std * m.AllCor(ia, ib)
                Next
            Next
            t.Rows.Add(New String() {p.ToName, Calc.N3(r2)})
            rz.Add(p.ToName & "|*R*² = " & Calc.N3(r2))
        Next
        t.PN("*R*² 为该变量的方差中由其全部自变量解释的比例。", "*R*² = proportion of variance in the variable explained by its predictors.")
        t.PR("内生变量被解释的方差：" & JoinTriples(rz, "，", "；") & "。", "Variance explained in the endogenous variables: " & JoinTriples(rz, ", ", "; ") & ".")
        t.Notes.Add("R² = β′Rβ：β 为该变量全部自变量的标准化系数，R 为这些自变量之间的模型隐含相关矩阵。递归模型（无反馈环、扰动项互不相关）下等于 AMOS 的 SMC。")
        Return t
    End Function

    ' ---- 沿结构路径枚举 X → Y 的全部链
    Private Shared Sub Dfs(ByVal m As ModelData, ByVal ps As List(Of SemPath), ByVal cur As String, ByVal target As String, ByVal trail As List(Of SemPath), ByVal found As List(Of List(Of SemPath)))
        For Each p As SemPath In ps
            If p.FromName <> cur Then Continue For
            Dim seen As Boolean = False
            For Each t As SemPath In trail
                If t.ToName = p.ToName OrElse t.FromName = p.ToName Then seen = True
            Next
            If seen Then Continue For
            trail.Add(p)
            If p.ToName = target Then
                If trail.Count >= 2 Then found.Add(New List(Of SemPath)(trail))
            Else
                Dfs(m, ps, p.ToName, target, trail, found)
            End If
            trail.RemoveAt(trail.Count - 1)
        Next
    End Sub

    Public Shared Function SpecificIndirectTable(ByVal m As ModelData, ByVal ps As List(Of SemPath)) As RTable
        Dim t As New RTable()
        t.Id = "indirect"
        t.Title = Tx.T("特定间接效应", "Specific Indirect Effects")
        Dim iz As New List(Of String)()
        If m.BootN > 0 Then
            t.Cols.AddRange(New String() {"路径", "估计 b", "S.E.（bootstrap）", "BC 95% 区间", "标准化估计"})
        Else
            t.Cols.AddRange(New String() {"路径", "估计 b", "标准化估计"})
        End If
        Dim n As Integer = 0
        Dim sources As New List(Of String)()
        Dim targets As New List(Of String)()
        For Each p As SemPath In ps
            If Not sources.Contains(p.FromName) Then sources.Add(p.FromName)
            If Not targets.Contains(p.ToName) Then targets.Add(p.ToName)
        Next
        sources.Sort(Function(x As String, y As String) Ord(m, x).CompareTo(Ord(m, y)))
        targets.Sort(Function(x As String, y As String) Ord(m, x).CompareTo(Ord(m, y)))
        For Each xName As String In sources
            For Each yName As String In targets
                If xName = yName Then Continue For
                Dim found As New List(Of List(Of SemPath))()
                Dfs(m, ps, xName, yName, New List(Of SemPath)(), found)
                If found.Count = 0 Then Continue For
                n += 1
                Dim head(t.Cols.Count - 1) As String
                For k As Integer = 0 To head.Length - 1
                    head(k) = ""
                Next
                head(0) = xName & " → " & yName
                t.Rows.Add(head)
                Dim pair As String = PairKey(xName, yName)
                t.RowMeta.Add(New String() {pair, "", "group", xName, yName})
                Dim pathNo As Integer = 0
                Dim sumEst As Double = 0
                Dim sumStd As Double = 0
                Dim sumBoot As List(Of Double) = Nothing
                If m.BootN > 0 Then
                    sumBoot = New List(Of Double)()
                    For b As Integer = 0 To m.BootN - 1
                        sumBoot.Add(0)
                    Next
                End If
                For Each ch As List(Of SemPath) In found
                    pathNo += 1
                    Dim pathKey As String = pair & ":" & pathNo.ToString()
                    Dim lab As String = "　" & xName
                    Dim est As Double = 1
                    Dim sd As Double = 1
                    For Each e As SemPath In ch
                        lab &= " → " & e.ToName
                        est *= e.Est
                        sd *= e.Std
                    Next
                    sumEst += est
                    sumStd += sd
                    If m.BootN > 0 Then
                        Dim vals As New List(Of Double)()
                        For b As Integer = 0 To m.BootN - 1
                            Dim prod As Double = 1
                            For Each e As SemPath In ch
                                prod *= m.BootDirect(b)(e.Row, e.Col)
                            Next
                            vals.Add(prod)
                            sumBoot(b) += prod
                        Next
                        Dim lo As Double, hi As Double
                        BcInterval(vals, est, lo, hi)
                        t.Rows.Add(New String() {lab, Calc.N3(est), Calc.N3(SdOf(vals)), "[" & Calc.N3(lo) & ", " & Calc.N3(hi) & "]", Calc.N3(sd)})
                        iz.Add(lab.Trim("　"c) & "|*b* = " & Ap.Minus(Calc.N3(est)) & "|95% CI " & Ap.Minus("[" & Calc.N3(lo) & ", " & Calc.N3(hi) & "]"))
                        t.ProseParts.Add(New String() {pair, pathKey, Tx.T(lab.Trim() & "：*b* = " & Ap.Minus(Calc.N3(est)) & "，95% CI " & Ap.Minus("[" & Calc.N3(lo) & ", " & Calc.N3(hi) & "]") & "。", lab.Trim() & ": *b* = " & Ap.Minus(Calc.N3(est)) & ", 95% CI " & Ap.Minus("[" & Calc.N3(lo) & ", " & Calc.N3(hi) & "]") & ".")})
                    Else
                        t.Rows.Add(New String() {lab, Calc.N3(est), Calc.N3(sd)})
                        iz.Add(lab.Trim("　"c) & "|*b* = " & Ap.Minus(Calc.N3(est)))
                        t.ProseParts.Add(New String() {pair, pathKey, Tx.T(lab.Trim() & "：*b* = " & Ap.Minus(Calc.N3(est)) & "。", lab.Trim() & ": *b* = " & Ap.Minus(Calc.N3(est)) & ".")})
                    End If
                    t.RowMeta.Add(New String() {pair, pathKey, "path", xName, yName})
                Next
                If found.Count > 1 Then
                    If m.BootN > 0 Then
                        Dim lo2 As Double, hi2 As Double
                        BcInterval(sumBoot, sumEst, lo2, hi2)
                        t.Rows.Add(New String() {"　总间接效应", Calc.N3(sumEst), Calc.N3(SdOf(sumBoot)), "[" & Calc.N3(lo2) & ", " & Calc.N3(hi2) & "]", Calc.N3(sumStd)})
                    Else
                        t.Rows.Add(New String() {"　总间接效应", Calc.N3(sumEst), Calc.N3(sumStd)})
                    End If
                    t.RowMeta.Add(New String() {pair, "", "total", xName, yName})
                End If
            Next
        Next
        If n = 0 Then Return Nothing
        t.Notes.Add("每条链的估计 = 各段非标准化路径系数之积；链由程序沿结构路径自动枚举，不必逐条写自定义估计量。")
        If m.BootN > 0 Then
            t.PN("*b* 为非标准化间接效应。标准误与 95% 置信区间（CI）由偏差校正 bootstrap 法得到（重复抽样 " & m.BootN.ToString() & " 次）。", "*b* = unstandardized indirect effect. Standard errors and 95% confidence intervals (CI) were obtained with the bias-corrected bootstrap (" & m.BootN.ToString("#,0", CultureInfo.InvariantCulture) & " resamples).")
        Else
            t.PN("*b* 为非标准化间接效应（点估计）。", "*b* = unstandardized indirect effect (point estimate).")
        End If
        t.PR("特定间接效应：" & JoinTriples(iz, "，", "；") & "。", "Specific indirect effects: " & JoinTriples(iz, ", ", "; ") & ".")
        If m.BootN > 0 Then
            t.Notes.Add("S.E. 与 BC 区间由 " & m.BootN.ToString() & " 个 bootstrap 样本逐个计算每条链的乘积得到（AMOS 引擎提供每个样本的路径系数），区间含 0 即不显著。")
        Else
            t.Notes.Add("没有做 bootstrap（数据有缺失值时 AMOS 不能做 bootstrap），只给点估计。")
        End If
        Return t
    End Function

    ' 行文里的并列项：每项「名称|数|数」，项内用 inner 相连，项间用 outer 相连
    Public Shared Function JoinTriples(ByVal items As List(Of String), ByVal inner As String, ByVal outer As String) As String
        Dim res As New List(Of String)()
        For Each it As String In items
            res.Add(String.Join(inner, it.Split("|"c)))
        Next
        Return String.Join(outer, res.ToArray())
    End Function

    Private Shared Function Z3(ByVal x As Double) As String
        If Math.Abs(x) < 0.000000000001 Then Return "—"
        Return Calc.N3(x)
    End Function

    ' ---- 总效应分解：只列有间接效应的（自变量, 因变量）
    Public Shared Function EffectsTable(ByVal m As ModelData, ByVal ps As List(Of SemPath)) As RTable
        Dim t As New RTable()
        t.Id = "effects"
        t.Title = Tx.T("直接效应、间接效应与总效应", "Direct, Indirect, and Total Effects")
        Dim ez As New List(Of String)()
        Dim ee As New List(Of String)()
        If m.BootN > 0 Then
            t.Cols.AddRange(New String() {"自变量 → 因变量", "直接效应", "间接效应", "间接效应 BC 95% 区间", "总效应", "总效应 BC 95% 区间", "标准化总效应"})
        Else
            t.Cols.AddRange(New String() {"自变量 → 因变量", "直接效应", "间接效应", "总效应", "标准化总效应"})
        End If
        Dim n As Integer = 0
        Dim items As New List(Of Integer())()
        For j As Integer = 0 To m.ColNames.Length - 1
            For i As Integer = 0 To m.RowNames.Length - 1
                If m.RowNames(i) = m.ColNames(j) Then Continue For
                If Calc.IndexOf(m.Obs, m.RowNames(i)) >= 0 AndAlso Calc.IndexOf(m.Obs, m.ColNames(j)) < 0 Then Continue For
                Dim chains As New List(Of List(Of SemPath))()
                Dfs(m, ps, m.ColNames(j), m.RowNames(i), New List(Of SemPath)(), chains)
                If chains.Count > 0 Then items.Add(New Integer() {i, j})
            Next
        Next
        items.Sort(Function(a As Integer(), b As Integer())
                       Dim c As Integer = Ord(m, m.ColNames(a(1))).CompareTo(Ord(m, m.ColNames(b(1))))
                       If c <> 0 Then Return c
                       Return Ord(m, m.RowNames(a(0))).CompareTo(Ord(m, m.RowNames(b(0))))
                   End Function)
        For Each ij As Integer() In items
            Dim i As Integer = ij(0)
            Dim j As Integer = ij(1)
            n += 1
            Dim lab As String = m.ColNames(j) & " → " & m.RowNames(i)
            Dim pair As String = PairKey(m.ColNames(j), m.RowNames(i))
            t.RowMeta.Add(New String() {pair, "", "effects", m.ColNames(j), m.RowNames(i)})
            If m.BootN > 0 Then
                t.Rows.Add(New String() {lab, Z3(m.Dir(i, j)), Calc.N3(m.Ind(i, j)), "[" & Calc.N3(m.BcLo(i, j)) & ", " & Calc.N3(m.BcHi(i, j)) & "]", Calc.N3(m.Tot(i, j)), "[" & Calc.N3(m.BcLoTot(i, j)) & ", " & Calc.N3(m.BcHiTot(i, j)) & "]", Calc.N3(m.StdTot(i, j))})
                Dim ci1 As String = Ap.Minus("[" & Calc.N3(m.BcLo(i, j)) & ", " & Calc.N3(m.BcHi(i, j)) & "]")
                Dim ci2 As String = Ap.Minus("[" & Calc.N3(m.BcLoTot(i, j)) & ", " & Calc.N3(m.BcHiTot(i, j)) & "]")
                ez.Add(lab & "，间接效应 = " & Ap.Minus(Calc.N3(m.Ind(i, j))) & "，95% CI " & ci1 & "，总效应 = " & Ap.Minus(Calc.N3(m.Tot(i, j))) & "，95% CI " & ci2)
                ee.Add(lab & ", indirect effect = " & Ap.Minus(Calc.N3(m.Ind(i, j))) & ", 95% CI " & ci1 & ", total effect = " & Ap.Minus(Calc.N3(m.Tot(i, j))) & ", 95% CI " & ci2)
            Else
                t.Rows.Add(New String() {lab, Z3(m.Dir(i, j)), Calc.N3(m.Ind(i, j)), Calc.N3(m.Tot(i, j)), Calc.N3(m.StdTot(i, j))})
                ez.Add(lab & "，间接效应 = " & Ap.Minus(Calc.N3(m.Ind(i, j))) & "，总效应 = " & Ap.Minus(Calc.N3(m.Tot(i, j))))
                ee.Add(lab & ", indirect effect = " & Ap.Minus(Calc.N3(m.Ind(i, j))) & ", total effect = " & Ap.Minus(Calc.N3(m.Tot(i, j))))
            End If
        Next
        For k As Integer = 0 To ez.Count - 1
            t.ProseParts.Add(New String() {t.RowMeta(k)(0), "", Tx.T(ez(k) & "。", ee(k) & ".")})
        Next
        If n = 0 Then Return Nothing
        If m.BootN > 0 Then
            t.PN("表中为非标准化效应，最后一列为标准化总效应。95% 置信区间（CI）由偏差校正 bootstrap 法得到（重复抽样 " & m.BootN.ToString() & " 次）。直接效应处的短横线表示模型中没有设这条直接路径。", "Unstandardized effects are shown, except in the last column. The 95% confidence intervals (CI) were obtained with the bias-corrected bootstrap (" & m.BootN.ToString("#,0", CultureInfo.InvariantCulture) & " resamples). Dashes indicate that no direct path was specified.")
        Else
            t.PN("表中为非标准化效应，最后一列为标准化总效应。直接效应处的短横线表示模型中没有设这条直接路径。", "Unstandardized effects are shown, except in the last column. Dashes indicate that no direct path was specified.")
        End If
        t.PR("间接效应与总效应：" & String.Join("；", ez.ToArray()) & "。", "Indirect and total effects: " & String.Join("; ", ee.ToArray()) & ".")
        t.Notes.Add("总效应 = 直接效应 + 间接效应（AMOS 的效应矩阵）。置信区间为 AMOS 引擎给出的偏差校正（BC）bootstrap 区间。")
        Return t
    End Function

    Public Shared Function MeasurementSummary(ByVal m As ModelData, ByVal facs As List(Of Factor)) As RTable
        Dim t As New RTable()
        t.Id = "measure"
        t.Title = Tx.T("各构念的信度与聚合效度", "Reliability and Convergent Validity of the Constructs")
        t.Cols.AddRange(New String() {"构念", "题项数", "标准化载荷范围", "CR", "AVE", "Cronbach α"})
        For Each f As Factor In facs
            Dim mn As Double = Double.MaxValue
            Dim mx As Double = Double.MinValue
            For Each l As Double In f.Std
                If l < mn Then mn = l
                If l > mx Then mx = l
            Next
            t.Rows.Add(New String() {f.Name, f.Items.Count.ToString(), Calc.N3(mn) & " – " & Calc.N3(mx), Calc.N3(f.CR), Calc.N3(f.AVE), Calc.N3(f.AlphaRaw)})
        Next
        t.PN("CR = 组合信度；AVE = 平均方差抽取量。", "CR = composite reliability; AVE = average variance extracted.")
        t.Notes.Add("完整的载荷表、Fornell–Larcker 与 HTMT 见 CFA Report；此处的 CR、AVE 是在当前结构模型下由标准化载荷算出的。")
        Calc.RelProse(t, facs, m.Cov IsNot Nothing)
        Return t
    End Function
End Class

' ============================================================================
' SemX.vb —— 「SEM Report」的竞争模型比较：把 Manage Models 里定义的各个模型逐个估计，列拟合并与参照模型比较。
' 只拼进 SEM_Report.vb（在 SemCalc.vb 之后）。本文件不碰路径图（pd）：模型怎样交给引擎由调用方给的委托决定
' （插件里是 pd.SpecifyModel(sem)，核对外壳里是手写的引擎语句），所以能不开 AMOS 界面对答案（核对\核对SEM报告增强.ps1）。
'
' Manage Models 里的模型＝同一张路径图加上一组参数约束（如 b1 = 0、b2 = b3），所以各模型都嵌套在「不加约束」的模型里。
' 模型定义怎样进到引擎：先用 Model(名, 约束数组) 自己补定义再 FitModel(模型名)（窗口实测：pd.SpecifyModel 不带这些定义）；
' 不行（例如引擎里已经有同名模型）再直接 FitModel(模型名)。两种都不行就照实说明，不影响报告的其余部分。
' ============================================================================

Friend Delegate Sub SemSetup(ByVal sem As AmosEngine)

Friend Class SemModelFit
    Public Name As String = ""
    Public Constraints As New List(Of String)()
    Public OK As Boolean = False
    Public Msg As String = ""
    Public Cmin As Double = Double.NaN
    Public Df As Integer = 0
    Public Npar As Integer = 0
    Public Cfi As Double = Double.NaN
    Public Tli As Double = Double.NaN
    Public Rmsea As Double = Double.NaN
    Public Aic As Double = Double.NaN
    Public Bic As Double = Double.NaN
    Public Admissible As Boolean = True
End Class

Friend Class SemModels
    Public Fits As New List(Of SemModelFit)()
    Public Notes As New List(Of String)()
    Public How As String = ""          ' 模型定义是怎样进到引擎里的（写进表注，便于排查）
    Public Failed As String = ""       ' 两种办法都不行时的原因
    Public DefinedHere As Boolean = False   ' 模型定义是本插件补进引擎的（路径图没有带入）

    ' Manage Models 里一个模型的约束文本 → 逐条约束（按换行与分号拆开，去掉空白）
    Public Shared Function SplitConstraints(ByVal text As String) As List(Of String)
        Dim res As New List(Of String)()
        If text Is Nothing Then Return res
        For Each raw As String In text.Split(New Char() {ChrW(13), ChrW(10), ";"c})
            Dim one As String = raw.Trim()
            If one <> "" Then res.Add(one)
        Next
        Return res
    End Function

    Public Shared Function Run(ByVal names() As String, ByVal texts() As String, ByVal setup As SemSetup, ByVal m As ModelData) As SemModels
        Dim res As New SemModels()
        Dim why1 As String = ""
        Dim why2 As String = ""
        ' 2026-10-09 窗口实测（AMOS 30）：pd.SpecifyModel 不把 Manage Models 的定义带进引擎，所以先走「自己补定义」
        If res.Attempt(names, texts, setup, m, True, why2) Then
            res.How = "各模型的约束取自 Manage Models，由本插件在引擎里逐条补上。"
            res.DefinedHere = True
            Return res
        End If
        res.Fits.Clear()
        If res.Attempt(names, texts, setup, m, False, why1) Then
            res.How = "各模型的定义由路径图带入引擎。"
            Return res
        End If
        res.Fits.Clear()
        res.Failed = "没有能把 Manage Models 里的模型交给引擎（补定义后估计：" & why2 & "；直接按模型名估计：" & why1 & "）。"
        Return res
    End Function

    ' 一次尝试。define = False：直接 FitModel(名)；define = True：先 Model(名, 约束) 再 FitModel(名)。
    ' 返回 False 表示这种办法行不通（抛了异常），why 给出原因。模型估计不成功（返回非 0）不算办法行不通。
    Private Function Attempt(ByVal names() As String, ByVal texts() As String, ByVal setup As SemSetup, ByVal m As ModelData, ByVal define As Boolean, ByRef why As String) As Boolean
        Dim sem As New AmosEngine()
        Try
            ' 声明类方法都在设定模型之前
            If m.HasMissing AndAlso m.SatOK Then
                sem.SetSaturatedFit(True, m.SatCmin)
                sem.SetIndependenceFit(True, m.IndCmin)
            End If
            setup(sem)
            If define Then
                For i As Integer = 0 To names.Length - 1
                    sem.Model(names(i), SplitConstraints(texts(i)).ToArray())
                Next
            End If
            For i As Integer = 0 To names.Length - 1
                Dim f As New SemModelFit()
                f.Name = names(i)
                f.Constraints = SplitConstraints(texts(i))
                Dim st As Integer = sem.FitModel(names(i))
                If st <> 0 Then
                    If st = -6 Then
                        f.Msg = "AMOS 判定该模型很可能不可识别（引擎状态 -6）。"
                    Else
                        f.Msg = "引擎返回状态 " & st.ToString() & "，没有得到估计。"
                    End If
                Else
                    f.Cmin = sem.Cmin
                    f.Df = CInt(sem.Df)
                    f.Npar = sem.Npar
                    Try
                        f.Rmsea = sem.Rmsea
                    Catch
                    End Try
                    f.Admissible = sem.Admissible
                    If m.BaseOK AndAlso m.BaseDf > 0 AndAlso f.Df > 0 Then
                        Dim d1 As Double = Math.Max(f.Cmin - f.Df, 0)
                        Dim d2 As Double = Math.Max(Math.Max(m.BaseCmin - m.BaseDf, f.Cmin - f.Df), 0)
                        If d2 > 0 Then f.Cfi = 1 - d1 / d2 Else f.Cfi = 1
                        f.Tli = ((m.BaseCmin / m.BaseDf) - (f.Cmin / f.Df)) / ((m.BaseCmin / m.BaseDf) - 1)
                    End If
                    f.Aic = f.Cmin + 2 * f.Npar
                    If Not m.HasMissing AndAlso m.NCases > 0 Then f.Bic = f.Cmin + f.Npar * Math.Log(m.NCases)
                    f.OK = True
                End If
                Fits.Add(f)
            Next
            Return True
        Catch ex As Exception
            why = ex.Message
            Return False
        Finally
            sem.Dispose()
        End Try
    End Function

    ' 参照模型：估计成功的模型里约束最少（自由度最小）的那个；并列时取没有约束的、排在前面的
    Public Function Reference() As SemModelFit
        Dim best As SemModelFit = Nothing
        For Each f As SemModelFit In Fits
            If Not f.OK Then Continue For
            If best Is Nothing Then
                best = f
            ElseIf f.Df < best.Df Then
                best = f
            ElseIf f.Df = best.Df AndAlso best.Constraints.Count > 0 AndAlso f.Constraints.Count = 0 Then
                best = f
            End If
        Next
        Return best
    End Function

    ' ---- 两张表：各模型的拟合；与参照模型的 χ² 差异检验
    Public Function Tables() As List(Of RTable)
        Dim res As New List(Of RTable)()
        If Fits.Count = 0 Then Return res
        Dim t As New RTable()
        t.Id = "models_fit"
        t.Section = "竞争模型比较"
        Dim front As String = "本报告前面各表对应其中第一个模型「" & Fits(0).Name & "」。"
        If DefinedHere AndAlso Fits(0).Constraints.Count > 0 Then front = "本报告前面各表是路径图不加任何约束时的结果，不对应下面带约束的模型。"
        t.Lead.Add("Manage Models 里定义了 " & Fits.Count.ToString() & " 个模型。每个模型都是同一张路径图加上一组参数约束，下面逐个估计并比较。" & front)
        t.Title = Tx.T("竞争模型的拟合指标", "Fit Indices for the Competing Models")
        t.PN("", Ap.AbbrFit & " " & Ap.AbbrIc)
        t.Cols.AddRange(New String() {"模型", "χ²", "df", "CFI", "TLI", "RMSEA", "AIC", "BIC", "参数个数"})
        Dim minAic As SemModelFit = Nothing
        Dim minBic As SemModelFit = Nothing
        For Each f As SemModelFit In Fits
            If f.OK Then
                t.Rows.Add(New String() {f.Name, Calc.N3(f.Cmin), f.Df.ToString(), Calc.N3(f.Cfi), Calc.N3(f.Tli), Calc.N3(f.Rmsea), Calc.N3(f.Aic), Calc.N3(f.Bic), f.Npar.ToString()})
                If minAic Is Nothing OrElse f.Aic < minAic.Aic Then minAic = f
                If Not Double.IsNaN(f.Bic) AndAlso (minBic Is Nothing OrElse f.Bic < minBic.Bic) Then minBic = f
            Else
                t.Rows.Add(New String() {f.Name, "—", "—", "—", "—", "—", "—", "—", "—"})
            End If
            Dim cons As String = "没有约束"
            If f.Constraints.Count > 0 Then cons = "约束 " & String.Join("；", f.Constraints.ToArray())
            t.Notes.Add(f.Name & "：" & cons & "。" & If(f.OK, If(f.Admissible, "", "该解不可接受（Admissible = False），结果请谨慎使用。"), "本次没有得到估计：" & f.Msg))
        Next
        If How <> "" Then t.Notes.Add(How)
        If minAic IsNot Nothing Then
            Dim line As String = "AIC 最小的是「" & minAic.Name & "」"
            If minBic IsNot Nothing Then line &= "，BIC 最小的是「" & minBic.Name & "」"
            t.Paras.Add(line & "。AIC、BIC 越小越好，只在同一批数据、同一组观测变量的模型之间比较；它们兼顾拟合与简约，可以用于不嵌套的模型。")
        End If
        res.Add(t)

        Dim refFit As SemModelFit = Reference()
        If refFit Is Nothing Then Return res
        Dim c As New RTable()
        c.Id = "models_cmp"
        c.Title = Tx.T("竞争模型与参照模型（" & refFit.Name & "）的 χ² 差异检验", "Chi-Square Difference Tests Against the Reference Model (" & refFit.Name & ")")
        c.WrapLast = True
        c.NoCopy.Add("含义")
        c.PN("Δχ² 与 Δ*df* 为各模型与参照模型（" & refFit.Name & "）之差。", "Δχ² and Δ*df* are differences from the reference model (" & refFit.Name & ").")
        Dim cz As New List(Of String)()
        c.Cols.AddRange(New String() {"模型（约束更多）", "Δχ²", "Δdf", "p", "含义"})
        For Each f As SemModelFit In Fits
            If Object.ReferenceEquals(f, refFit) Then Continue For
            If Not f.OK Then
                c.Rows.Add(New String() {f.Name, "—", "—", "—", "该模型没有得到估计，无法比较。"})
                Continue For
            End If
            Dim d As Double = f.Cmin - refFit.Cmin
            Dim ddf As Integer = f.Df - refFit.Df
            If ddf <= 0 Then
                c.Rows.Add(New String() {f.Name, Calc.N3(d), ddf.ToString(), "—", "自由度不比参照模型多，不是在参照模型上加约束得到的，不能用 χ² 差异检验；请看上表的 AIC、BIC。"})
                Continue For
            End If
            Dim p As Double = SemStat.ChiSqP(d, ddf)
            Dim near As Boolean = Math.Abs(p - 0.05) < 0.005
            Dim ptxt As String = If(near, p.ToString("0.0000", CultureInfo.InvariantCulture), Calc.PText(p))
            Dim meaning As String
            If p < 0.05 Then
                meaning = "加上这些约束后拟合显著变差：约束不成立，保留参照模型。"
            Else
                meaning = "加上这些约束后拟合没有显著变差：约束后的模型更简约，可以保留。"
            End If
            If near Then meaning &= "p 值贴近 0.05，这一判断不稳，宜谨慎表述。"
            c.Rows.Add(New String() {f.Name, Calc.N3(d), ddf.ToString(), ptxt, meaning})
            cz.Add(f.Name & "|Δχ²(" & ddf.ToString() & ") = " & Ap.Minus(Calc.N3(d)) & "|" & Ap.PEq(ptxt))
        Next
        If cz.Count > 0 Then c.PR("与参照模型（" & refFit.Name & "）相比：" & SemCalc.JoinTriples(cz, "，", "；") & "。", "Compared with the reference model (" & refFit.Name & "): " & SemCalc.JoinTriples(cz, ", ", "; ") & ".")
        If refFit.Constraints.Count > 0 Then
            c.Notes.Add("参照模型自身也带约束。只有当其他模型的约束包含参照模型的全部约束时，两者才是嵌套关系，χ² 差异检验才成立；请自行确认。")
        Else
            c.Notes.Add("参照模型是不加约束的模型，其余各模型都嵌套在它里面。Δχ² = 该模型的 χ² − 参照模型的 χ²，Δdf 同理；显著性取 0.05。")
        End If
        c.Notes.Add("模型的取舍不能只看统计检验：被约束为 0 或相等的路径要有理论依据，取舍的理由要在论文里交代。")
        If c.Rows.Count > 0 Then res.Add(c)
        Return res
    End Function
End Class

' ---------------------------------------------------------------- χ² 分布的右尾概率（与 Cmb.vb 的 CmbStat 同一算法；各插件单独成文件，所以各带一份）
Friend Class SemStat
    Public Shared Function ChiSqP(ByVal x As Double, ByVal df As Double) As Double
        If Double.IsNaN(x) OrElse df <= 0 Then Return Double.NaN
        If x <= 0 Then Return 1
        Return GammaQ(df / 2.0, x / 2.0)
    End Function

    Private Shared Function LogGamma(ByVal xx As Double) As Double
        Dim cof() As Double = {76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.001208650973866179, -0.000005395239384953}
        Dim y As Double = xx
        Dim tmp As Double = xx + 5.5
        tmp -= (xx + 0.5) * Math.Log(tmp)
        Dim ser As Double = 1.000000000190015
        For j As Integer = 0 To 5
            y += 1
            ser += cof(j) / y
        Next
        Return -tmp + Math.Log(2.5066282746310007 * ser / xx)
    End Function

    Private Shared Function GammaQ(ByVal a As Double, ByVal x As Double) As Double
        Dim gln As Double = LogGamma(a)
        If x < a + 1 Then
            Dim ap As Double = a
            Dim del As Double = 1.0 / a
            Dim sum As Double = del
            For n As Integer = 1 To 1000
                ap += 1
                del *= x / ap
                sum += del
                If Math.Abs(del) < Math.Abs(sum) * 0.000000000000001 Then Exit For
            Next
            Return 1 - sum * Math.Exp(-x + a * Math.Log(x) - gln)
        End If
        Dim tiny As Double = 1.0E-300
        Dim b As Double = x + 1 - a
        Dim c As Double = 1.0 / tiny
        Dim d As Double = 1.0 / b
        Dim h As Double = d
        For i As Integer = 1 To 1000
            Dim an As Double = -i * (i - a)
            b += 2
            d = an * d + b
            If Math.Abs(d) < tiny Then d = tiny
            c = b + an / c
            If Math.Abs(c) < tiny Then c = tiny
            d = 1.0 / d
            Dim del2 As Double = d * c
            h *= del2
            If Math.Abs(del2 - 1) < 0.000000000000001 Then Exit For
        Next
        Return Math.Exp(-x + a * Math.Log(x) - gln) * h
    End Function
End Class

Friend Class PaperEffectSpec
    Public X As String=""
    Public Y As String=""
    Public Selected As New List(Of String)()
    Public CompareA As String=""
    Public CompareB As String=""
    Public BootN As Integer=5000
    Public Seed As Integer=2026
End Class

Friend Class PaperSem
    Public Shared Function Batch(ByVal m As ModelData,ByVal specs As List(Of PaperEffectSpec)) As RTable
        If specs.Count=0 Then Throw New ArgumentException("请选择效应关系。")
        Dim result As RTable=Nothing,seen As New List(Of String)()
        For Each spec As PaperEffectSpec In specs
            Dim key As String=spec.X & "|" & spec.Y
            If seen.Contains(key) Then Throw New ArgumentException("效应关系重复，请在同一关系内选择具体路径。")
            seen.Add(key)
            Dim t As RTable=Effects(m,spec)
            If result Is Nothing Then
                result=t
            Else
                Dim offset As Integer=result.Rows.Count : result.Rows.AddRange(t.Rows)
                For Each merge As Integer() In t.Merges : result.Merges.Add(New Integer(){merge(0),merge(1)+offset,merge(2)+offset}) : Next
                For Each note As String In t.PaperNotes
                    If Not result.PaperNotes.Contains(note) Then result.PaperNotes.Add(note)
                Next
            End If
        Next
        If specs.Count>1 Then
            result.PaperNotes.Clear()
            result.PN(Paper.BootNote(m) & "每个关系的占比分别以该关系的总效应为分母。选定关系及具体路径合并列示；各差值按表中前一路径减后一路径，由同次重抽样计算。", "*N* = " & m.NCases.ToString() & "; " & m.BootN.ToString() & " individual bootstrap samples; BC 95% CI; seed " & m.BootSeed.ToString() & ". Percentages use each relationship's own total effect. Contrasts subtract the second path from the first within the same resample.")
            For Each row As String() In result.Rows
                If row(5)="不适用" Then
                    result.PN("总效应接近0或组成效应方向相反的关系，占比记为不适用。", "Percentages are not applicable when a total is near zero or components have opposite signs.") : Exit For
                End If
            Next
        End If
        Return result
    End Function
    Public Shared Function Label(ByVal chain As List(Of SemPath)) As String
        Dim names As New List(Of String)()
        If chain.Count=0 Then Return ""
        names.Add(chain(0).FromName)
        For Each p As SemPath In chain : names.Add(p.ToName) : Next
        Return String.Join(" → ",names.ToArray())
    End Function
    Private Shared Sub Walk(ByVal paths As List(Of SemPath),ByVal x As String,ByVal y As String,ByVal seen As List(Of String),ByVal trail As List(Of SemPath),ByVal found As List(Of List(Of SemPath)))
        If seen.Contains(x) Then Throw New InvalidOperationException("效应分解需要无反馈环的递归模型。")
        seen.Add(x)
        For Each p As SemPath In paths
            If p.FromName<>x Then Continue For
            trail.Add(p)
            If p.ToName=y Then
                If trail.Count>=2 Then found.Add(New List(Of SemPath)(trail))
            Else
                Walk(paths,p.ToName,y,seen,trail,found)
            End If
            trail.RemoveAt(trail.Count-1)
        Next
        seen.RemoveAt(seen.Count-1)
    End Sub
    Public Shared Function Chains(ByVal paths As List(Of SemPath),ByVal x As String,ByVal y As String) As List(Of List(Of SemPath))
        If x="" OrElse y="" OrElse x=y Then Throw New ArgumentException("请选择不同的起点和结局变量。")
        Dim states As New Dictionary(Of String,Integer)()
        For Each p As SemPath In paths : Visit(paths,p.FromName,states) : Next
        Dim found As New List(Of List(Of SemPath))()
        Walk(paths,x,y,New List(Of String)(),New List(Of SemPath)(),found)
        Return found
    End Function
    Private Shared Sub Visit(ByVal paths As List(Of SemPath),ByVal node As String,ByVal states As Dictionary(Of String,Integer))
        If states.ContainsKey(node) Then
            If states(node)=1 Then Throw New InvalidOperationException("效应分解需要无反馈环的递归模型。")
            Return
        End If
        states(node)=1
        For Each p As SemPath In paths
            If p.FromName=node Then Visit(paths,p.ToName,states)
        Next
        states(node)=2
    End Sub
    Public Shared Function Product(ByVal chain As List(Of SemPath),Optional ByVal matrix As Double(,)=Nothing) As Double
        Dim answer As Double=1
        For Each p As SemPath In chain
            answer*=If(matrix Is Nothing,p.Est,matrix(p.Row,p.Col))
        Next
        Return answer
    End Function
    Public Shared Function Stats(ByVal values As List(Of Double),ByVal estimate As Double) As String()
        If values Is Nothing OrElse values.Count<5000 Then Throw New InvalidOperationException("Bootstrap有效次数不足5000。")
        For Each v As Double In values
            If Double.IsNaN(v) OrElse Double.IsInfinity(v) Then Throw New InvalidOperationException("Bootstrap包含无效估计，已停止生成效应表。")
        Next
        Dim lo As Double,hi As Double
        SemCalc.BcInterval(values,estimate,lo,hi)
        Return New String(){Paper.N(estimate),Paper.N(SemCalc.SdOf(values)),"[" & Paper.N(lo) & ", " & Paper.N(hi) & "]"}
    End Function
    Private Shared Sub AddEffect(ByVal t As RTable,ByVal relation As String,ByVal label As String,ByVal est As Double,ByVal values As List(Of Double),ByVal total As Double,ByVal share As Boolean)
        Dim st() As String=Stats(values,est)
        t.Rows.Add(New String(){relation,label,st(0),st(1),st(2),If(share,Paper.N(est/total*100,1) & "%",Tx.Row("不适用","Not applicable"))})
    End Sub
    Public Shared Function Effects(ByVal m As ModelData,ByVal spec As PaperEffectSpec) As RTable
        Paper.RequireModel(m) : Paper.RequireBoot(m)
        Dim paths As List(Of SemPath)=SemCalc.Paths(m),chains1 As List(Of List(Of SemPath))=Chains(paths,spec.X,spec.Y)
        If chains1.Count=0 Then Throw New ArgumentException("所选关系没有间接路径。")
        Dim ri As Integer=Calc.IndexOf(m.RowNames,spec.Y),ci As Integer=Calc.IndexOf(m.ColNames,spec.X)
        If ri<0 OrElse ci<0 Then Throw New ArgumentException("起点或结局不在当前模型中。")
        Dim dir As Double=m.Dir(ri,ci),ind As Double=0,total As Double
        Dim points As New Dictionary(Of String,Double)(),draws As New Dictionary(Of String,List(Of Double))()
        For Each chain As List(Of SemPath) In chains1
            Dim key As String=Label(chain),vals As New List(Of Double)()
            points(key)=Product(chain) : ind+=points(key)
            For Each matrix As Double(,) In m.BootDirect : vals.Add(Product(chain,matrix)) : Next
            draws(key)=vals
        Next
        total=dir+ind
        Dim share As Boolean=Math.Abs(total)>0.00000001 AndAlso dir*ind>=0
        For Each v As Double In points.Values
            If v*total<0 Then share=False
        Next
        Dim directBoot As New List(Of Double)(),indBoot As New List(Of Double)(),totalBoot As New List(Of Double)()
        For i As Integer=0 To m.BootN-1
            Dim sum As Double=0
            For Each vals As List(Of Double) In draws.Values : sum+=vals(i) : Next
            Dim direct As Double=m.BootDirect(i)(ri,ci)
            directBoot.Add(direct) : indBoot.Add(sum) : totalBoot.Add(sum+direct)
        Next
        Dim t As RTable=Paper.Table("effects","效应分解与间接效应比较","Effect decomposition and indirect-effect contrasts",New String(){"关系","效应或对比","b或Δb","SEboot","BC 95% CI","占总效应"},New Double(){1.0,2.1,.65,.75,1.7,.95})
        Dim relation As String=spec.X & " → " & spec.Y
        Dim allIndirect As Boolean=Math.Abs(dir)<0.000000000001 AndAlso Not m.ParamEst.ContainsKey(spec.Y & "|" & spec.X)
        AddEffect(t,relation,If(allIndirect,"总效应（均为间接）","总效应"),total,totalBoot,total,share)
        If Not allIndirect Then
            AddEffect(t,relation,"直接效应",dir,directBoot,total,share)
            If chains1.Count<>1 OrElse Not spec.Selected.Contains(Label(chains1(0))) Then AddEffect(t,relation,"总间接效应",ind,indBoot,total,share)
        End If
        For Each key As String In spec.Selected
            If Not points.ContainsKey(key) Then Throw New ArgumentException("所选间接路径不属于当前关系：" & key)
            If allIndirect AndAlso chains1.Count=1 Then Continue For
            AddEffect(t,relation,key,points(key),draws(key),total,share)
        Next
        If spec.CompareA<>"" OrElse spec.CompareB<>"" Then
            If spec.CompareA=spec.CompareB OrElse Not points.ContainsKey(spec.CompareA) OrElse Not points.ContainsKey(spec.CompareB) Then Throw New ArgumentException("请选择当前关系中两条不同的间接路径作比较。")
            Dim vals As New List(Of Double)()
            For i As Integer=0 To m.BootN-1 : vals.Add(draws(spec.CompareA)(i)-draws(spec.CompareB)(i)) : Next
            Dim st() As String=Stats(vals,points(spec.CompareA)-points(spec.CompareB))
            t.Rows.Add(New String(){relation,spec.CompareA & " − " & spec.CompareB,st(0),st(1),st(2),"—"})
        End If
        If t.Rows.Count>1 Then t.Merges.Add(New Integer(){0,0,t.Rows.Count-1})
        t.SetExtra("boot_n",m.BootN.ToString())
        t.PN(Paper.BootNote(m) & "占比以同一" & relation & "总效应为分母；差值行不计算占比。", "*N* = " & m.NCases.ToString() & "; unstandardized effects, " & m.BootN.ToString() & " individual bootstrap samples, BC 95% CIs, seed " & m.BootSeed.ToString() & ". Percentages use the total effect for " & relation & "; contrasts have no percentage.")
        If Not share Then t.PN("总效应接近0或存在方向相反的组成效应，占比记为不适用。", "Percentages are not applicable because the total is near zero or component effects have opposite signs.")
        If spec.CompareA<>"" Then t.PN("差值按前一条路径减后一条路径，在同次重抽样内计算。", "Contrasts subtract the second path from the first within each bootstrap sample.")
        Return t
    End Function
End Class

Partial Friend Class Paper
    Public Shared Function Paths(ByVal m As ModelData) As RTable
        Dim ps As List(Of SemPath)=SemCalc.Paths(m) : SemCalc.SortPaths(m,ps)
        Dim t As RTable=Table("paths","结构路径与解释率","Structural paths and explained variance",New String(){"路径","b","SE","β","Wald 95% CI","p","R²"},New Double(){1.7,.65,.65,.6,1.6,.65,.55})
        Dim rr As RTable=SemCalc.RSquareTable(m,ps),r2 As New Dictionary(Of String,String)()
        If rr IsNot Nothing Then
            For Each row As String() In rr.Rows : r2(row(0))=row(1) : Next
        End If
        Dim last As String="",start As Integer=0,hasObservedIv As Boolean=False
        For Each p As SemPath In ps
            If p.FromObserved Then hasObservedIv=True
            If p.ToName<>last Then
                If t.Rows.Count-start>1 Then t.Merges.Add(New Integer(){6,start,t.Rows.Count-1})
                start=t.Rows.Count : last=p.ToName
            End If
            t.Rows.Add(New String(){p.FromName & " → " & p.ToName,N(p.Est),If(p.Se>0,N(p.Se),"—"),N(p.Std),CI(p.Est,p.Se),If(p.Se>0,Paper.P(Calc.PFromZ(p.Est/p.Se)),"—"),If(r2.ContainsKey(p.ToName),r2(p.ToName),"—")})
        Next
        If t.Rows.Count-start>1 Then t.Merges.Add(New Integer(){6,start,t.Rows.Count-1})
        t.PN("*N* = " & m.NCases.ToString() & "。*b*为非标准化系数，β为完全标准化系数；*SE*、Wald 95% CI和双侧*p*对应*b*。同一因变量的*R*²合并显示。", "*N* = " & m.NCases.ToString() & ". *b* is unstandardized and β fully standardized; *SE*, Wald 95% CIs, and two-sided *p* values refer to *b*. *R*² is merged for each outcome.")
        If hasObservedIv Then
            t.SetExtra("has_observed_iv","1")
            t.PN("模型包含外生观测变量或二分类预测变量，建议优先解释其非标准化系数*b*及置信区间，而非仅依赖标准化系数β。", "The model includes observed exogenous or binary predictors; prioritize unstandardized *b* and its confidence interval over standardized β when interpreting their effects.")
        End If
        Return t
    End Function
End Class

Partial Friend Class PaperOptions
    Public Shared Function Nodes(ByVal paths As List(Of SemPath)) As List(Of String)
        Dim names As New List(Of String)()
        For Each p As SemPath In paths
            If Not names.Contains(p.FromName) Then names.Add(p.FromName)
            If Not names.Contains(p.ToName) Then names.Add(p.ToName)
        Next
        Return names
    End Function
    Public Shared Function Effect(ByVal auto As Dictionary(Of String,String)) As PaperEffectSpec
        Dim spec As New PaperEffectSpec()
        spec.X=GetValue(auto,"x") : spec.Y=GetValue(auto,"y")
        spec.Selected.AddRange(Split(GetValue(auto,"paths")))
        spec.CompareA=GetValue(auto,"compareA") : spec.CompareB=GetValue(auto,"compareB")
        spec.BootN=IntegerValue(auto,"boot",5000,5000,100000)
        spec.Seed=IntegerValue(auto,"seed",2026,1,29999)
        Return spec
    End Function
    Public Shared Function EffectBatch(ByVal auto As Dictionary(Of String,String)) As List(Of PaperEffectSpec)
        Dim result As New List(Of PaperEffectSpec)(),relations As List(Of String)=Split(GetValue(auto,"relations"))
        If relations.Count=0 Then result.Add(Effect(auto)) : Return result
        Dim selected As List(Of String)=Split(GetValue(auto,"paths")),used As New List(Of String)()
        For Each relation As String In relations
            Dim parts() As String=relation.Split(">"c)
            If parts.Length<>2 Then Throw New ArgumentException("关系写为X>Y。")
            Dim spec As New PaperEffectSpec() With {.X=parts(0).Trim(),.Y=parts(1).Trim(),.BootN=IntegerValue(auto,"boot",5000,5000,100000),.Seed=IntegerValue(auto,"seed",2026,1,29999)}
            For Each label As String In selected
                If label.StartsWith(spec.X & " → ",StringComparison.Ordinal) AndAlso label.EndsWith(" → " & spec.Y,StringComparison.Ordinal) Then spec.Selected.Add(label) : used.Add(label)
            Next
            Dim ca As String=GetValue(auto,"compareA"),cb As String=GetValue(auto,"compareB")
            If ca.StartsWith(spec.X & " → ",StringComparison.Ordinal) AndAlso ca.EndsWith(" → " & spec.Y,StringComparison.Ordinal) Then spec.CompareA=ca : spec.CompareB=cb
            result.Add(spec)
        Next
        If used.Count<>selected.Count Then Throw New ArgumentException("有具体间接路径没有匹配到选定关系。")
        Return result
    End Function
End Class

Friend Class PaperSemDialog
    Inherits PaperDialog
    Public EffectCheck As CheckBox
    Public DescribeCheck As CheckBox
    Public CompeteCheck As CheckBox
    Private RelationList As New CheckedListBox()
    Private SpecificPathsCheck As CheckBox
    Private PathBox As New CheckedListBox()
    Private CompareCheck As CheckBox
    Private CompareBox As ComboBox
    Private BootBox As NumericUpDown,SeedBox As NumericUpDown
    Private BtnAll As Button,BtnExoTerm As Button,BtnClear As Button
    Private Paths As List(Of SemPath)
    Private Relations As New List(Of String())()
    Private ChainsByRel As New Dictionary(Of String,List(Of String))()
    Private SelectedByRel As New Dictionary(Of String,List(Of String))()
    Private ComparePairs As New List(Of String())()
    Private HasMissing As Boolean=False
    Private Busy As Boolean=False

    Public Sub New(ByVal m As ModelData,Optional ByVal competeCount As Integer=-1)
        MyBase.New("SEM Report 论文输出")
        Me.ClientSize=New System.Drawing.Size(610,690)
        HasMissing=m.HasMissing
        Paths=SemCalc.Paths(m)
        If competeCount<0 Then competeCount=ProbeCompeteModels()

        Help("默认输出模型拟合、结构路径与 R²。有间接路径时可直接在下方勾选关系与特定路径，无需逐个加入清单。")
        DiscoverRelations(m)

        EffectCheck=Check("输出选定关系的效应分解（含 Bootstrap 置信区间）",Not HasMissing AndAlso Relations.Count>0)
        If HasMissing Then
            EffectCheck.Enabled=False
            Dim warnLbl As New Label() : warnLbl.AutoSize=False : warnLbl.Size=New System.Drawing.Size(545,24)
            warnLbl.ForeColor=System.Drawing.Color.Firebrick
            warnLbl.Text="提示：当前数据含缺失值（FIML 估计），AMOS 不支持运行 Bootstrap，效应分解已自动禁用。"
            Body.Controls.Add(warnLbl)
        ElseIf Relations.Count=0 Then
            EffectCheck.Enabled=False
            Dim emptyLbl As New Label() : emptyLbl.AutoSize=False : emptyLbl.Size=New System.Drawing.Size(545,22)
            emptyLbl.Text="当前结构模型未检测到间接路径（仅输出拟合与路径表）。"
            Body.Controls.Add(emptyLbl)
        End If

        Dim quickPanel As New FlowLayoutPanel() : quickPanel.Size=New System.Drawing.Size(545,32) : quickPanel.FlowDirection=FlowDirection.LeftToRight : quickPanel.Margin=New Padding(0,0,0,2)
        BtnAll=New Button() : BtnAll.Text="全选所有中介" : BtnAll.Size=New System.Drawing.Size(120,26)
        BtnExoTerm=New Button() : BtnExoTerm.Text="仅选外生→终端" : BtnExoTerm.Size=New System.Drawing.Size(130,26)
        BtnClear=New Button() : BtnClear.Text="清空" : BtnClear.Size=New System.Drawing.Size(80,26)
        quickPanel.Controls.Add(BtnAll) : quickPanel.Controls.Add(BtnExoTerm) : quickPanel.Controls.Add(BtnClear)
        Body.Controls.Add(quickPanel)

        RelationList.Width=545 : RelationList.Height=115 : RelationList.CheckOnClick=True
        Body.Controls.Add(RelationList)
        Busy=True
        For Each rel As String() In Relations
            RelationList.Items.Add(rel(0) & " → " & rel(1) & "（" & rel(3) & " 条间接路径）",rel(4)="1" AndAlso Not HasMissing)
        Next
        Busy=False

        SpecificPathsCheck=Check("输出具体间接路径（默认全选；点击上方关系可在下方逐条调整）",True)
        PathBox.Width=545 : PathBox.Height=90 : PathBox.CheckOnClick=True
        Body.Controls.Add(PathBox)

        CompareCheck=Check("特定间接效应两两对比（可选）",False)
        CompareBox=Choice("对比路径对",New List(Of String)(),False)

        BootBox=Number("Bootstrap次数",5000,5000,100000) : SeedBox=Number("固定种子",2026,1,29999)
        DescribeCheck=Check("附构念得分的描述统计与相关")
        If HasMissing Then
            DescribeCheck.Checked=False : DescribeCheck.Enabled=False
        End If

        If competeCount>=2 Then
            CompeteCheck=Check("比较 Manage Models 中已定义的竞争模型（检测到 " & competeCount.ToString() & " 个）")
        Else
            CompeteCheck=Check("比较 Manage Models 中已定义的竞争模型（未检测到 ≥ 2 个模型）")
            CompeteCheck.Checked=False : CompeteCheck.Enabled=False
            Dim tipLbl As New Label() : tipLbl.AutoSize=False : tipLbl.Size=New System.Drawing.Size(545,22)
            tipLbl.ForeColor=System.Drawing.Color.DimGray
            tipLbl.Text="说明：如需比较竞争模型，请先在 AMOS 的 Manage Models 中定义至少 2 个理论模型。"
            Body.Controls.Add(tipLbl)
        End If

        AddHandler BtnAll.Click,Sub(sender As Object,e As EventArgs)
                                    SetAllRelations(True)
                                End Sub
        AddHandler BtnExoTerm.Click,Sub(sender As Object,e As EventArgs)
                                        SetExoTermRelations()
                                    End Sub
        AddHandler BtnClear.Click,Sub(sender As Object,e As EventArgs)
                                      SetAllRelations(False)
                                  End Sub
        AddHandler RelationList.SelectedIndexChanged,AddressOf OnRelationFocused
        AddHandler RelationList.ItemCheck,AddressOf OnRelationItemCheck
        AddHandler PathBox.ItemCheck,AddressOf OnPathItemCheck
        AddHandler EffectCheck.CheckedChanged,AddressOf OnStateChanged
        AddHandler SpecificPathsCheck.CheckedChanged,AddressOf OnStateChanged
        AddHandler CompareCheck.CheckedChanged,AddressOf OnStateChanged

        If RelationList.Items.Count>0 Then
            Dim firstChecked As Integer=-1
            For i As Integer=0 To RelationList.Items.Count-1
                If RelationList.GetItemChecked(i) Then firstChecked=i : Exit For
            Next
            RelationList.SelectedIndex=If(firstChecked>=0,firstChecked,0)
        End If
        RefreshComparePairs()
        UpdateEnabled()
        Finish()
    End Sub

    Private Shared Function ProbeCompeteModels() As Integer
        Dim count As Integer=0
        Try
            Dim names() As String=Nothing,texts() As String=Nothing
            pd.GetModels(names,texts)
            If names IsNot Nothing Then
                For i As Integer=0 To names.Length-1
                    If names(i) IsNot Nothing AndAlso names(i).Trim()<>"" Then count+=1
                Next
            End If
        Catch
        End Try
        Return count
    End Function

    Private Sub DiscoverRelations(ByVal m As ModelData)
        Dim nodes As List(Of String)=PaperOptions.Nodes(Paths)
        nodes.Sort(Function(a As String,b As String)
                       Dim ia As Integer=m.DiagramOrder.IndexOf(a),ib As Integer=m.DiagramOrder.IndexOf(b)
                       If ia<0 Then ia=100000
                       If ib<0 Then ib=100000
                       Return ia.CompareTo(ib)
                   End Function)
        Dim hasIn As New Dictionary(Of String,Boolean)(),hasOut As New Dictionary(Of String,Boolean)()
        For Each p As SemPath In Paths
            hasOut(p.FromName)=True : hasIn(p.ToName)=True
        Next
        For Each x As String In nodes
            For Each y As String In nodes
                If x=y Then Continue For
                Try
                    Dim chains As List(Of List(Of SemPath))=PaperSem.Chains(Paths,x,y)
                    If chains.Count=0 Then Continue For
                    Dim key As String=x & "|" & y
                    Dim labels As New List(Of String)()
                    For Each ch As List(Of SemPath) In chains : labels.Add(PaperSem.Label(ch)) : Next
                    ChainsByRel(key)=labels
                    SelectedByRel(key)=New List(Of String)(labels)
                    Dim isExoTerm As Boolean=(Not hasIn.ContainsKey(x)) AndAlso (Not hasOut.ContainsKey(y))
                    Relations.Add(New String(){x,y,key,chains.Count.ToString(),If(isExoTerm,"1","0")})
                Catch
                End Try
            Next
        Next
    End Sub

    Private Sub SetAllRelations(ByVal state As Boolean)
        Busy=True
        For i As Integer=0 To RelationList.Items.Count-1 : RelationList.SetItemChecked(i,state) : Next
        Busy=False
        RefreshComparePairs()
        UpdateEnabled()
    End Sub

    Private Sub SetExoTermRelations()
        Busy=True
        For i As Integer=0 To Relations.Count-1 : RelationList.SetItemChecked(i,Relations(i)(4)="1") : Next
        Busy=False
        RefreshComparePairs()
        UpdateEnabled()
    End Sub

    Private Sub OnRelationFocused(ByVal sender As Object,ByVal e As EventArgs)
        PopulatePathBox()
    End Sub

    Private Sub PopulatePathBox()
        Busy=True
        PathBox.Items.Clear()
        Dim idx As Integer=RelationList.SelectedIndex
        If idx>=0 AndAlso idx<Relations.Count Then
            Dim key As String=Relations(idx)(2),sel As List(Of String)=SelectedByRel(key)
            For Each label As String In ChainsByRel(key)
                PathBox.Items.Add(label,sel.Contains(label))
            Next
        End If
        Busy=False
    End Sub

    Private Sub OnPathItemCheck(ByVal sender As Object,ByVal e As ItemCheckEventArgs)
        If Busy Then Return
        Dim idx As Integer=RelationList.SelectedIndex
        If idx<0 OrElse idx>=Relations.Count Then Return
        Dim key As String=Relations(idx)(2),sel As New List(Of String)()
        For i As Integer=0 To PathBox.Items.Count-1
            Dim chk As Boolean=If(i=e.Index,e.NewValue=CheckState.Checked,PathBox.GetItemChecked(i))
            If chk Then sel.Add(CStr(PathBox.Items(i)))
        Next
        SelectedByRel(key)=sel
    End Sub

    Private Sub OnRelationItemCheck(ByVal sender As Object,ByVal e As ItemCheckEventArgs)
        If Busy Then Return
        RefreshComparePairs(e.Index,e.NewValue=CheckState.Checked)
        UpdateEnabled()
    End Sub

    Private Sub OnStateChanged(ByVal sender As Object,ByVal e As EventArgs)
        UpdateEnabled()
    End Sub

    Private Sub RefreshComparePairs(Optional ByVal overrideIdx As Integer=-1,Optional ByVal overrideVal As Boolean=False)
        Dim prevText As String=If(CompareBox.SelectedIndex>=0,CStr(CompareBox.SelectedItem),"")
        CompareBox.Items.Clear() : ComparePairs.Clear()
        For i As Integer=0 To Relations.Count-1
            Dim isChecked As Boolean=If(i=overrideIdx,overrideVal,RelationList.GetItemChecked(i))
            If Not isChecked Then Continue For
            Dim key As String=Relations(i)(2),chains As List(Of String)=ChainsByRel(key)
            If chains.Count<2 Then Continue For
            For a As Integer=0 To chains.Count-2
                For b As Integer=a+1 To chains.Count-1
                    Dim disp As String=chains(a) & "  vs  " & chains(b)
                    ComparePairs.Add(New String(){key,chains(a),chains(b),disp})
                    CompareBox.Items.Add(disp)
                Next
            Next
        Next
        If CompareBox.Items.Count>0 Then
            Dim sel As Integer=0
            If prevText<>"" Then
                For i As Integer=0 To CompareBox.Items.Count-1
                    If CStr(CompareBox.Items(i))=prevText Then sel=i : Exit For
                Next
            End If
            CompareBox.SelectedIndex=sel
        Else
            CompareCheck.Checked=False
        End If
    End Sub

    Private Sub UpdateEnabled()
        Dim onEff As Boolean=EffectCheck.Checked AndAlso Not HasMissing AndAlso Relations.Count>0
        BtnAll.Enabled=onEff : BtnExoTerm.Enabled=onEff : BtnClear.Enabled=onEff
        RelationList.Enabled=onEff
        SpecificPathsCheck.Enabled=onEff
        PathBox.Enabled=onEff AndAlso SpecificPathsCheck.Checked
        CompareCheck.Enabled=onEff AndAlso ComparePairs.Count>0
        If Not CompareCheck.Enabled Then CompareCheck.Checked=False
        CompareBox.Enabled=onEff AndAlso CompareCheck.Enabled AndAlso CompareCheck.Checked
        BootBox.Enabled=onEff : SeedBox.Enabled=onEff
    End Sub

    Protected Overrides Function ValidateInput() As String
        If EffectCheck.Checked Then
            If HasMissing Then Return "数据含缺失值（FIML 估计），AMOS 不支持 Bootstrap，请取消勾选效应分解。"
            If RelationList.CheckedIndices.Count=0 Then Return "请至少勾选一个包含间接路径的关系，或取消勾选「输出选定关系的效应分解」。"
            If CompareCheck.Checked AndAlso (CompareBox.SelectedIndex<0 OrElse CompareBox.SelectedIndex>=ComparePairs.Count) Then Return "当前勾选的关系中没有包含至少两条间接路径的可比路径对，请取消对比或勾选含多条路径的关系。"
        End If
        Return ""
    End Function

    Public Function Specs() As List(Of PaperEffectSpec)
        Dim result As New List(Of PaperEffectSpec)()
        If Not EffectCheck.Checked Then Return result
        Dim bootN As Integer=CInt(BootBox.Value),seed As Integer=CInt(SeedBox.Value)
        Dim cmpKey As String="",cmpA As String="",cmpB As String=""
        If CompareCheck.Checked AndAlso CompareBox.SelectedIndex>=0 AndAlso CompareBox.SelectedIndex<ComparePairs.Count Then
            cmpKey=ComparePairs(CompareBox.SelectedIndex)(0)
            cmpA=ComparePairs(CompareBox.SelectedIndex)(1)
            cmpB=ComparePairs(CompareBox.SelectedIndex)(2)
        End If
        For Each idx As Integer In RelationList.CheckedIndices
            Dim rel As String()=Relations(idx)
            Dim s As New PaperEffectSpec() With {.X=rel(0),.Y=rel(1),.BootN=bootN,.Seed=seed}
            If SpecificPathsCheck.Checked Then s.Selected.AddRange(SelectedByRel(rel(2)))
            If cmpKey=rel(2) Then s.CompareA=cmpA : s.CompareB=cmpB
            result.Add(s)
        Next
        Return result
    End Function
End Class

Friend Class PaperSemX
    Public Shared Function Competition(ByVal models As SemModels,ByVal m As ModelData) As RTable
        If models.Failed<>"" Then Throw New InvalidOperationException(models.Failed)
        Dim reference As SemModelFit=models.Reference()
        If reference Is Nothing Then Throw New InvalidOperationException("没有可用的参照模型。")
        Dim t As RTable=Paper.Table("fit","结构竞争模型的拟合与比较","Competing structural models",New String(){"模型","χ² (df)","χ²/df","CFI","TLI","RMSEA","AIC","BIC","Δχ² (Δdf)","p"},New Double(){1.4,1.1,.65,.55,.55,.8,.9,.9,1.2,.65})
        For Each f As SemModelFit In models.Fits
            If Not f.OK OrElse Not f.Admissible Then Throw New InvalidOperationException("竞争模型没有得到可用估计：" & f.Name & " " & f.Msg)
            Dim difference As String="—",p As String="—",dd As Integer=f.Df-reference.Df
            If dd>0 AndAlso f.Cmin>=reference.Cmin-0.00001 AndAlso Regular(f,reference,m) Then
                difference=Paper.N(f.Cmin-reference.Cmin,2) & " (" & dd.ToString() & ")" : p=Paper.P(SemStat.ChiSqP(f.Cmin-reference.Cmin,dd))
            End If
            t.Rows.Add(New String(){f.Name,Paper.N(f.Cmin,2) & " (" & f.Df.ToString() & ")",If(f.Df>0,Paper.N(f.Cmin/f.Df),"—"),Paper.N(f.Cfi),Paper.N(f.Tli),Paper.N(f.Rmsea),Paper.N(f.Aic,2),Paper.N(f.Bic,2),difference,p})
        Next
        Dim constraints As New List(Of String)()
        For Each f As SemModelFit In models.Fits : constraints.Add(f.Name & ": " & If(f.Constraints.Count=0,"free",String.Join("; ",f.Constraints.ToArray()))) : Next
        t.SetExtra("reference_model",reference.Name)
        t.PN("比较基准为" & reference.Name & "；Δχ²为受限减自由模型，仅对可核对的新增约束报告常规ML差异检验。各模型约束：" & String.Join("；",constraints.ToArray()) & "。", "Reference: " & reference.Name & ". ML chi-square differences compare restricted and unrestricted models. Constraints: " & String.Join("; ",constraints.ToArray()) & ".")
        Return t
    End Function
    Private Shared Function Regular(ByVal f As SemModelFit,ByVal reference As SemModelFit,ByVal m As ModelData) As Boolean
        If reference.Constraints.Count<>0 Then Return False
        For Each constraint As String In f.Constraints
            Dim sides() As String=constraint.Split("="c)
            If sides.Length<>2 Then Return False
            Dim named As Integer=0
            For Each raw As String In sides
                Dim term As String=raw.Trim(),value As Double
                If m.RegressionLabels.Contains(term) Then
                    named+=1
                ElseIf Not Double.TryParse(term,NumberStyles.Float,CultureInfo.InvariantCulture,value) OrElse Double.IsNaN(value) OrElse Double.IsInfinity(value) Then
                    Return False
                End If
            Next
            If named=0 Then Return False
        Next
        Return f.Constraints.Count>0
    End Function
End Class

' ---------------------------------------------------------------- 插件类：SEM Report（适用：含结构路径的模型——SEM、路径分析）
<System.ComponentModel.Composition.Export(GetType(IPlugin))>
Public Class CustomCode
    Implements IPlugin

    Private Const PLUGIN_NAME As String = "SEM Report"
    Private Const PLUGIN_VERSION As String = "1.0.0"


    Public Function Name() As String Implements IPlugin.Name
        Return PluginInfo.MenuPrefix & PLUGIN_NAME
    End Function

    Public Function Description() As String Implements IPlugin.Description
        Return "结构模型论文表：拟合、路径与R²合表；选定X/Y后输出所需效应与同次Bootstrap差值区间。竞争模型与描述相关表按任务选择，一键复制Word。"
    End Function

    Public Function Mainsub() As Integer Implements IPlugin.Mainsub
        Dim oldCursor As Cursor=Cursor.Current
        Try
            Cursor.Current=Cursors.WaitCursor
            Dim m As ModelData=Collector.Run()
            Paper.RequireModel(m)
            Dim kind As ModelKind=ModelKind.Detect(m)
            If kind.Kind<>ModelKind.SEM AndAlso kind.Kind<>ModelKind.PATH Then Throw New InvalidOperationException("请在含结构路径的模型上运行SEM Report。")
            Cursor.Current=oldCursor
            Dim competeCount As Integer=0
            Try
                Dim probeNames() As String=Nothing,probeTexts() As String=Nothing
                pd.GetModels(probeNames,probeTexts)
                If probeNames IsNot Nothing Then
                    For i As Integer=0 To probeNames.Length-1
                        If probeNames(i) IsNot Nothing AndAlso probeNames(i).Trim()<>"" Then competeCount+=1
                    Next
                End If
            Catch
            End Try
            Dim auto As Dictionary(Of String,String)=PaperOptions.ReadTestOptions("SEM_Report")
            Dim effects As Boolean=False,describe As Boolean=False,compete As Boolean=False,specs As New List(Of PaperEffectSpec)()
            If auto IsNot Nothing Then
                effects=PaperOptions.Flag(auto,"effects") : describe=PaperOptions.Flag(auto,"describe") : compete=PaperOptions.Flag(auto,"compete")
                specs=PaperOptions.EffectBatch(auto)
            Else
                Using dlg As New PaperSemDialog(m,competeCount)
                    If dlg.ShowDialog()<>DialogResult.OK Then Return 0
                    effects=dlg.EffectCheck.Checked : describe=dlg.DescribeCheck.Checked : compete=dlg.CompeteCheck.Checked : specs=dlg.Specs()
                End Using
            End If
            Cursor.Current=Cursors.WaitCursor
            Dim tables As New List(Of RTable)(),notes As New List(Of String)(m.Notes)
            If compete Then
                Dim names() As String=Nothing,texts() As String=Nothing,validNames As New List(Of String)(),validTexts As New List(Of String)()
                pd.GetModels(names,texts)
                If names IsNot Nothing Then
                    For i As Integer=0 To names.Length-1
                        If names(i) Is Nothing OrElse names(i).Trim()="" Then Continue For
                        validNames.Add(names(i)) : validTexts.Add(If(texts IsNot Nothing AndAlso i<texts.Length AndAlso texts(i) IsNot Nothing,texts(i),""))
                    Next
                End If
                If validNames.Count<2 Then Throw New ArgumentException("Manage Models中至少需要两个理论模型。")
                tables.Add(PaperSemX.Competition(SemModels.Run(validNames.ToArray(),validTexts.ToArray(),AddressOf SetupFromDiagram,m),m))
            Else
                tables.Add(Paper.Fit(m,"结构模型","Structural model"))
            End If
            tables.Add(Paper.Paths(m))
            If effects Then
                Collector.BootPass(m,specs(0).BootN,specs(0).Seed)
                tables.Add(PaperSem.Batch(m,specs))
            End If
            If describe Then
                Dim facs As List(Of Factor)=Calc.FindFactors(m,notes)
                tables.Add(PaperData.Describe(m,facs))
            End If
            PaperHtml.Save(m,"SEM_Report","结构模型论文结果",tables,notes)
            Return 0
        Catch ex As Exception
            MessageBox.Show(ex.Message,"SEM Report") : Return 1
        Finally
            Cursor.Current=oldCursor
        End Try
    End Function

    ' 把当前路径图的模型交给引擎（竞争模型比较用）
    Private Sub SetupFromDiagram(ByVal sem As AmosEngine)
        pd.SpecifyModel(sem)
    End Sub
End Class

Friend Class PaperAssets
Public Const Css As String = "body{margin:0;color:#111;background:#fff;font:16px/1.65 'Times New Roman',SimSun,serif}" & vbLf & ".doc,.bar,.table-block,.paper-content,.table-wrap,.interp-card,.copy-tools,.check-section,.check-block,.prose-box,.prose-text{box-sizing:border-box;max-width:100%}" & vbLf & ".doc{max-width:1140px;margin:32px auto;padding:0 28px 60px}" & vbLf & ".bar{position:sticky;top:0;background:white;border-bottom:1px solid #ccc;padding:10px 24px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;z-index:3;font:14px 'Microsoft YaHei',sans-serif}" & vbLf & "button{cursor:pointer;background:white;border:1px solid #999;padding:6px 12px;font:14px 'Microsoft YaHei',sans-serif;border-radius:3px}" & vbLf & "button:hover{background:#f3f4f6}" & vbLf & ".bar button.on{background:#222;color:white;border-color:#222}" & vbLf & "h1{font-size:25px;font-weight:bold;margin:24px 0 12px}" & vbLf & ".meta,.status{font-size:14px;color:#444}" & vbLf & ".table-block{margin:28px 0 40px}" & vbLf & ".copy-tools{font:13px 'Microsoft YaHei',sans-serif;margin-bottom:12px;display:flex;gap:10px 12px;align-items:center;flex-wrap:wrap}" & vbLf & ".table-no{font-weight:bold;margin:0 0 12px}" & vbLf & ".table-title{font-style:italic;margin:0 0 12px}" & vbLf & ".table-wrap{overflow-x:auto;max-width:100%}" & vbLf & "table.paper{border-collapse:collapse;width:100%;table-layout:fixed;font-size:16px;line-height:1.45}" & vbLf & "table.paper th,table.paper td{font-weight:normal;text-align:center;vertical-align:middle;padding:6px 5px;border:none;overflow-wrap:normal}" & vbLf & "table.paper thead tr:first-child th{border-top:1.5pt solid black}" & vbLf & "table.paper thead{border-bottom:.75pt solid black}" & vbLf & "table.paper tbody{border-bottom:1.5pt solid black}" & vbLf & ".note{font-size:15px;margin:10px 0 0;line-height:1.6}" & vbLf & ".en{display:none}" & vbLf & "body.lang-en .en{display:inline}" & vbLf & "body.lang-en .zh{display:none}" & vbLf & ".interp-card{margin-top:14px;padding:14px 18px;background:#f8fafc;border:1px solid #e2e8f0;border-left:3.5px solid #2b4c7e;border-radius:4px;font:14px/1.65 'Microsoft YaHei','PingFang SC',sans-serif;color:#1e293b}" & vbLf & ".interp-head{font-weight:bold;font-size:14px;color:#0f172a;margin:0 0 8px}" & vbLf & ".interp-list{list-style:none;margin:0;padding:0}" & vbLf & ".interp-item{display:flex;align-items:flex-start;gap:8px;margin:6px 0}" & vbLf & ".interp-text{flex:1 1 auto;min-width:0}" & vbLf & ".badge{display:inline-block;flex:0 0 auto;font-size:12px;font-weight:bold;padding:1px 7px;border-radius:3px;line-height:1.45;margin-top:2px;white-space:nowrap}" & vbLf & ".badge-ok{background:#e6f4ea;color:#137333;border:1px solid #a8dab5}" & vbLf & ".badge-warn{background:#fef7e0;color:#b06000;border:1px solid #fdd663}" & vbLf & ".badge-info{background:#e8f0fe;color:#1967d2;border:1px solid #aecbfa}" & vbLf & ".prose-box{margin-top:12px;padding-top:10px;border-top:1px dashed #cbd5e1}" & vbLf & ".prose-label{font-weight:bold;font-size:13px;color:#334155;margin-bottom:5px}" & vbLf & ".prose-text{margin:0;font:15px/1.7 'Times New Roman',SimSun,serif;color:#111;background:#fff;padding:8px 12px;border:1px solid #e2e8f0;border-radius:3px}" & vbLf & "body.hide-interp .interp-card{display:none}" & vbLf & ".check-section{margin-top:42px;padding-top:20px;border-top:2px solid #cbd5e1;font-family:'Microsoft YaHei','PingFang SC',sans-serif}" & vbLf & ".check-section h2{font-size:19px;margin:0 0 16px;color:#0f172a}" & vbLf & ".check-block{margin:0 0 26px;padding:16px 18px;background:#fafafa;border:1px solid #d4d4d8;border-radius:4px}" & vbLf & ".check-block h3{font-size:16px;margin:0 0 8px;color:#18181b}" & vbLf & ".check-lead{margin:0 0 10px;font-size:14px;color:#334155}" & vbLf & ".check-block .interp-list{margin-bottom:12px}" & vbLf & "table.check-table{border-collapse:collapse;width:100%;font-size:13.5px;line-height:1.5;background:#fff;border:1px solid #cbd5e1}" & vbLf & "table.check-table th,table.check-table td{border:1px solid #e2e8f0;padding:6px 10px;text-align:left;vertical-align:top}" & vbLf & "table.check-table thead th{background:#f1f5f9;font-weight:bold;color:#1e293b}" & vbLf & "table.check-table td.lv-must{color:#b00020;font-weight:bold;white-space:nowrap}" & vbLf & "table.check-table td.lv-sug{color:#8a5a00;font-weight:bold;white-space:nowrap}" & vbLf & "table.check-table td.lv-pass{color:#1a6b1a;white-space:nowrap}" & vbLf & ".check-notes{margin-top:10px;font-size:13px;color:#475569;line-height:1.6}" & vbLf & ".check-notes p{margin:4px 0}" & vbLf & "details{margin-top:28px;font-size:14px}" & vbLf & "details li{margin:6px 0}" & vbLf & ".plot svg{max-width:750px;width:100%}" & vbLf & "@media(max-width:720px){.doc{padding:0 14px}.doc,.bar,.interp-card,.prose-text,.copy-tools,.check-section,.check-block,.meta{word-break:break-word;overflow-wrap:anywhere}.table-wrap{overflow-x:auto}table.paper{min-width:650px}table.check-table{min-width:520px}.bar{padding:8px 12px;gap:6px}.bar button{padding:5px 9px;font-size:13px}h1{font-size:22px}.interp-card,.check-block{padding:12px}}" & vbLf & "@media print{.bar,.copy-tools,details,.meta,button{display:none!important}.doc{max-width:none;margin:0;padding:0}.table-block,.interp-card,.check-block{break-inside:avoid}.table-wrap{overflow:visible}table.paper{font-size:10.5pt;min-width:0}table.check-table{min-width:0;font-size:9.5pt}.note{font-size:10.5pt}.table-no,.table-title{break-after:avoid}}"
Public Const Js As String = "var paperLanguage='zh';" & vbLf & "function paperSetLanguage(lang){" & vbLf & " paperLanguage=lang==='en'?'en':'zh';" & vbLf & " document.body.classList.remove('lang-zh','lang-en');" & vbLf & " document.body.classList.add('lang-'+paperLanguage);" & vbLf & " document.querySelectorAll('[data-lang]').forEach(function(b){b.classList.toggle('on',b.dataset.lang===paperLanguage)});" & vbLf & " var tb=document.querySelector('button[onclick*=""paperToggleInterp""]');" & vbLf & " if(tb){var hid=document.body.classList.contains('hide-interp');tb.textContent=paperLanguage==='en'?(hid?'Show Interpretation':'Hide Interpretation'):(hid?'显示统计解读':'隐藏统计解读');}" & vbLf & " try{localStorage.setItem('amosPaperLanguage',paperLanguage)}catch(e){}" & vbLf & "}" & vbLf & "function paperCopyContent(block){" & vbLf & " var c=block.cloneNode(true);" & vbLf & " c.querySelectorAll(paperLanguage==='en'?'.zh':'.en').forEach(function(x){x.remove()});" & vbLf & " c.querySelectorAll('button,.copy-tools,[hidden]').forEach(function(x){x.remove()});" & vbLf & " c.querySelectorAll('.table-wrap').forEach(function(x){x.style.cssText='overflow:visible;'});" & vbLf & " c.querySelectorAll('table.paper').forEach(function(t){" & vbLf & "  t.style.cssText='border-collapse:collapse;table-layout:fixed;width:100%;font-family:Times New Roman,SimSun;font-size:10.5pt;';t.setAttribute('width','100%');" & vbLf & "  var widths=Array.from(t.querySelectorAll('col'),function(x){return parseFloat(x.style.width)});" & vbLf & "  t.querySelectorAll('th,td').forEach(function(x){x.style.cssText='border:none;padding:5pt 3pt;text-align:center;font-weight:normal;vertical-align:middle;';var p=document.createElement('p');p.style.cssText='margin:0;';if(x.closest('thead'))p.style.pageBreakAfter='avoid';while(x.firstChild)p.appendChild(x.firstChild);x.appendChild(p)});" & vbLf & "  t.querySelectorAll('tr').forEach(function(row){row.style.pageBreakInside='avoid'});" & vbLf & "  [t.tHead].concat(Array.from(t.tBodies)).forEach(function(section){var occupied=widths.map(function(){return 0});Array.from(section.rows).forEach(function(row){var col=0;Array.from(row.cells).forEach(function(cell){while(occupied[col]>0)col++;var n=cell.colSpan,w=widths.slice(col,col+n).reduce(function(a,b){return a+b},0);cell.style.width=w+'%';cell.setAttribute('width',w+'%');for(var j=col;j<col+n;j++)occupied[j]=cell.rowSpan;col+=n});occupied=occupied.map(function(n){return Math.max(0,n-1)})})});" & vbLf & "  Array.from(t.tHead.rows).forEach(function(row,r){Array.from(row.cells).forEach(function(cell){if(r===0)cell.style.borderTop='1.5pt solid black';if(r+cell.rowSpan===t.tHead.rows.length)cell.style.borderBottom='.75pt solid black'})});" & vbLf & "  Array.from(t.tBodies[0].rows).forEach(function(row,r){Array.from(row.cells).forEach(function(cell){if(r+cell.rowSpan===t.tBodies[0].rows.length)cell.style.borderBottom='1.5pt solid black'})});" & vbLf & " });" & vbLf & " c.querySelectorAll('.table-no').forEach(function(x){x.style.cssText='font-family:Times New Roman,SimSun;font-size:11pt;font-weight:bold;margin:12pt 0 8pt;page-break-after:avoid;'});" & vbLf & " c.querySelectorAll('.table-title').forEach(function(x){x.style.cssText='font-family:Times New Roman,SimSun;font-size:11pt;font-style:italic;margin:0 0 8pt;page-break-after:avoid;'});" & vbLf & " c.querySelectorAll('.note').forEach(function(x){x.style.cssText='font-family:Times New Roman,SimSun;font-size:10.5pt;line-height:1.5;margin:8pt 0 14pt;'});" & vbLf & " return {html:c.innerHTML,text:c.innerText||c.textContent};" & vbLf & "}" & vbLf & "async function paperCopy(id){" & vbLf & " var b;if(id==='all'){b=document.createElement('div');document.querySelectorAll('.paper-content').forEach(function(x){b.appendChild(x.cloneNode(true))})}else b=document.getElementById('paper-'+id);" & vbLf & " var result=paperCopyContent(b),ok=false;" & vbLf & " var listener=function(e){e.clipboardData.setData('text/html',result.html);e.clipboardData.setData('text/plain',result.text);e.preventDefault();ok=true};" & vbLf & " document.addEventListener('copy',listener);try{document.execCommand('copy')}finally{document.removeEventListener('copy',listener)}" & vbLf & " if(!ok&&navigator.clipboard&&window.ClipboardItem){try{await navigator.clipboard.write([new ClipboardItem({'text/html':new Blob([result.html],{type:'text/html'}),'text/plain':new Blob([result.text],{type:'text/plain'})})]);ok=true}catch(e){}}" & vbLf & " document.getElementById('copy-status-'+id).textContent=ok?(paperLanguage==='en'?'Copied for Word':'已复制，可粘贴到Word'):(paperLanguage==='en'?'Select the table and copy':'请选择表格后复制');" & vbLf & "}" & vbLf & "async function paperCopyPlain(text,statusId,okMsgZh,okMsgEn){" & vbLf & " var ok=false;" & vbLf & " var listener=function(e){e.clipboardData.setData('text/plain',text);e.preventDefault();ok=true};" & vbLf & " document.addEventListener('copy',listener);try{document.execCommand('copy')}finally{document.removeEventListener('copy',listener)}" & vbLf & " if(!ok&&navigator.clipboard&&navigator.clipboard.writeText){try{await navigator.clipboard.writeText(text);ok=true}catch(e){}}" & vbLf & " var st=document.getElementById('copy-status-'+statusId);" & vbLf & " if(st)st.textContent=ok?(paperLanguage==='en'?okMsgEn:okMsgZh):(paperLanguage==='en'?'Copy failed; select text manually':'复制失败，请手动选中复制');" & vbLf & "}" & vbLf & "function paperExtractProse(el){" & vbLf & " if(!el)return '';" & vbLf & " var sp=el.querySelector(paperLanguage==='en'?'.en':'.zh');" & vbLf & " var t=((sp||el).innerText||(sp||el).textContent||'').trim();" & vbLf & " return t;" & vbLf & "}" & vbLf & "function paperCopyProse(id){" & vbLf & " var el=document.getElementById('prose-'+id);" & vbLf & " var t=paperExtractProse(el);" & vbLf & " if(!t)return;" & vbLf & " paperCopyPlain(t,id,'已复制结果行文','Prose copied');" & vbLf & "}" & vbLf & "function paperCopyAllProse(){" & vbLf & " var parts=[];" & vbLf & " document.querySelectorAll('.prose-text').forEach(function(el){" & vbLf & "  if(el.closest('[hidden]'))return;" & vbLf & "  var blk=el.closest('.table-block');" & vbLf & "  if(blk&&blk.hidden)return;" & vbLf & "  var t=paperExtractProse(el);" & vbLf & "  if(t)parts.push(t);" & vbLf & " });" & vbLf & " if(!parts.length)return;" & vbLf & " paperCopyPlain(parts.join('\n\n'),'all','已复制全部结果行文','All prose copied');" & vbLf & "}" & vbLf & "function paperToggleInterp(btn){" & vbLf & " var hid=document.body.classList.toggle('hide-interp');" & vbLf & " if(btn)btn.textContent=paperLanguage==='en'?(hid?'Show Interpretation':'Hide Interpretation'):(hid?'显示统计解读':'隐藏统计解读');" & vbLf & "}" & vbLf & "try{paperSetLanguage(localStorage.getItem('amosPaperLanguage')||'zh')}catch(e){paperSetLanguage('zh')}" & vbLf & ""
End Class
