// @ts-nocheck
import { debugLog } from '../common';
import { usePolicyStore } from '../../../stores/policy';
import { useModelStore } from '../../../stores/model';
import { usePersonalizationStore } from '../../../stores/personalization';
import { useTutorialStore } from '../../../stores/tutorial';
import { renderMarkdown as renderMarkdownHelper } from '../../../composables/useMarkdownRenderer';
import { scrollToBottom as scrollToBottomHelper, conditionalScrollToBottom as conditionalScrollToBottomHelper, scrollThinkingToBottom as scrollThinkingToBottomHelper } from '../../../composables/useScrollControl';
import { startResize as startPanelResize, handleResize as handlePanelResize, stopResize as stopPanelResize } from '../../../composables/usePanelResize';
import {
  SUB_AGENT_DONE_PREFIX_RE,
  BG_RUN_COMMAND_DONE_PREFIX_RE,
  userMDebug,
  UI_BOUNCE_TRACE_MAX,
  uiBounceTraceLastTsByKey,
  isUiBounceTraceEnabled,
  uiBounceTrace,
  isConnectionDiagEnabled,
  pushConnectionDiagRecord,
  connectionDiag,
  parseSubAgentDoneLabel,
  parseBackgroundRunCommandDoneLabel,
  parseSystemNoticeLabel,
} from './shared';

export const modeMethods = {
  handleQuickModeToggle() {
    if (!this.isConnected || this.streamingMessage) {
      return;
    }
    this.handleCycleRunMode();
  },
  toggleQuickMenu() {
    if (!this.isConnected) {
      return;
    }
    const opened = this.inputToggleQuickMenu();
    if (!opened) {
      this.modeMenuOpen = false;
      this.modelMenuOpen = false;
    }
  },
  closeQuickMenu() {
    this.inputCloseMenus();
    this.modeMenuOpen = false;
    this.modelMenuOpen = false;
  },
  handleToggleGoalMode() {
    if (!this.isConnected) {
      return;
    }
    if (this.goalRunning) {
      // 运行中点击 → 打开进度弹窗，而非切换
      this.goalDialogOpen = true;
      this.inputCloseMenus();
      return;
    }
    const goalStatus = String(this.goalProgress?.status || '').toLowerCase();
    if (goalStatus === 'done' || goalStatus === 'stopped') {
      this.goalProgress = null;
      this.goalDialogOpen = false;
    }
    this.inputToggleGoalArmed();
    this.inputCloseMenus();
    this.modeMenuOpen = false;
    this.modelMenuOpen = false;
  },
  handleToggleAgentMode() {
    if (!this.isConnected) {
      return;
    }
    // 有运行中对话时不允许切换
    if (this.composerBusy || this.anyWorkspaceHasRunningTask) {
      return;
    }
    this.inputCloseMenus();
    // 多智能体模式 → 传统模式；传统模式 → 多智能体模式
    const target = this.multiAgentMode ? '/new' : '/multiagent/new';
    window.location.href = target;
  },
  toggleModeMenu() {
    if (!this.isConnected || this.streamingMessage) {
      return;
    }
    const next = !this.modeMenuOpen;
    this.modeMenuOpen = next;
    if (next) {
      this.modelMenuOpen = false;
    }
    if (next) {
      this.inputSetToolMenuOpen(false);
      this.inputSetSettingsOpen(false);
      if (!this.quickMenuOpen) {
        this.inputOpenQuickMenu();
      }
    }
  },
  async handleModeSelect(mode) {
    if (!this.isConnected || this.streamingMessage) {
      return;
    }
    await this.setRunMode(mode);
  },
  async handleHeaderRunModeSelect(mode) {
    await this.handleModeSelect(mode);
    this.closeHeaderMenu();
  },
  async handleCycleRunMode() {
    const modes: Array<'fast' | 'thinking' | 'deep'> = ['fast', 'thinking', 'deep'];
    const currentMode = this.resolvedRunMode;
    const currentIndex = modes.indexOf(currentMode);
    const nextMode = modes[(currentIndex + 1) % modes.length];
    await this.setRunMode(nextMode);
  },
  async setRunMode(mode, options = {}) {
    if (!this.isConnected || this.streamingMessage) {
      this.modeMenuOpen = false;
      return;
    }
    const modelStore = useModelStore();
    const fastOnly = modelStore.currentModel?.fastOnly;
    const deepOnly = modelStore.currentModel?.deepOnly;
    if (fastOnly && mode !== 'fast') {
      if (!options.suppressToast) {
        this.uiPushToast({
          title: '模式不可用',
          message: '当前模型仅支持快速模式',
          type: 'warning'
        });
      }
      this.modeMenuOpen = false;
      this.inputCloseMenus();
      return;
    }
    if (deepOnly && mode !== 'deep') {
      if (!options.suppressToast) {
        this.uiPushToast({
          title: '模式不可用',
          message: '当前模型仅支持深度思考模式',
          type: 'warning'
        });
      }
      this.modeMenuOpen = false;
      this.inputCloseMenus();
      return;
    }
    if (mode === this.resolvedRunMode) {
      this.modeMenuOpen = false;
      this.closeQuickMenu();
      return;
    }
    try {
      const response = await fetch('/api/thinking-mode', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ mode })
      });
      const payload = await response.json();
      if (!response.ok || !payload.success) {
        throw new Error(payload.message || payload.error || '切换失败');
      }
      const data = payload.data || {};
      this.thinkingMode =
        typeof data.thinking_mode === 'boolean' ? data.thinking_mode : mode !== 'fast';
      this.runMode = data.mode || mode;
    } catch (error) {
      console.error('切换运行模式失败:', error);
      const message = error instanceof Error ? error.message : String(error || '未知错误');
      this.uiPushToast({
        title: '切换思考模式失败',
        message: message || '请稍后重试',
        type: 'error'
      });
    } finally {
      this.modeMenuOpen = false;
      this.inputCloseMenus();
    }
  },
  async toggleThinkingMode() {
    await this.handleCycleRunMode();
  },
  async handleStopAllSubAgents() {
    const isMultiAgent = !!this.multiAgentMode;
    const mode = isMultiAgent ? 'soft_stop' : 'terminate';
    const title = isMultiAgent ? '是否暂停所有子智能体？' : '是否终结所有子智能体？';
    const message = isMultiAgent
      ? '所有正在运行的子智能体将停止工作并变为空闲状态。取消表示不执行操作。'
      : '所有后台子智能体将被强制终止。取消表示不执行操作。';
    const confirmText = isMultiAgent ? '暂停' : '终结';
    let proceed = false;
    try {
      const uiStore = (await import('../../../stores/ui')).useUiStore();
      proceed = await uiStore.requestConfirm({
        title,
        message,
        confirmText,
        cancelText: '取消',
        confirmVariant: 'danger',
        closeOnBackdrop: true
      });
    } catch (error) {
      console.error('[stopAllSubAgents] 弹窗异常:', error);
      return;
    }
    if (!proceed) return;
    try {
      const { useSubAgentStore } = await import('../../../stores/subAgent');
      const store = useSubAgentStore();
      const result = await store.stopAllAgents(mode);
      if (!result.success) {
        this.uiPushToast({
          title: '停止子智能体失败',
          message: result.error || '请重试',
          type: 'error'
        });
        return;
      }
      this.uiPushToast({
        title: isMultiAgent ? '子智能体已暂停' : '子智能体已终结',
        message: `已处理 ${result.stoppedCount || 0} 个子智能体`,
        type: 'info'
      });
    } catch (error: any) {
      console.error('[stopAllSubAgents] 调用失败:', error);
      this.uiPushToast({
        title: '停止子智能体失败',
        message: error?.message || String(error),
        type: 'error'
        });
    }
  }
};
