/**
 * 字段树构建工具
 * 从 JSON Schema 构建字段路径树，用于字段映射选择器
 */

import type { FieldPathNode, JSONSchemaProperty } from '#/types/workflow'

/**
 * 从 JSON Schema 构建字段树
 * @param schema JSON Schema
 * @param maxDepth 最大展开深度（默认 3）
 * @returns 字段路径节点列表
 */
export function buildFieldTree(
  schema: JSONSchemaProperty,
  maxDepth: number = 3,
): FieldPathNode[] {
  return buildFieldTreeRecursive(schema, '', [], 0, maxDepth)
}

/**
 * 递归构建字段树
 */
function buildFieldTreeRecursive(
  schema: JSONSchemaProperty,
  currentPath: string,
  pathSegments: string[],
  depth: number,
  maxDepth: number,
): FieldPathNode[] {
  const nodes: FieldPathNode[] = []

  // 达到最大深度或没有子属性
  if (depth >= maxDepth || !schema.properties) {
    return nodes
  }

  // 遍历所有属性
  for (const [key, value] of Object.entries(schema.properties)) {
    const newPath = currentPath ? `${currentPath}.${key}` : key
    const newPathSegments = [...pathSegments, key]

    const node: FieldPathNode = {
      name: key,
      path: newPath,
      type: value.type,
      description: value.description,
      children: [],
    }

    // 如果是对象或数组，递归构建子节点
    if (value.type === 'object' && value.properties) {
      node.children = buildFieldTreeRecursive(
        value,
        newPath,
        newPathSegments,
        depth + 1,
        maxDepth,
      )
    } else if (value.type === 'array' && value.items) {
      // 数组项
      const itemSchema = value.items as JSONSchemaProperty
      if (itemSchema.type === 'object' && itemSchema.properties) {
        // 对于数组项，使用 [0] 作为示例路径
        node.children = buildFieldTreeRecursive(
          itemSchema,
          `${newPath}[0]`,
          [...newPathSegments, '[0]'],
          depth + 1,
          maxDepth,
        )
      }
    }

    nodes.push(node)
  }

  return nodes
}

/**
 * 从节点元数据构建输出字段树
 * @param nodeId 节点 ID
 * @param nodeName 节点名称
 * @param outputSchema 输出 Schema
 * @param maxDepth 最大深度
 */
export function buildOutputFieldTree(
  nodeId: string,
  nodeName: string,
  outputSchema: JSONSchemaProperty,
  maxDepth: number = 3,
): FieldPathNode {
  const outputNode: FieldPathNode = {
    name: 'output',
    path: 'output',
    type: 'object',
    description: '节点输出',
    children: buildFieldTree(outputSchema, maxDepth),
  }

  return {
    name: `${nodeName} (${nodeId})`,
    path: nodeId,
    type: 'object',
    description: '节点数据',
    children: [outputNode],
  }
}

/**
 * 扁平化字段树为路径列表
 * @param tree 字段树
 * @returns 路径列表
 */
export function flattenFieldTree(tree: FieldPathNode[]): string[] {
  const paths: string[] = []

  function traverse(node: FieldPathNode) {
    paths.push(node.path)
    if (node.children && node.children.length > 0) {
      node.children.forEach(traverse)
    }
  }

  tree.forEach(traverse)
  return paths
}

/**
 * 在字段树中查找节点
 * @param tree 字段树
 * @param path 路径
 */
export function findNodeInTree(
  tree: FieldPathNode[],
  path: string,
): FieldPathNode | null {
  for (const node of tree) {
    if (node.path === path) {
      return node
    }
    if (node.children && node.children.length > 0) {
      const found = findNodeInTree(node.children, path)
      if (found) return found
    }
  }
  return null
}

/**
 * 获取字段的完整描述
 * @param node 字段节点
 */
export function getFieldDescription(node: FieldPathNode): string {
  const parts = [node.name]
  if (node.type) {
    parts.push(`(${node.type})`)
  }
  if (node.description) {
    parts.push(`- ${node.description}`)
  }
  return parts.join(' ')
}

