package commerce

import (
	"context"
	"fmt"
	"strings"
	"time"

	"qycw/go-server/internal/plugins"
)

var diagnosticCapabilities = []string{
	plugins.CapabilityEmail,
	plugins.CapabilitySMS,
	plugins.CapabilityVerification,
	plugins.CapabilityPayment,
}

func (s *Service) AdminPluginDiagnostics(ctx context.Context) (map[string]any, error) {
	data := emptyPluginDiagnostics()
	warnings := []map[string]any{}
	if s.plugins == nil {
		warnings = append(warnings, diagnosticWarning("error", "插件运行环境", "插件运行环境未启用", "请检查 GO_PLUGIN_DIRS 配置并重启 API 服务。", "/admin/notification-plugins"))
		return finishPluginDiagnostics(data, warnings), nil
	}
	if err := s.plugins.Refresh(ctx); err != nil {
		warnings = append(warnings, diagnosticWarning("error", "插件运行环境", "插件目录刷新失败", err.Error(), "/admin/notification-plugins"))
		return finishPluginDiagnostics(data, warnings), nil
	}

	manifests, err := s.plugins.ListAll(ctx, "")
	if err != nil {
		warnings = append(warnings, diagnosticWarning("error", "插件运行环境", "插件清单读取失败", err.Error(), "/admin/notification-plugins"))
		manifests = []plugins.Manifest{}
	}
	selection, err := s.adminPluginSelection(ctx)
	if err != nil {
		warnings = append(warnings, diagnosticWarning("error", "插件配置", "当前插件选择读取失败", err.Error(), "/admin/notification-plugins"))
		selection = adminPluginSelection{
			featureProviders: map[string]string{},
			featureEnabled:   map[string]bool{},
			paymentEnabled:   map[string]bool{},
		}
	}
	channels, channelWarnings, enabledCount := s.diagnosticChannels(ctx, manifests, selection)
	data["channels"] = channels
	warnings = append(warnings, channelWarnings...)

	provision, provisionWarnings, security, securityWarnings, err := s.diagnosticProvision(ctx, manifests)
	if err != nil {
		warnings = append(warnings, diagnosticWarning("error", "开通巡检", "开通巡检数据读取失败", err.Error(), "/admin/provision-plugins"))
		provision = data["provision"].(map[string]any)
		security = data["security"].(map[string]any)
	}
	data["provision"] = provision
	data["security"] = security
	warnings = append(warnings, provisionWarnings...)
	warnings = append(warnings, securityWarnings...)

	verification, verificationWarnings, err := s.diagnosticVerification(ctx)
	if err != nil {
		warnings = append(warnings, diagnosticWarning("error", "实名巡检", "实名巡检数据读取失败", err.Error(), "/admin/users"))
		verification = data["verification"].(map[string]any)
	}
	data["verification"] = verification
	warnings = append(warnings, verificationWarnings...)

	provisionSummary := provision["summary"].(map[string]any)
	securitySummary := security
	data["summary"] = map[string]any{
		"generated_at":                   time.Now().UTC().Format(time.RFC3339),
		"total_plugins":                  len(manifests),
		"notification_plugins":           diagnosticManifestCount(manifests, diagnosticCapabilities),
		"provision_plugins":              diagnosticManifestCount(manifests, []string{plugins.CapabilityProvision}),
		"enabled_plugins":                enabledCount + diagnosticIntFromAny(provisionSummary["enabled_interfaces"]),
		"recent_failed_instances":        diagnosticIntFromAny(provisionSummary["failed_instances"]),
		"pending_redirect_verifications": diagnosticIntFromAny(verification["pending_redirect"]),
		"product_binding_issues":         diagnosticIntFromAny(provisionSummary["product_binding_issues"]),
		"plaintext_secret_count":         diagnosticIntFromAny(securitySummary["plaintext_secret_count"]),
	}
	return finishPluginDiagnostics(data, warnings), nil
}

func emptyPluginDiagnostics() map[string]any {
	return map[string]any{
		"summary": map[string]any{}, "warnings": []map[string]any{}, "channels": []map[string]any{},
		"provision":    map[string]any{"summary": map[string]any{"plugin_count": 0, "interface_count": 0, "enabled_interfaces": 0, "product_count": 0, "active_product_count": 0, "product_binding_issues": 0, "failed_instances": 0, "stuck_provisioning": 0}, "plugins": []map[string]any{}, "interfaces": []map[string]any{}, "product_issues": []map[string]any{}, "recent_failures": []map[string]any{}, "instance_status_counts": map[string]int{}, "actions": diagnosticActions("/admin/provision-plugins", "配置开通插件")},
		"verification": map[string]any{"pending_redirect": 0, "processing_records": []map[string]any{}, "status_counts": map[string]int{}, "actions": diagnosticActions("/admin/notification-plugins", "配置实名插件")},
		"security":     map[string]any{"secret_count": 0, "encrypted_secret_count": 0, "plaintext_secret_count": 0, "items": []map[string]any{}},
	}
}

func finishPluginDiagnostics(data map[string]any, warnings []map[string]any) map[string]any {
	errors, notices := 0, 0
	for _, warning := range warnings {
		if warning["level"] == "error" {
			errors++
		} else {
			notices++
		}
	}
	summary, _ := data["summary"].(map[string]any)
	if summary == nil {
		summary = map[string]any{}
	}
	summary["issue_count"], summary["error_count"], summary["warning_count"] = errors+notices, errors, notices
	data["summary"], data["warnings"] = summary, warnings
	return data
}

func (s *Service) diagnosticChannels(ctx context.Context, manifests []plugins.Manifest, selection adminPluginSelection) ([]map[string]any, []map[string]any, int) {
	channels, warnings, enabledTotal := make([]map[string]any, 0, len(diagnosticCapabilities)), []map[string]any{}, 0
	for _, capability := range diagnosticCapabilities {
		items := diagnosticManifests(manifests, capability)
		current := []map[string]any{}
		enabled := []map[string]any{}
		missingFields := []map[string]any{}
		channelWarnings := []string{}
		selectedIDs := map[string]bool{}
		if capability == plugins.CapabilityPayment {
			selectedIDs = selection.paymentEnabled
		} else if id := selection.featureProviders[capability]; id != "" {
			selectedIDs[id] = true
		}
		featureEnabled := selection.featureEnabled[capability]
		if capability == plugins.CapabilityPayment {
			featureEnabled = len(selectedIDs) > 0
		}
		for _, manifest := range items {
			if !selectedIDs[manifest.ID] {
				continue
			}
			current = append(current, diagnosticPluginLite(manifest, true, manifest.Enabled && featureEnabled))
			if manifest.Enabled && featureEnabled {
				enabled = append(enabled, diagnosticPluginLite(manifest, true, true))
				enabledTotal++
				config, err := s.effectiveAdminPluginConfig(ctx, manifest)
				if err != nil {
					channelWarnings = append(channelWarnings, "插件配置读取失败："+err.Error())
					continue
				}
				missingFields = append(missingFields, diagnosticMissingFields(manifest, config)...)
			}
		}
		for id := range selectedIDs {
			if !diagnosticHasManifest(items, id) {
				channelWarnings = append(channelWarnings, "已选择的插件未安装："+id)
			}
		}
		status := "disabled"
		if len(channelWarnings) > 0 || len(missingFields) > 0 {
			status = "error"
		} else if len(enabled) > 0 {
			status = "ok"
		}
		label := diagnosticCapabilityLabel(capability)
		channel := map[string]any{"type": capability, "label": label, "status": status, "total_plugins": len(items), "enabled_count": len(enabled), "current_count": len(current), "current_plugins": current, "enabled_plugins": enabled, "missing_required": missingFields, "warnings": channelWarnings, "actions": diagnosticActions("/admin/notification-plugins", "配置插件")}
		channels = append(channels, channel)
		if status == "error" {
			suggestions := append([]string{}, channelWarnings...)
			if len(missingFields) > 0 {
				suggestions = append(suggestions, "缺少必填项："+diagnosticFieldLabels(missingFields))
			}
			warnings = append(warnings, diagnosticWarning("error", "通知与业务通道", label+"插件配置异常", strings.Join(suggestions, "；"), "/admin/notification-plugins"))
		}
	}
	return channels, warnings, enabledTotal
}

func (s *Service) diagnosticProvision(ctx context.Context, manifests []plugins.Manifest) (map[string]any, []map[string]any, map[string]any, []map[string]any, error) {
	provisionManifests := diagnosticManifests(manifests, plugins.CapabilityProvision)
	manifestByID := map[string]plugins.Manifest{}
	for _, item := range provisionManifests {
		manifestByID[item.ID] = item
	}
	if s.db == nil {
		warning := diagnosticWarning("warning", "数据库", "数据库未启用，无法执行开通巡检", "启用数据库后可检查接口、商品绑定和失败实例。", "/admin/provision-plugins")
		return emptyPluginDiagnostics()["provision"].(map[string]any), []map[string]any{warning}, emptyPluginDiagnostics()["security"].(map[string]any), nil, nil
	}

	var interfaces []map[string]any
	if err := s.db.WithContext(ctx).Table("provision_interfaces").Order("id ASC").Find(&interfaces).Error; err != nil {
		return nil, nil, nil, nil, err
	}
	interfaceByID := map[int64]map[string]any{}
	interfaceRows, warnings := make([]map[string]any, 0, len(interfaces)), []map[string]any{}
	securityItems, encryptedSecrets, plaintextSecrets := []map[string]any{}, 0, 0
	for _, row := range interfaces {
		id, _ := int64FromAny(row["id"])
		interfaceByID[id] = row
		pluginID, manifest := stringFromMap(row, "plugin_id"), plugins.Manifest{}
		var exists bool
		if manifest, exists = manifestByID[pluginID]; !exists {
			manifest = plugins.Manifest{ID: pluginID, Name: pluginID}
		}
		config := diagnosticStoredConfig(row["config"])
		missing := []map[string]any{}
		issues := []string{}
		if !exists {
			issues = append(issues, "绑定的开通插件未安装")
		} else {
			missing = diagnosticMissingFields(manifest, config)
			if len(missing) > 0 {
				issues = append(issues, "缺少必填配置")
			}
		}
		enabled := truthy(row["enabled"])
		if !enabled {
			issues = append(issues, "接口已禁用")
		}
		lastTest, tested := diagnosticNullableBool(row["last_test_ok"])
		if enabled && tested && !lastTest {
			issues = append(issues, firstString(row["last_test_message"], "最近一次接口测试失败"))
		}
		if enabled && !tested {
			issues = append(issues, "接口尚未完成连通性测试")
		}
		status := "ok"
		if !enabled {
			status = "disabled"
		} else if !exists || len(missing) > 0 || (tested && !lastTest) {
			status = "error"
		} else if !tested {
			status = "warning"
		}
		interfaceRows = append(interfaceRows, map[string]any{"id": id, "name": stringFromMap(row, "name"), "plugin_id": pluginID, "plugin_name": firstString(manifest.Name, pluginID), "enabled": enabled, "status": status, "missing_required": missing, "warnings": issues, "last_test_ok": diagnosticOptionalBool(lastTest, tested), "last_test_message": row["last_test_message"], "updated_at": row["updated_at"]})
		if status == "error" || status == "warning" {
			warnings = append(warnings, diagnosticWarning(map[bool]string{true: "error", false: "warning"}[status == "error"], "开通接口", "开通接口 "+stringFromMap(row, "name")+" 需要处理", strings.Join(issues, "；"), "/admin/provision-plugins"))
		}
		items, encrypted, plaintext := diagnosticInterfaceSecrets(row, pluginID, stringFromMap(row, "name"))
		securityItems, encryptedSecrets, plaintextSecrets = append(securityItems, items...), encryptedSecrets+encrypted, plaintextSecrets+plaintext
	}

	var products []Product
	if err := s.db.WithContext(ctx).Where("api_type = ?", "plugin").Order("sort_order ASC, id DESC").Find(&products).Error; err != nil {
		return nil, nil, nil, nil, err
	}
	productIssues := diagnosticProductIssues(products, interfaceByID, manifestByID)
	for _, issue := range productIssues {
		warnings = append(warnings, diagnosticWarning("error", "商品绑定", "商品 "+stringFromMap(issue, "product_name")+" 的开通绑定异常", strings.Join(stringSliceFromAny(issue["issues"]), "；"), fmt.Sprintf("/admin/products/%d", diagnosticIntFromAny(issue["product_id"]))))
	}

	recentFailures, failedCount, statusCounts, err := s.diagnosticProvisionFailures(ctx)
	if err != nil {
		return nil, nil, nil, nil, err
	}
	if failedCount > 0 {
		warnings = append(warnings, diagnosticWarning("error", "开通实例", "存在开通失败实例", "修复对应配置后，再确认是否需要重新开通。", "/admin/instances"))
	}
	var stuckCount int64
	if err := s.db.WithContext(ctx).Model(&Instance{}).Joins("JOIN products ON products.id = instances.product_id").Where("products.api_type = ? AND instances.status = ? AND instances.updated_at <= ?", "plugin", "provisioning", time.Now().UTC().Add(-30*time.Minute)).Count(&stuckCount).Error; err != nil {
		return nil, nil, nil, nil, err
	}
	if stuckCount > 0 {
		warnings = append(warnings, diagnosticWarning("warning", "开通实例", "存在超过 30 分钟仍在开通中的实例", "请检查上游动作日志和任务执行状态。", "/admin/tasks"))
	}

	pluginRows := make([]map[string]any, 0, len(provisionManifests))
	for _, manifest := range provisionManifests {
		pluginRows = append(pluginRows, diagnosticProvisionPlugin(manifest, interfaces, products))
	}
	provision := map[string]any{"summary": map[string]any{"plugin_count": len(pluginRows), "interface_count": len(interfaceRows), "enabled_interfaces": diagnosticEnabledInterfaces(interfaces), "product_count": len(products), "active_product_count": diagnosticActiveProducts(products), "product_binding_issues": len(productIssues), "failed_instances": failedCount, "stuck_provisioning": stuckCount}, "plugins": pluginRows, "interfaces": interfaceRows, "product_issues": productIssues, "recent_failures": recentFailures, "instance_status_counts": statusCounts, "actions": diagnosticActions("/admin/provision-plugins", "配置开通插件")}
	security := map[string]any{"secret_count": len(securityItems), "encrypted_secret_count": encryptedSecrets, "plaintext_secret_count": plaintextSecrets, "items": securityItems}
	securityWarnings := []map[string]any{}
	if plaintextSecrets > 0 {
		securityWarnings = append(securityWarnings, diagnosticWarning("error", "安全", "发现明文插件密钥", "请重新保存开通接口配置，使密钥字段以加密方式存储。", "/admin/plugin-diagnostics"))
	}
	return provision, warnings, security, securityWarnings, nil
}

func (s *Service) diagnosticVerification(ctx context.Context) (map[string]any, []map[string]any, error) {
	if s.db == nil {
		return emptyPluginDiagnostics()["verification"].(map[string]any), nil, nil
	}
	var pending int64
	if err := s.db.WithContext(ctx).Table("user_verification_records").Where("mode = ? AND status = ? AND provider_task_id IS NOT NULL", "face_redirect", "processing").Count(&pending).Error; err != nil {
		return nil, nil, err
	}
	var statusRows []struct {
		Status string
		Count  int
	}
	if err := s.db.WithContext(ctx).Table("user_verification_records").Select("status, COUNT(*) AS count").Group("status").Scan(&statusRows).Error; err != nil {
		return nil, nil, err
	}
	statusCounts := map[string]int{}
	for _, row := range statusRows {
		statusCounts[row.Status] = row.Count
	}
	var processing []map[string]any
	if err := s.db.WithContext(ctx).Table("user_verification_records AS r").Select("r.id, r.user_id, u.username, r.provider, r.mode, r.status, r.provider_task_id AS external_id, r.created_at, r.updated_at").Joins("LEFT JOIN users u ON u.id = r.user_id").Where("r.status IN ?", []string{"pending", "processing"}).Order("r.updated_at DESC").Limit(10).Find(&processing).Error; err != nil {
		return nil, nil, err
	}
	warnings := []map[string]any{}
	if pending > 0 {
		warnings = append(warnings, diagnosticWarning("warning", "实名认证", "存在仍在处理中的 H5 实名记录", "请检查实名插件回调地址及服务商回调投递情况。", "/admin/users"))
	}
	return map[string]any{"pending_redirect": pending, "processing_records": processing, "status_counts": statusCounts, "actions": diagnosticActions("/admin/notification-plugins", "配置实名插件")}, warnings, nil
}

func (s *Service) diagnosticProvisionFailures(ctx context.Context) ([]map[string]any, int64, map[string]int, error) {
	var failed int64
	if err := s.db.WithContext(ctx).Table("instances AS i").Joins("JOIN products AS product ON product.id = i.product_id").Where("product.api_type = ? AND i.status IN ?", "plugin", []string{"failed", "provision_failed"}).Count(&failed).Error; err != nil {
		return nil, 0, nil, err
	}
	var statusRows []struct {
		Status string
		Count  int
	}
	if err := s.db.WithContext(ctx).Table("instances AS i").Joins("JOIN products AS product ON product.id = i.product_id").Where("product.api_type = ?", "plugin").Select("i.status, COUNT(*) AS count").Group("i.status").Scan(&statusRows).Error; err != nil {
		return nil, 0, nil, err
	}
	statusCounts := map[string]int{}
	for _, row := range statusRows {
		statusCounts[row.Status] = row.Count
	}
	rows := []map[string]any{}
	err := s.db.WithContext(ctx).Table("instances AS i").Joins("JOIN products AS product ON product.id = i.product_id").Joins("JOIN orders AS o ON o.id = i.order_id").Joins("JOIN users AS u ON u.id = i.user_id").Where("product.api_type = ? AND i.status IN ?", "plugin", []string{"failed", "provision_failed"}).Select("i.id AS instance_id, i.product_id, product.name AS product_name, product.api_identifier AS plugin_id, i.order_id, o.out_order_no, i.user_id, u.username, i.status, i.provision_attempts AS attempts, i.last_provision_at, i.updated_at, i.provision_log").Order("i.updated_at DESC").Limit(10).Find(&rows).Error
	return rows, failed, statusCounts, err
}

func diagnosticManifests(all []plugins.Manifest, capability string) []plugins.Manifest {
	out := []plugins.Manifest{}
	for _, item := range all {
		if item.HasCapability(capability) {
			out = append(out, item)
		}
	}
	return out
}
func diagnosticManifestCount(all []plugins.Manifest, capabilities []string) int {
	count := 0
	for _, item := range all {
		for _, capability := range capabilities {
			if item.HasCapability(capability) {
				count++
				break
			}
		}
	}
	return count
}
func diagnosticHasManifest(items []plugins.Manifest, id string) bool {
	for _, item := range items {
		if item.ID == id {
			return true
		}
	}
	return false
}
func diagnosticPluginLite(item plugins.Manifest, current bool, enabled bool) map[string]any {
	return map[string]any{"id": item.ID, "type": primaryPluginCapability(item), "name": item.Name, "version": item.Version, "provider": firstString(item.Provider, "plugin:"+item.ID), "enabled": enabled, "current": current, "capabilities": item.Capabilities}
}
func diagnosticCapabilityLabel(capability string) string {
	labels := map[string]string{plugins.CapabilityEmail: "邮件", plugins.CapabilitySMS: "短信", plugins.CapabilityVerification: "实名认证", plugins.CapabilityPayment: "支付"}
	return labels[capability]
}
func diagnosticActions(path, label string) []map[string]any {
	return []map[string]any{{"path": path, "label": label}}
}
func diagnosticWarning(level, scope, message, suggestion, path string) map[string]any {
	return map[string]any{"level": level, "scope": scope, "message": message, "suggestion": suggestion, "path": path}
}
func diagnosticFieldLabels(fields []map[string]any) string {
	labels := make([]string, 0, len(fields))
	for _, field := range fields {
		labels = append(labels, stringFromMap(field, "label"))
	}
	return strings.Join(labels, ", ")
}
func diagnosticMissingFields(manifest plugins.Manifest, config map[string]any) []map[string]any {
	out := []map[string]any{}
	for _, item := range asSlice(pluginConfigFields(manifest.ConfigSchema)) {
		field, ok := item.(map[string]any)
		if !ok || !truthy(field["required"]) {
			continue
		}
		key := stringFromMap(field, "key")
		if key != "" && !diagnosticPresent(config[key]) {
			out = append(out, map[string]any{"plugin_id": manifest.ID, "plugin_name": manifest.Name, "key": key, "label": firstString(field["label"], key)})
		}
	}
	return out
}
func diagnosticPresent(value any) bool {
	switch v := value.(type) {
	case nil:
		return false
	case string:
		return strings.TrimSpace(v) != ""
	case []any:
		return len(v) > 0
	case map[string]any:
		return len(v) > 0
	default:
		return true
	}
}
func diagnosticStoredConfig(value any) map[string]any {
	stored := parseJSONMap(value)
	if values, ok := stored["values"].(map[string]any); ok {
		return values
	}
	return stored
}
func diagnosticNullableBool(value any) (bool, bool) {
	if value == nil {
		return false, false
	}
	switch v := value.(type) {
	case bool:
		return v, true
	case int64:
		return v != 0, true
	case int:
		return v != 0, true
	case []byte:
		return truthy(string(v)), true
	case string:
		return truthy(v), true
	default:
		return truthy(v), true
	}
}
func diagnosticOptionalBool(value bool, valid bool) any {
	if !valid {
		return nil
	}
	return value
}
func diagnosticEnabledInterfaces(rows []map[string]any) int {
	count := 0
	for _, row := range rows {
		if truthy(row["enabled"]) {
			count++
		}
	}
	return count
}
func diagnosticActiveProducts(rows []Product) int {
	count := 0
	for _, row := range rows {
		if row.Status == "active" {
			count++
		}
	}
	return count
}
func diagnosticIntFromAny(value any) int {
	if n, ok := int64FromAny(value); ok {
		return int(n)
	}
	return 0
}
func stringSliceFromAny(value any) []string {
	out := []string{}
	for _, item := range asSlice(value) {
		if text := firstString(item); text != "" {
			out = append(out, text)
		}
	}
	return out
}

func diagnosticProductIssues(products []Product, interfaces map[int64]map[string]any, manifests map[string]plugins.Manifest) []map[string]any {
	out := []map[string]any{}
	for _, product := range products {
		issues := []string{}
		pluginID := strings.TrimSpace(firstString(product.APIIdentifier))
		if pluginID == "" {
			issues = append(issues, "未选择开通插件")
		} else if _, ok := manifests[pluginID]; !ok {
			issues = append(issues, "选择的开通插件未安装")
		}
		var iface map[string]any
		if product.ProvisionInterfaceID == nil {
			issues = append(issues, "未绑定开通接口")
		} else {
			iface = interfaces[*product.ProvisionInterfaceID]
			if iface == nil {
				issues = append(issues, "绑定的开通接口不存在")
			} else {
				if !truthy(iface["enabled"]) {
					issues = append(issues, "绑定的开通接口已禁用")
				}
				if pluginID != "" && pluginID != stringFromMap(iface, "plugin_id") {
					issues = append(issues, "开通接口所属插件不一致")
				}
			}
		}
		if product.Status == "active" && !product.AutoProvision {
			issues = append(issues, "在售商品未开启自动开通")
		}
		if len(issues) > 0 {
			out = append(out, map[string]any{"product_id": product.ID, "product_name": product.Name, "sku": product.SKU, "status": product.Status, "auto_provision": product.AutoProvision, "plugin_id": diagnosticNullableString(pluginID), "interface_id": product.ProvisionInterfaceID, "issues": issues})
		}
	}
	return out
}

func diagnosticProvisionPlugin(manifest plugins.Manifest, interfaces []map[string]any, products []Product) map[string]any {
	interfacesTotal, interfacesEnabled, productsTotal, productsActive := 0, 0, 0, 0
	for _, row := range interfaces {
		if stringFromMap(row, "plugin_id") == manifest.ID {
			interfacesTotal++
			if truthy(row["enabled"]) {
				interfacesEnabled++
			}
		}
	}
	for _, product := range products {
		if strings.TrimSpace(firstString(product.APIIdentifier)) == manifest.ID {
			productsTotal++
			if product.Status == "active" {
				productsActive++
			}
		}
	}
	purchaseFields := []any{}
	if manifest.ProductPage != nil {
		purchaseFields = asSlice(manifest.ProductPage["purchase_fields"])
	}
	return map[string]any{"id": manifest.ID, "name": manifest.Name, "version": manifest.Version, "status": manifest.Status, "capabilities": manifest.Capabilities, "interface_count": interfacesTotal, "enabled_interface_count": interfacesEnabled, "product_count": productsTotal, "active_product_count": productsActive, "config_field_count": len(asSlice(pluginConfigFields(manifest.ConfigSchema))), "purchase_field_count": len(purchaseFields), "manage_action_count": len(manifest.ManageActions)}
}

func diagnosticInterfaceSecrets(row map[string]any, pluginID, interfaceName string) ([]map[string]any, int, int) {
	stored := parseJSONMap(row["config"])
	values := diagnosticStoredConfig(row["config"])
	items, encrypted, plaintext := []map[string]any{}, 0, 0
	for _, rawKey := range valuesFromAny(stored["secret_keys"]) {
		key := firstString(rawKey)
		if key == "" {
			continue
		}
		value := firstString(values[key])
		status := "plaintext"
		if strings.TrimSpace(value) == "" || value == "***" {
			status = "empty"
		} else if _, err := decryptStoredSecret(value); err == nil {
			status = "encrypted"
			encrypted++
		} else {
			plaintext++
		}
		items = append(items, map[string]any{"scope": "provision_interface", "key": key, "label": key, "plugin": pluginID, "interface_id": row["id"], "interface_name": interfaceName, "status": status})
	}
	return items, encrypted, plaintext
}

func diagnosticNullableString(value string) any {
	if value == "" {
		return nil
	}
	return value
}
