'use client'

import type { AppRouterInstance } from 'next/dist/shared/lib/app-router-context.shared-runtime'

export async function executeClientAction(
  tool: string,
  params: Record<string, any>,
  router: AppRouterInstance,
): Promise<{ success: boolean; message: string }> {
  if (!router) {
    return { success: false, message: 'Router not initialized' }
  }

  switch (tool) {
    case 'navigate':
      if (params.path) {
        router.push(params.path)
        return { success: true, message: `正在导航到：${params.description || params.path}` }
      }
      return { success: false, message: '导航路径无效' }

    case 'setModel':
      if (params.model) {
        sessionStorage.setItem('assistant-set-model', params.model)
        router.push('/sandbox')
        setTimeout(() => {
          window.dispatchEvent(new CustomEvent('assistant-set-model', { detail: params.model }))
        }, 500)
        return { success: true, message: `正在切换模型：${params.model}` }
      }
      return { success: false, message: '模型名称无效' }

    case 'startChat':
      if (params.prompt) {
        sessionStorage.setItem('assistant-start-chat', params.prompt)
        router.push('/sandbox')
        setTimeout(() => {
          window.dispatchEvent(new CustomEvent('assistant-start-chat', { detail: params.prompt }))
        }, 500)
        return { success: true, message: `正在开始对话：${params.prompt.slice(0, 20)}...` }
      }
      return { success: false, message: '对话内容无效' }

    case 'openSkill':
      if (params.skillId) {
        router.push(`/skills/${params.skillId}`)
        return { success: true, message: `正在打开技能：${params.description || params.skillId}` }
      }
      return { success: false, message: '技能 ID 无效' }

    case 'setParameter': {
      const storageParams: Record<string, string> = {}
      if (params.temperature !== undefined) storageParams.temperature = String(params.temperature)
      if (params.top_p !== undefined) storageParams.top_p = String(params.top_p)
      if (params.max_tokens !== undefined) storageParams.max_tokens = String(params.max_tokens)
      if (Object.keys(storageParams).length > 0) {
        sessionStorage.setItem('assistant-set-params', JSON.stringify(storageParams))
        router.push('/sandbox')
        setTimeout(() => {
          window.dispatchEvent(new CustomEvent('assistant-set-params', { detail: storageParams }))
        }, 500)
        return { success: true, message: `正在设置参数：${params.description}` }
      }
      return { success: false, message: '参数无效' }
    }

    default:
      return { success: false, message: '未知操作类型' }
  }
}
