/**
 * 数据动作解析与执行器
 * 处理 CRUD 数据操作，调用 admin-operations Edge Function
 */

import { executeAdminOperation } from '@/utils/adminOperationsClient';
import { AdminOperationType } from '@/types/adminOperations';
import { toast } from 'sonner';

// 数据动作类型
export type DataActionType =
  | 'create_product'
  | 'update_product'
  | 'delete_product'
  | 'create_order'
  | 'update_order'
  | 'cancel_order'
  | 'create_category'
  | 'update_category'
  | 'delete_category'
  | 'create_brand'
  | 'update_brand'
  | 'delete_brand'
  | 'create_banner'
  | 'update_banner'
  | 'delete_banner'
  | 'create_coupon'
  | 'update_coupon'
  | 'delete_coupon'
  | 'approve_aftersales'
  | 'reject_aftersales'
  | 'create_goal'
  | 'update_goal'
  | 'delete_goal'
  | 'query_data'
  // Agent配置动作
  | 'query_agent'
  | 'update_agent'
  | 'set_agent_auto_execute'
  | 'set_agent_max_amount'
  | 'set_agent_goals'
  | 'set_agent_notifications'
  | 'set_agent_approval_types';

// 数据动作接口
export interface DataAction {
  kind: 'data_action';
  type: DataActionType;
  params: Record<string, any>;
  description?: string;
}

// 动作类型到 admin-operations 类型的映射
const ACTION_TO_OPERATION: Record<DataActionType, AdminOperationType> = {
  create_product: 'product.create',
  update_product: 'product.update',
  delete_product: 'product.delete',
  create_order: 'order.update', // 订单通常不直接创建，而是更新
  update_order: 'order.update',
  cancel_order: 'order.cancel',
  create_category: 'category.create',
  update_category: 'category.update',
  delete_category: 'category.delete',
  create_brand: 'brand.create',
  update_brand: 'brand.update',
  delete_brand: 'brand.delete',
  create_banner: 'banner.create',
  update_banner: 'banner.update',
  delete_banner: 'banner.delete',
  create_coupon: 'coupon.create',
  update_coupon: 'coupon.update',
  delete_coupon: 'coupon.delete',
  approve_aftersales: 'afterSales.approve',
  reject_aftersales: 'afterSales.reject',
  create_goal: 'goal.create',
  update_goal: 'goal.update',
  delete_goal: 'goal.delete',
  query_data: 'product.query', // 查询根据params中的table动态确定
  // Agent配置映射
  query_agent: 'agent.query',
  update_agent: 'agent.update',
  set_agent_auto_execute: 'agent.setAutoExecute',
  set_agent_max_amount: 'agent.setMaxAmount',
  set_agent_goals: 'agent.setGoals',
  set_agent_notifications: 'agent.setNotifications',
  set_agent_approval_types: 'agent.setApprovalTypes',
};

// 动作类型标签
const DATA_ACTION_LABELS: Record<DataActionType, string> = {
  create_product: '创建商品',
  update_product: '更新商品',
  delete_product: '删除商品',
  create_order: '创建订单',
  update_order: '更新订单',
  cancel_order: '取消订单',
  create_category: '创建分类',
  update_category: '更新分类',
  delete_category: '删除分类',
  create_brand: '创建品牌',
  update_brand: '更新品牌',
  delete_brand: '删除品牌',
  create_banner: '创建横幅',
  update_banner: '更新横幅',
  delete_banner: '删除横幅',
  create_coupon: '创建优惠券',
  update_coupon: '更新优惠券',
  delete_coupon: '删除优惠券',
  approve_aftersales: '批准售后',
  reject_aftersales: '拒绝售后',
  create_goal: '创建目标',
  update_goal: '更新目标',
  delete_goal: '删除目标',
  query_data: '查询数据',
  // Agent配置标签
  query_agent: '查询Agent配置',
  update_agent: '更新Agent配置',
  set_agent_auto_execute: '设置Agent自动执行',
  set_agent_max_amount: '设置Agent执行额度',
  set_agent_goals: '设置Agent目标',
  set_agent_notifications: '设置Agent通知',
  set_agent_approval_types: '设置Agent审批类型',
};

/**
 * 获取数据动作标签
 */
export function getDataActionLabel(type: DataActionType): string {
  return DATA_ACTION_LABELS[type] || type;
}

/**
 * 从文本中提取数据动作
 * 支持两种格式：
 * 1. [DATA_ACTION]{...}[/DATA_ACTION] 标记块
 * 2. {"kind":"data_action",...} JSON对象
 */
export function extractDataAction(text: string): DataAction | null {
  // 优先匹配标记块
  const blockRegex = /\[DATA_ACTION\]([\s\S]*?)\[\/DATA_ACTION\]/i;
  const blockMatch = text.match(blockRegex);
  
  if (blockMatch) {
    try {
      const parsed = JSON.parse(blockMatch[1].trim());
      if (parsed.type && Object.keys(ACTION_TO_OPERATION).includes(parsed.type)) {
        return {
          kind: 'data_action',
          type: parsed.type,
          params: parsed.params || {},
          description: parsed.description,
        };
      }
    } catch (e) {
      console.warn('解析 DATA_ACTION 标记块失败:', e);
    }
  }

  // 匹配 JSON 对象
  const jsonRegex = /\{[^{}]*"kind"\s*:\s*"data_action"[^{}]*\}/g;
  const matches = text.match(jsonRegex);
  
  if (matches) {
    for (const match of matches) {
      try {
        const parsed = JSON.parse(match);
        if (parsed.kind === 'data_action' && parsed.type) {
          return {
            kind: 'data_action',
            type: parsed.type,
            params: parsed.params || {},
            description: parsed.description,
          };
        }
      } catch (e) {
        // 继续尝试下一个匹配
      }
    }
  }

  // 尝试匹配嵌套的 JSON（可能在更大的 JSON 结构中）
  try {
    const fullJson = JSON.parse(text);
    if (fullJson.kind === 'data_action' && fullJson.type) {
      return {
        kind: 'data_action',
        type: fullJson.type,
        params: fullJson.params || {},
        description: fullJson.description,
      };
    }
    // 检查是否在 action 或 actions 字段中
    const action = fullJson.action || fullJson.actions?.[0];
    if (action?.kind === 'data_action' && action.type) {
      return {
        kind: 'data_action',
        type: action.type,
        params: action.params || {},
        description: action.description,
      };
    }
  } catch (e) {
    // 不是有效的 JSON
  }

  return null;
}

/**
 * 校验数据动作
 */
export interface DataActionValidation {
  ok: boolean;
  missing?: string[];
  warnings?: string[];
}

export function validateDataAction(action: DataAction): DataActionValidation {
  const missing: string[] = [];
  const warnings: string[] = [];

  if (!action.type) {
    missing.push('type');
  }

  // 根据动作类型检查必需参数
  switch (action.type) {
    case 'create_product':
      if (!action.params.name) missing.push('name');
      if (action.params.price === undefined) missing.push('price');
      break;
    case 'update_product':
    case 'delete_product':
      if (!action.params.id) missing.push('id');
      break;
    case 'update_order':
    case 'cancel_order':
      if (!action.params.id) missing.push('id (订单ID)');
      break;
    case 'create_category':
    case 'create_brand':
      if (!action.params.name) missing.push('name');
      break;
    case 'update_category':
    case 'delete_category':
    case 'update_brand':
    case 'delete_brand':
      if (!action.params.id) missing.push('id');
      break;
    case 'create_banner':
      if (!action.params.title) missing.push('title');
      break;
    case 'create_coupon':
      if (!action.params.name) missing.push('name (优惠券名称)');
      if (!action.params.code) missing.push('code (优惠券码)');
      if (!action.params.type) missing.push('type (类型: percentage/fixed)');
      if (action.params.discount_value === undefined) missing.push('discount_value (折扣值)');
      if (!action.params.start_date) missing.push('start_date (开始日期)');
      if (!action.params.end_date) missing.push('end_date (结束日期)');
      if (action.params.total_quantity === undefined) missing.push('total_quantity (总数量)');
      break;
    case 'update_coupon':
    case 'delete_coupon':
      if (!action.params.id) missing.push('id (优惠券ID)');
      break;
    case 'approve_aftersales':
    case 'reject_aftersales':
      if (!action.params.id) missing.push('id (售后ID)');
      break;
    case 'create_goal':
      if (!action.params.title) missing.push('title (目标标题)');
      if (action.params.targetValue === undefined) missing.push('targetValue (目标值)');
      if (!action.params.deadline) missing.push('deadline (截止日期)');
      if (!action.params.agentType) missing.push('agentType (所属Agent)');
      break;
    case 'update_goal':
    case 'delete_goal':
      if (!action.params.id) missing.push('id (目标ID)');
      break;
    // Agent配置校验
    case 'update_agent':
    case 'set_agent_auto_execute':
    case 'set_agent_max_amount':
    case 'set_agent_goals':
    case 'set_agent_notifications':
    case 'set_agent_approval_types':
      if (!action.params.agentType) missing.push('agentType (Agent类型)');
      break;
  }

  return {
    ok: missing.length === 0,
    missing: missing.length > 0 ? missing : undefined,
    warnings: warnings.length > 0 ? warnings : undefined,
  };
}

/**
 * 执行数据动作结果
 */
export interface DataActionResult {
  success: boolean;
  action: DataAction;
  message: string;
  data?: any;
  latency?: number;
}

/**
 * 执行数据动作
 */
export async function executeDataAction(
  action: DataAction,
  options: {
    showToast?: boolean;
    debug?: boolean;
    requireConfirmation?: boolean;
    onConfirm?: (action: DataAction) => Promise<boolean>;
  } = {}
): Promise<DataActionResult> {
  const startTime = performance.now();
  const { showToast = true, debug = false, requireConfirmation = false, onConfirm } = options;

  // 校验动作
  const validation = validateDataAction(action);
  if (!validation.ok) {
    const errorMsg = `数据操作参数不完整: 缺少 ${validation.missing?.join(', ')}`;
    if (showToast) toast.error(errorMsg);
    return {
      success: false,
      action,
      message: errorMsg,
      latency: performance.now() - startTime,
    };
  }

  // 危险操作确认
  const dangerousTypes: DataActionType[] = ['delete_product', 'delete_category', 'delete_brand', 'delete_banner', 'cancel_order'];
  if (requireConfirmation && dangerousTypes.includes(action.type)) {
    if (onConfirm) {
      const confirmed = await onConfirm(action);
      if (!confirmed) {
        return {
          success: false,
          action,
          message: '用户取消操作',
          latency: performance.now() - startTime,
        };
      }
    }
  }

  try {
    // 确定操作类型
    let operationType = ACTION_TO_OPERATION[action.type];
    
    // 对于 query_data，根据 table 参数动态确定
    if (action.type === 'query_data' && action.params.table) {
      const tableToQuery: Record<string, AdminOperationType> = {
        products: 'product.query',
        orders: 'order.query',
        users: 'user.query',
        categories: 'category.query',
        brands: 'brand.query',
        banners: 'banner.query',
        afterSales: 'afterSales.query',
      };
      operationType = tableToQuery[action.params.table] || 'product.query';
    }

    // 调用 admin-operations
    const result = await executeAdminOperation(operationType, action.params);

    if (debug) {
      console.log('DataAction 执行结果:', {
        type: action.type,
        operationType,
        params: action.params,
        result,
        latency: performance.now() - startTime,
      });
    }

    if (result.success) {
      const successMsg = result.message || `${getDataActionLabel(action.type)}成功`;
      if (showToast) toast.success(successMsg);
      return {
        success: true,
        action,
        message: successMsg,
        data: result.data,
        latency: performance.now() - startTime,
      };
    } else {
      const errorMsg = result.error || `${getDataActionLabel(action.type)}失败`;
      if (showToast) toast.error(errorMsg);
      return {
        success: false,
        action,
        message: errorMsg,
        latency: performance.now() - startTime,
      };
    }
  } catch (error) {
    const errorMsg = `执行${getDataActionLabel(action.type)}失败: ${error instanceof Error ? error.message : '未知错误'}`;
    if (showToast) toast.error(errorMsg);
    return {
      success: false,
      action,
      message: errorMsg,
      latency: performance.now() - startTime,
    };
  }
}

/**
 * 批量执行数据动作
 */
export async function executeDataActions(
  actions: DataAction[],
  options: {
    showToast?: boolean;
    debug?: boolean;
    stopOnError?: boolean;
  } = {}
): Promise<DataActionResult[]> {
  const results: DataActionResult[] = [];
  const { stopOnError = false } = options;

  for (const action of actions) {
    const result = await executeDataAction(action, {
      ...options,
      showToast: false,
    });
    results.push(result);

    if (!result.success && stopOnError) {
      break;
    }
  }

  // 批量执行完成后显示汇总
  const successCount = results.filter(r => r.success).length;
  const failCount = results.length - successCount;

  if (options.showToast !== false) {
    if (failCount === 0) {
      toast.success(`成功执行 ${successCount} 个数据操作`);
    } else {
      toast.warning(`执行完成: ${successCount} 成功, ${failCount} 失败`);
    }
  }

  return results;
}
