/**
 * Nova SDK Kit 组件类型定义
 */

import { useNovaService } from './hooks/useNovaService'

// 事件类型常量
export const EventType = {
  UserInput: 'user_input',
  Message: 'message',
  ToolCall: 'tool_call',
  TaskUpdate: 'task_update',
  TaskEnd: 'task_end',
  Error: 'error',
} as const

// 事件类型联合类型
export type EventType = typeof EventType[keyof typeof EventType]

// 任务状态常量（与接口 task_status 一致：pending / in_progress / completed / stopped / paused / failed）
export const TaskStatus = {
  /** 等待开始 */
  PENDING: 'pending',
  /** 进行中 */
  IN_PROGRESS: 'in_progress',
  /** 已完成 */
  COMPLETED: 'completed',
  /** 已停止 */
  STOPPED: 'stopped',
  /** 暂停 */
  PAUSED: 'paused',
  /** 失败 */
  FAILED: 'failed',
  /** 已取消 */
  CANCELLED: 'cancelled',
} as const

// 任务状态联合类型
export type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus]

/** 终止态：遇到这些状态时关闭 loading（completed / stopped / failed / cancelled） */
export const TERMINAL_TASK_STATUS: TaskStatus[] = [
  TaskStatus.COMPLETED,
  TaskStatus.STOPPED,
  TaskStatus.FAILED,
  TaskStatus.CANCELLED,
  TaskStatus.PAUSED,
]

// 基础事件接口
export interface BaseEvent {
  event_id: string
  event_type: EventType | string
  /** 规范化后的 action_type，便于前端直接使用 */
  action_type?: string
  timestamp?: number
  content?: {
    text?: string
    action_type?: string
    metadata?: Record<string, unknown>
    tool_name?: string
    tool_input?: unknown
    tool_output?: unknown
    [key: string]: unknown
  }
  metadata?: {
    isUserInput?: boolean
    isTemp?: boolean
    agent_id?: string
    template_type?: string
    template_id?: string
    isTempSystemReply?: boolean
    is_summary?: boolean
    [key: string]: unknown
  }
  plan_step_state?: string
  event_status?: string
  stream?: boolean
}

// 消息内容
export interface MessageContent {
  content?: string
  text?: string
  refer_content?: string
}

// Action 信息（工具调用/操作）
export interface ActionInfo {
  name?: string
  arguments?: string[]
  action_type?: string
  block?: boolean
  tool_input?: unknown
  tool_output?: unknown
}

// 操作
export interface Operation {
  [key: string]: unknown
}

// MCP 内容
export interface McpContent {
  [key: string]: unknown
}

// 计划配置
export interface PlanConfig {
  steps?: Array<{
    id: string
    title: string
    status?: string
    [key: string]: unknown
  }>
  [key: string]: unknown
}

// Todo 列表配置
export interface TaskTodoConfig {
  list: Array<{
    id?: string
    title?: string
    status?: string
    [key: string]: unknown
  }>
}

// 用户交互（如选项、确认等）
export interface SlideQuestion {
  question: string
  type?: 'input' | 'single' | 'multiple'
  options?: string[]
  answer?: string
}

export interface UserInteraction {
  type?: string
  content?: string
  /** 选项按钮（choice 类型） */
  choice_options?: Array<string | { label: string; disabled?: boolean; tooltip?: string }>
  /** 幻灯片表单问题列表 */
  questions?: SlideQuestion[]
  /** 浏览器类型：sandbox / local_browser */
  browser_type?: string
  /** 授权类型（browser auth） */
  authorization_type?: string
  tool_code?: string
  event_id?: string
  origin_text?: string
  select_action?: string
  [key: string]: unknown
}

// 附件
export interface Attachment {
  file_name: string
  file_type: string
  file_url: string
  path?: string
  file_id?: string
}

// 图片附件
export interface ImageAttachment {
  url: string
  path?: string
  file_name?: string
  file_url?: string
}

// 上传文件
export interface UploadFile {
  uid: string
  name: string
  type: string
  byte_size?: number
  url?: string
  upload_file_id?: string
  progress?: number
  uploadStatus?: 'pending' | 'uploading' | 'success' | 'error'
}

// 消息项属性
export interface MessageItemProps {
  base?: BaseEvent
  content?: MessageContent
  attachment?: Attachment[]
  imageAttachment?: ImageAttachment[]
  taskState?: TaskStatus
  action?: ActionInfo
  mcpContent?: McpContent
  planConfig?: PlanConfig
  taskTodoConfig?: TaskTodoConfig
  operation?: Operation
  userInteraction?: UserInteraction
}

// 扩展事件（用于渲染）
export interface ExtendedEvent extends BaseEvent {
  renderProps?: MessageItemProps
}

/**
 * API 原始事件类型 - 对应服务端 Event 结构（次于 next-agent-chat.type.ts 的 Event）
 * nova-sdk 内部以此类型处理原始事件流
 */
export interface ApiEvent {
  event_id: string
  event_type: string
  event_status?: string
  stream?: boolean
  role?: string
  task_id?: string
  created_at?: string | number
  timestamp?: string | number
  plan_step_state?: string
  is_display?: boolean
  metadata?: Record<string, unknown>
  content?: {
    text?: string
    content?: unknown
    action_type?: string
    tool_name?: string
    action_name?: string
    arguments?: unknown
    tool_input?: unknown
    tool_output?: unknown
    tool_call_id?: string
    metadata?: Record<string, unknown>
    attachment_files?: Array<{
      file_name?: string
      file_type?: string
      path?: string
      [key: string]: unknown
    }>
    refer_content?: string
    timestamp?: string | number
    fast_mode?: boolean
    [key: string]: unknown
  }
}

// 发送消息的 Payload
export interface SendMessagePayload {
  content: string
  agent_id?: string
  config?: {
    label_ids?: string[]
    search_custom_knowledge_enabled?: boolean
    template_type?: string
    template_id?: string
    brand_id?: string
    [key: string]: unknown
  }
  refer_content?: string
  upload_file_ids?: string[]
}

// Artifact 类型
export interface TaskArtifact {
  path: string
  file_name: string
  file_type: string
  last_modified?: number
  url?: string
  content?: string
  task_id?: string
  // 工具调用相关
  event_type?: string
  /** 工具 action_type，例如 skill_loader 等 */
  action_type?: string
  tool_name?: string
  event_arguments?: unknown
  tool_input?: unknown
  tool_output?: unknown
  from?: 'assistant' | 'user'
}

// Nova API 接口 - 从 useArtifactService 返回值自动推导
export type NovaAPI = ReturnType<typeof useNovaService>

// 消息列表 Provider 值
export interface NovaKitContextValue {
  agentId?: string
  agentName?: string
  /** API 命名空间 */
  api: NovaAPI
  messageList: ExtendedEvent[][]
  panelMode?: 'sidebar' | 'dialog'
  taskStatus: TaskStatus
  conversationId: string | null
  isLoading: boolean
  artifacts: TaskArtifact[]
  setLoading: (loading: boolean) => void
  loading: boolean
  mode?: 'chat' | 'share'
}

export type HandleImageAttachmentClick = (image: ImageAttachment, from: 'assistant' | 'user') => void