import { agent } from '@repo/api-service'
import { load as parseYaml } from 'js-yaml'

import type { INodeType } from '@/nodes/Interface'
import { registerDynamicNodes } from '@/nodes'
import { toCustomNodeType, type CustomNodeSource } from './parser'

const normalizeSource = (item: unknown): CustomNodeSource | null => {
	if (!item) return null

	if (typeof item === 'string') {
		try {
			const parsed = parseYaml(item)
			if (parsed && typeof parsed === 'object') {
				return parsed as CustomNodeSource
			}
		} catch (error) {
			console.warn('[custom-node] yaml parse failed', error)
		}
		return null
	}

	if (typeof item === 'object') {
		return item as CustomNodeSource
	}

	return null
}

const toDynamicNodes = (rawList: unknown[]): INodeType[] => {
	const nodes: INodeType[] = []
	for (const item of rawList) {
		const source = normalizeSource(item)
		if (!source) continue
		const node = toCustomNodeType(source)
		if (node) nodes.push(node)
	}
	return nodes
}

export const initializeCustomNodes = async () => {
	try {
		const response = await agent.postAgentGetSupportCustomAgentNodeYamlList({})
		if (!response?.isSuccess) {
			console.warn('[custom-node] backend returned unsuccessful response')
			return
		}

		const rawList = Array.isArray(response?.result) ? response.result : []
		const dynamicNodes = toDynamicNodes(rawList as unknown[])
		if (!dynamicNodes.length) return

		registerDynamicNodes(dynamicNodes)
	} catch (error) {
		console.error('[custom-node] initialize failed', error)
	}
}
