/**
 * 统一动作系统
 * 整合页面动作和数据动作，提供统一的解析和执行接口
 */

import { PageAction, extractPageAction, validatePageAction, getActionTypeLabel, getTabLabel } from './pageActions';
import { DataAction, extractDataAction, validateDataAction, getDataActionLabel } from './dataActions';
import { executePageAction, ExecuteOptions as PageExecuteOptions, ExecuteResult as PageExecuteResult } from './executePageAction';
import { executeDataAction, DataActionResult } from './dataActions';

// 统一动作类型
export type UnifiedAction = PageAction | DataAction;

// 统一动作结果
export interface UnifiedActionResult {
  success: boolean;
  actionKind: 'page_action' | 'data_action';
  action: UnifiedAction;
  message: string;
  data?: any;
  latency?: number;
}

/**
 * 从文本中提取所有动作（页面动作 + 数据动作）
 * 优先级：标记块 > JSON对象
 */
export function extractUnifiedActions(text: string): UnifiedAction[] {
  const actions: UnifiedAction[] = [];

  // 提取页面动作
  const pageAction = extractPageAction(text);
  if (pageAction) {
    actions.push(pageAction);
  }

  // 提取数据动作
  const dataAction = extractDataAction(text);
  if (dataAction) {
    actions.push(dataAction);
  }

  // 尝试从 JSON 的 actions 数组中提取多个动作
  try {
    // 匹配包含 actions 数组的 JSON
    const actionsArrayRegex = /"actions"\s*:\s*\[([\s\S]*?)\]/;
    const match = text.match(actionsArrayRegex);
    if (match) {
      const actionsJson = `[${match[1]}]`;
      const parsedActions = JSON.parse(actionsJson);
      
      for (const action of parsedActions) {
        if (action.kind === 'page_action' && action.type) {
          const pa: PageAction = {
            kind: 'page_action',
            type: action.type,
            params: action.params || {},
          };
          if (!actions.some(a => a.kind === 'page_action' && a.type === pa.type)) {
            actions.push(pa);
          }
        } else if (action.kind === 'data_action' && action.type) {
          const da: DataAction = {
            kind: 'data_action',
            type: action.type,
            params: action.params || {},
            description: action.description,
          };
          if (!actions.some(a => a.kind === 'data_action' && a.type === da.type)) {
            actions.push(da);
          }
        }
      }
    }
  } catch (e) {
    // 解析失败，忽略
  }

  return actions;
}

/**
 * 判断动作类型
 */
export function isPageAction(action: UnifiedAction): action is PageAction {
  return action.kind === 'page_action';
}

export function isDataAction(action: UnifiedAction): action is DataAction {
  return action.kind === 'data_action';
}

/**
 * 获取动作标签
 */
export function getActionLabel(action: UnifiedAction): string {
  if (isPageAction(action)) {
    return `${getActionTypeLabel(action.type)} - ${getTabLabel((action.params as any).tab || '')}`;
  } else {
    return getDataActionLabel(action.type);
  }
}

/**
 * 校验动作
 */
export function validateUnifiedAction(action: UnifiedAction): { ok: boolean; missing?: string[]; warnings?: string[] } {
  if (isPageAction(action)) {
    return validatePageAction(action);
  } else {
    return validateDataAction(action);
  }
}

/**
 * 执行单个动作
 */
export async function executeUnifiedAction(
  action: UnifiedAction,
  options: {
    // 页面动作选项
    onNavigate?: (tab: string) => void;
    emitPageState?: (state: any) => void;
    router?: { navigate: (path: string) => void; push?: (path: string) => void };
    // 通用选项
    showToast?: boolean;
    debug?: boolean;
    requireConfirmation?: boolean;
    onConfirm?: (action: UnifiedAction) => Promise<boolean>;
  } = {}
): Promise<UnifiedActionResult> {
  const { showToast = true, debug = false, onNavigate, emitPageState, router, requireConfirmation, onConfirm } = options;

  if (isPageAction(action)) {
    const result = await executePageAction(action, {
      onNavigate,
      emitPageState,
      router,
      showToast,
      debug,
    });
    return {
      success: result.success,
      actionKind: 'page_action',
      action,
      message: result.message,
      latency: result.latency,
    };
  } else {
    const result = await executeDataAction(action, {
      showToast,
      debug,
      requireConfirmation,
      onConfirm: onConfirm ? async (a) => onConfirm(a as UnifiedAction) : undefined,
    });
    return {
      success: result.success,
      actionKind: 'data_action',
      action,
      message: result.message,
      data: result.data,
      latency: result.latency,
    };
  }
}

/**
 * 批量执行动作
 * 先执行数据动作，再执行页面动作（因为数据动作可能影响页面显示）
 */
export async function executeUnifiedActions(
  actions: UnifiedAction[],
  options: {
    onNavigate?: (tab: string) => void;
    emitPageState?: (state: any) => void;
    router?: { navigate: (path: string) => void; push?: (path: string) => void };
    showToast?: boolean;
    debug?: boolean;
    stopOnError?: boolean;
  } = {}
): Promise<UnifiedActionResult[]> {
  const results: UnifiedActionResult[] = [];
  const { stopOnError = false, showToast = true } = options;

  // 分离数据动作和页面动作
  const dataActions = actions.filter(isDataAction);
  const pageActions = actions.filter(isPageAction);

  // 先执行数据动作
  for (const action of dataActions) {
    const result = await executeUnifiedAction(action, { ...options, showToast: false });
    results.push(result);
    if (!result.success && stopOnError) break;
  }

  // 再执行页面动作
  for (const action of pageActions) {
    const result = await executeUnifiedAction(action, { ...options, showToast: false });
    results.push(result);
    if (!result.success && stopOnError) break;
  }

  // 显示汇总
  if (showToast && results.length > 0) {
    const successCount = results.filter(r => r.success).length;
    const failCount = results.length - successCount;

    if (failCount === 0) {
      if (results.length === 1) {
        // 单个操作已经在执行时显示了 toast
      } else {
        // toast.success(`成功执行 ${successCount} 个操作`);
      }
    } else {
      // toast.warning(`执行完成: ${successCount} 成功, ${failCount} 失败`);
    }
  }

  return results;
}

/**
 * 生成动作执行摘要
 */
export function generateActionSummary(results: UnifiedActionResult[]): string {
  if (results.length === 0) return '未执行任何操作';

  const lines: string[] = [];
  for (const result of results) {
    const icon = result.success ? '✓' : '✗';
    lines.push(`${icon} ${getActionLabel(result.action)}: ${result.message}`);
  }

  return lines.join('\n');
}
