import { getTools } from '@/editor/indexeddb/joins'
import {
  type JoinedTool,
  type JoinedToolResponse,
} from '@/editor/indexeddb/types'
import { isEmpty, pickBy } from 'lodash'
import { generateContent, generateControl } from './shared'

const generateToolResponses = async (toolResponses: JoinedToolResponse[]) => {
  const generatedResponses = await Promise.all(
    toolResponses.map(async toolResponse =>
      pickBy({
        param: toolResponse.parameter,
        regex: toolResponse.isRegex,
        time: toolResponse.time,
        content: await generateContent(
          `tr_${toolResponse.id}`,
          toolResponse.content,
          toolResponse.file
        ),
        control: generateControl(
          toolResponse.activateMilestone,
          toolResponse.milestoneConditionWithNames
        ),
      })
    )
  )

  return isEmpty(generatedResponses) ? undefined : generatedResponses
}

export const generateTools = async () => {
  const tools = await getTools()
  const generatedTools = await Promise.all(
    tools.map(async (tool: JoinedTool) =>
      pickBy({
        name: tool.name,
        tooltip_description: tool.tooltipDescription,
        hint: tool.hint,
        default_response: tool.defaultResponse,
        responses: await generateToolResponses(tool.toolResponses),
      })
    )
  )

  return isEmpty(generatedTools) ? undefined : generatedTools
}
