// @ts-nocheck
// @ts-nocheck
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 { debugLog } from '../common';

export const SUB_AGENT_DONE_PREFIX_RE = /^(?:✅\s*)?子智能体\s*#?\s*(\d+)\s*任务摘要[:：]/;
export const BG_RUN_COMMAND_DONE_PREFIX_RE = /^\[后台\s*run_command\s*完成\]/;
export const userMDebug = (...args: any[]) => {
  console.log('[USERMDEBUG]', ...args);
};
export let uiBounceTraceCount = 0;
export const UI_BOUNCE_TRACE_MAX = 140;
export const uiBounceTraceLastTsByKey = new Map<string, number>();

export function isUiBounceTraceEnabled() {
  if (typeof window === 'undefined') return true;
  try {
    const explicit = (window as any).__SCROLL_BOUNCE_TRACE__;
    if (explicit === false || explicit === '0') return false;
    if (explicit === true || explicit === '1') return true;
    const localFlag = window.localStorage?.getItem('scrollBounceTrace');
    if (localFlag === '0' || localFlag === 'false') return false;
    if (localFlag === '1' || localFlag === 'true') return true;
    return true;
  } catch {
    return true;
  }
}

export function uiBounceTrace(
  event: string,
  payload: Record<string, any> = {},
  key = event,
  throttleMs = 140
) {
  if (!isUiBounceTraceEnabled()) return;
  if (uiBounceTraceCount >= UI_BOUNCE_TRACE_MAX) return;
  const now = Date.now();
  const last = uiBounceTraceLastTsByKey.get(key) || 0;
  if (throttleMs > 0 && now - last < throttleMs) return;
  uiBounceTraceLastTsByKey.set(key, now);
  uiBounceTraceCount += 1;
  if (uiBounceTraceCount === UI_BOUNCE_TRACE_MAX) {
    console.warn('[SCROLL_BOUNCE_TRACE_UI]', 'log-limit-reached', { max: UI_BOUNCE_TRACE_MAX });
    return;
  }
  console.log('[SCROLL_BOUNCE_TRACE_UI]', event, payload);
}

export function isConnectionDiagEnabled() {
  if (typeof window === 'undefined') return true;
  try {
    const explicit = (window as any).__CONN_DIAG__;
    if (explicit === false || explicit === '0') return false;
    if (explicit === true || explicit === '1') return true;
    const localFlag = window.localStorage?.getItem('connDiag');
    if (localFlag === '0' || localFlag === 'false') return false;
    if (localFlag === '1' || localFlag === 'true') return true;
    // 默认常开：无需手动启动
    return true;
  } catch {
    return true;
  }
}

export function pushConnectionDiagRecord(record: Record<string, any>) {
  if (typeof window === 'undefined') return;
  try {
    const w = window as any;
    if (!Array.isArray(w.__CONN_DIAG_LOGS__)) {
      w.__CONN_DIAG_LOGS__ = [];
    }
    w.__CONN_DIAG_LOGS__.push(record);
    const max = 400;
    if (w.__CONN_DIAG_LOGS__.length > max) {
      w.__CONN_DIAG_LOGS__.splice(0, w.__CONN_DIAG_LOGS__.length - max);
    }
  } catch {
    // ignore
  }
}

export function connectionDiag(
  level: 'log' | 'warn' | 'error',
  event: string,
  payload: Record<string, any> = {},
  options: { force?: boolean } = {}
) {
  const force = !!options.force;
  const enabled = isConnectionDiagEnabled();
  if (!enabled && !force) {
    return;
  }
  const record = {
    ts: new Date().toISOString(),
    event,
    ...payload
  };
  pushConnectionDiagRecord(record);
  const logger = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log;
  logger('[CONN_DIAG]', event, record);
}

export function parseSubAgentDoneLabel(rawContent: any): string | null {
  const content = (rawContent || '').toString().trim();
  if (!content) {
    console.log('[DEBUG_SYSTEM][ui] parseSubAgentDoneLabel: 空内容');
    return null;
  }
  const match = content.match(SUB_AGENT_DONE_PREFIX_RE);
  const isCompleted = /已完成/.test(content);
  console.log('[DEBUG_SYSTEM][ui] parseSubAgentDoneLabel', {
    content,
    regex: SUB_AGENT_DONE_PREFIX_RE.toString(),
    matched: !!match,
    matchAgentId: match?.[1],
    isCompleted
  });
  if (!match || !isCompleted) {
    return null;
  }
  const agentId = match[1];
  return `子智能体${agentId} 任务完成`;
}

export function parseBackgroundRunCommandDoneLabel(rawContent: any): string | null {
  const content = (rawContent || '').toString().trim();
  if (!content) {
    return null;
  }
  if (!BG_RUN_COMMAND_DONE_PREFIX_RE.test(content)) {
    return null;
  }
  return '后台 run_command 完成';
}

export function parseSystemNoticeLabel(rawContent: any): string | null {
  const content = (rawContent || '').toString().trim();
  if (!content) return null;
  return parseSubAgentDoneLabel(content) || parseBackgroundRunCommandDoneLabel(content);
}

