import type { UIConfig } from '@/types/conf'
import packageInfo from '../../package.json'
import { useAgentCatalogStore } from '@/store/agentCatalogStore'
const version = packageInfo.version

export enum EventName {
  AskQuestion = 'agent-hub-ask-question',
  UploadFiles = 'agent-hub-upload-files',
  CreateAgent = 'agent-hub-create-agent',
  SaveAgent = 'agent-hub-save-agent',
  DeleteAgent = 'agent-hub-delete-agent',
  PublishAgent = 'agent-hub-publish-agent',
  ShareAgent = 'agent-hub-share-agent',
  FavoriteAgent = 'agent-hub-favorite-agent',
  AutoFillAgent = 'agent-hub-auto-fill-agent',
  DiscardAgentChanges = 'agent-hub-discard-agent-changes',
  ViewPromptLibrary = 'agent-hub-view-prompt-library',
  UsePredefinedPrompt = 'agent-hub-use-predefined-prompt',
  CopyPredefinedPrompt = 'agent-hub-copy-predefined-prompt',
  ViewToolsLibrary = 'agent-hub-view-tools-library',
  SelectAgent = 'agent-hub-select-agent',
  SelectExampleQuery = 'agent-hub-select-example-query',
  ViewAgentLibrary = 'agent-hub-view-agent-library',
  ViewMonitoring = 'agent-hub-view-monitoring',
  ViewAgentGroup = 'agent-hub-view-agent-group',
  MessageCreateStory = 'agent-hub-message-create-story',
  MessageViewStory = 'agent-hub-message-view-story',
  MessageViewEventLog = 'agent-hub-message-view-event-log',
  MessageGenerateChart = 'agent-hub-message-generate-chart',
  MessageEditMessage = 'agent-hub-message-edit-message',
  MessageFeedback = 'agent-hub-message-feedback',
  ViewHome = 'agent-hub-view-home',
  Open = 'agent-hub-open',
  Error = 'agent-hub-error',
  ResetConversation = 'agent-hub-reset-conversation',
  NewConversation = 'agent-hub-new-conversation',
  DeleteConversation = 'agent-hub-delete-conversation',
  DeleteAllConversations = 'agent-hub-delete-all-conversations',
  CopyTrace = 'agent-hub-copy-trace',
  ViewTraceExplorer = 'agent-hub-view-trace-explorer',
}

export class WT1iser {
  public static llmId: string | undefined
  private static visualizationMode: string | undefined
  private static promptLibraryEnabled: boolean | undefined
  private static nExcludedGroupsForAgentSharing: number
  private static quickAgentsEnabled: boolean | undefined
  private static appSmartModeEnabled: boolean | undefined
  private static webappVersion = version
  public static initialized: boolean = false
  public static opened: boolean = false
  public static open(): void {
    this.opened = true
    this.sendEvent(EventName.Open, {})
  }

  public static askQuestion(
    isDraft: boolean = false,
    agentsEnabled: boolean = true,
    nSelectedAgents: number = 0,
    nAttachments: number = 0
  ) {
    this.sendEvent(EventName.AskQuestion, {
      isDraft,
      agentsEnabled,
      nSelectedAgents,
      nAttachments,
    })
  }
  public static uploadFiles(nFiles: number) {
    this.sendEvent(EventName.UploadFiles, {
      nFiles,
    })
  }

  public static messageFeedback(feedbackType: string, feedbackHasComment: boolean = false): void {
    this.sendEvent(EventName.MessageFeedback, { feedbackType, feedbackHasComment })
  }

  public static createAgent(): void {
    this.sendEvent(EventName.CreateAgent, {})
  }
  public static saveAgent(agent: any): void {
    this.sendEvent(EventName.SaveAgent, {
      isCreated: agent.project_key !== null,
      hasDescription: agent.description?.trim().length > 0,
      nExamples: agent.sample_questions?.length,
      nActiveDocs: agent.documents?.filter((d: any) => d.active && !d.pendingDelete).length,
      nUploadedDocs: agent.documents?.filter((d: any) => !d.pendingDelete).length,
      nTools: agent.tools?.length,
      hasPrompt: agent.systemPrompt?.trim().length > 0,
      status: agent.status,
    })
  }
  public static deleteAgent(status: string): void {
    this.sendEvent(EventName.DeleteAgent, { status })
  }
  public static publishAgent(status: string): void {
    this.sendEvent(EventName.PublishAgent, { status })
  }
  public static shareAgent(): void {
    this.sendEvent(EventName.ShareAgent, {})
  }

  public static favoriteAgent(isFavorite: boolean): void {
    this.sendEvent(EventName.FavoriteAgent, { isFavorite })
  }

  public static discardAgentChanges(): void {
    this.sendEvent(EventName.DiscardAgentChanges, {})
  }
  public static autoFillAgent(name: string, description?: string, exp?: string[]): void {
    this.sendEvent(EventName.AutoFillAgent, {
      defaultName: name === 'New Agent',
      emptyDescription: description?.trim().length === 0,
      nExamples: exp?.length,
    })
  }
  public static viewPromptLibrary(): void {
    this.sendEvent(EventName.ViewPromptLibrary, {})
  }

  public static usePredefinedPrompt(): void {
    this.sendEvent(EventName.UsePredefinedPrompt, {})
  }
  public static copyPredefinedPrompt(): void {
    this.sendEvent(EventName.CopyPredefinedPrompt, {})
  }
  public static viewToolsLibrary(): void {
    this.sendEvent(EventName.ViewToolsLibrary, {})
  }
  public static selectAgent(agentType: string): void {
    this.sendEvent(EventName.SelectAgent, { agentType })
  }
  public static selectExampleQuery(): void {
    this.sendEvent(EventName.SelectExampleQuery, {})
  }
  public static viewAgentLibrary(): void {
    this.sendEvent(EventName.ViewAgentLibrary, {})
  }

  public static viewMonitoring(): void {
    this.sendEvent(EventName.ViewMonitoring, {})
  }
  public static viewAgentGroup(groupName: string): void {
    this.sendEvent(EventName.ViewAgentGroup, { groupName })
  }
  public static messageCreateStory(nbrTables?: number): void {
    this.sendEvent(EventName.MessageCreateStory, { nbrTables })
  }
  public static messageViewStory(): void {
    this.sendEvent(EventName.MessageViewStory, {})
  }
  public static messageViewEventLog(): void {
    this.sendEvent(EventName.MessageViewEventLog, {})
  }
  public static messageEditMessage(): void {
    this.sendEvent(EventName.MessageEditMessage, {})
  }
  public static messageGenerateChart(nbrRecords?: number): void {
    this.sendEvent(EventName.MessageGenerateChart, { nbrRecords })
  }
  public static viewHome(): void {
    this.sendEvent(EventName.ViewHome, {})
  }
  public static resetConversation(): void {
    this.sendEvent(EventName.ResetConversation, {})
  }

  public static newConversation() {
    this.sendEvent(EventName.NewConversation, {})
  }
  public static newMediaConversation() {
    this.sendEvent(EventName.NewConversation, {})
  }

  public static deleteConversation() {
    this.sendEvent(EventName.DeleteConversation, {})
  }

  public static deleteAllConversations() {
    this.sendEvent(EventName.DeleteAllConversations, {})
  }
  public static copyTrace(): void {
    this.sendEvent(EventName.CopyTrace, {})
  }
  public static viewTraceExplorer(): void {
    this.sendEvent(EventName.ViewTraceExplorer, {})
  }
  public static error(actionName: string, error: string): void {
    this.sendEvent(EventName.Error, { actionName, error })
  }
  public static init(uiConf: UIConfig): void {
    this.llmId = uiConf.default_llm ?? 'unset'
    this.visualizationMode = uiConf.visualization_mode ?? 'unset'
    this.promptLibraryEnabled = uiConf.enable_prompt_library ?? false
    this.nExcludedGroupsForAgentSharing = (uiConf.exclude_groups_for_agent_sharing ?? []).length
    this.quickAgentsEnabled = uiConf.enable_quick_agents ?? false
    this.appSmartModeEnabled = uiConf.enable_app_smart_mode ?? false
    this.initialized = true
    console.log('** agent hub version **', version)
    try {
      if (!(window.parent as any).WT1SVC && (window as any).dkuUsageReportingUtils) {
        console.debug('bootstrap standalone reporting mode')
        ;(window as any).dkuUsageReportingUtils.standaloneModeBootstrap()
      }
    } catch (error) {}
  }

  private static prepareEventParams(props: any) {
    const catalog = useAgentCatalogStore()
    const uniqueAgents = Array.from(new Map((catalog?.agents || []).map((a) => [a.id, a])).values())
    const commonContextParams = {
      llmId: this.llmId,
      visualizationMode: this.visualizationMode,
      promptLibraryEnabled: this.promptLibraryEnabled,
      quickAgentsEnabled: this.quickAgentsEnabled,
      appSmartModeEnabled: this.appSmartModeEnabled,
      webappVersion: this.webappVersion,
      nAgents: uniqueAgents.length,
      nMyAgents: uniqueAgents.filter((a) => !a.isShared && !a.isEnterprise).length,
      nSharedAgents: uniqueAgents.filter((a) => a.isShared && !a.isEnterprise).length,
      nEnterpriseAgents: uniqueAgents.filter((a) => a.isEnterprise).length,
      nExcludedGroupsForAgentSharing: this.nExcludedGroupsForAgentSharing,
    }

    return {
      ...props,
      ...commonContextParams,
    }
  }

  private static sendEvent(event: EventName, props: any) {
    try {
      const params = this.prepareEventParams(props)
      if ((window.parent as any).WT1SVC) {
        ;(window.parent as any).WT1SVC.event(event, params)
      } else if ((window as any).dkuUsageReportingUtils) {
        ;(window as any).dkuUsageReportingUtils.standaloneModeTrackEvent(event, params)
      }
    } catch (error) {}
  }
}
