/**
 * 仪表板动作指令解析与执行
 * 用于通过自然语言控制店长视窗组件的显示/隐藏/布局
 */

// ==================== 组件定义 ====================

// 组件ID枚举
export type WidgetId = 
  | 'agent_status'      // Agent状态栏
  | 'store_goal'        // 经营目标卡片
  | 'quick_actions'     // 快捷操作
  | 'pending_approvals' // 待审批列表
  | 'sales_trend'       // 销售趋势图
  | 'order_status'      // 订单状态分布
  | 'category_stats'    // 类目统计
  | 'user_growth'       // 用户增长
  | 'insight_feed'      // AI洞察流
  | 'stats_cards';      // 统计卡片

// 组件元数据
export interface WidgetMeta {
  id: WidgetId;
  name: string;
  nameCN: string;
  type: 'status' | 'goal' | 'actions' | 'list' | 'chart' | 'feed' | 'stats';
  defaultVisible: boolean;
  description: string;
}

// 组件注册表
export const WIDGET_REGISTRY: Record<WidgetId, WidgetMeta> = {
  agent_status: {
    id: 'agent_status',
    name: 'Agent Status Bar',
    nameCN: 'Agent状态栏',
    type: 'status',
    defaultVisible: true,
    description: '显示小管状态、今日洞察、待审批、已完成数量'
  },
  store_goal: {
    id: 'store_goal',
    name: 'Store Goal Card',
    nameCN: '经营目标卡片',
    type: 'goal',
    defaultVisible: true,
    description: '显示本月经营目标和完成进度'
  },
  quick_actions: {
    id: 'quick_actions',
    name: 'Quick Actions',
    nameCN: '快捷操作',
    type: 'actions',
    defaultVisible: true,
    description: '商品管理、用户管理、订单处理、营销活动快捷入口'
  },
  pending_approvals: {
    id: 'pending_approvals',
    name: 'Pending Approvals',
    nameCN: '待审批列表',
    type: 'list',
    defaultVisible: true,
    description: '显示等待审批的营销活动、商品、退款申请'
  },
  sales_trend: {
    id: 'sales_trend',
    name: 'Sales Trend Chart',
    nameCN: '销售趋势图',
    type: 'chart',
    defaultVisible: true,
    description: '7日销售金额和订单数趋势'
  },
  order_status: {
    id: 'order_status',
    name: 'Order Status Distribution',
    nameCN: '订单状态分布',
    type: 'chart',
    defaultVisible: true,
    description: '各状态订单数量饼图'
  },
  category_stats: {
    id: 'category_stats',
    name: 'Category Statistics',
    nameCN: '类目统计',
    type: 'chart',
    defaultVisible: true,
    description: '各类目商品数量柱状图'
  },
  user_growth: {
    id: 'user_growth',
    name: 'User Growth Chart',
    nameCN: '用户增长',
    type: 'chart',
    defaultVisible: true,
    description: '近6个月用户增长面积图'
  },
  insight_feed: {
    id: 'insight_feed',
    name: 'AI Insight Feed',
    nameCN: 'AI洞察流',
    type: 'feed',
    defaultVisible: true,
    description: 'AI生成的经营洞察和建议'
  },
  stats_cards: {
    id: 'stats_cards',
    name: 'Statistics Cards',
    nameCN: '统计卡片',
    type: 'stats',
    defaultVisible: true,
    description: '总商品、总用户、总订单、总收入概览'
  }
};

// 组件ID别名映射
const WIDGET_ALIASES: Record<string, WidgetId> = {
  // 英文
  'agent_status': 'agent_status',
  'agentstatus': 'agent_status',
  'agent': 'agent_status',
  'status': 'agent_status',
  'store_goal': 'store_goal',
  'storegoal': 'store_goal',
  'goal': 'store_goal',
  'target': 'store_goal',
  'quick_actions': 'quick_actions',
  'quickactions': 'quick_actions',
  'actions': 'quick_actions',
  'shortcuts': 'quick_actions',
  'pending_approvals': 'pending_approvals',
  'pendingapprovals': 'pending_approvals',
  'approvals': 'pending_approvals',
  'pending': 'pending_approvals',
  'sales_trend': 'sales_trend',
  'salestrend': 'sales_trend',
  'sales': 'sales_trend',
  'trend': 'sales_trend',
  'order_status': 'order_status',
  'orderstatus': 'order_status',
  'orders': 'order_status',
  'category_stats': 'category_stats',
  'categorystats': 'category_stats',
  'categories': 'category_stats',
  'user_growth': 'user_growth',
  'usergrowth': 'user_growth',
  'users': 'user_growth',
  'growth': 'user_growth',
  'insight_feed': 'insight_feed',
  'insightfeed': 'insight_feed',
  'insights': 'insight_feed',
  'feed': 'insight_feed',
  'stats_cards': 'stats_cards',
  'statscards': 'stats_cards',
  'stats': 'stats_cards',
  'overview': 'stats_cards',
  // 中文
  'Agent状态': 'agent_status',
  '状态栏': 'agent_status',
  '经营目标': 'store_goal',
  '目标': 'store_goal',
  '快捷操作': 'quick_actions',
  '快捷入口': 'quick_actions',
  '待审批': 'pending_approvals',
  '审批': 'pending_approvals',
  '审批列表': 'pending_approvals',
  '销售趋势': 'sales_trend',
  '销售图表': 'sales_trend',
  '订单状态': 'order_status',
  '订单分布': 'order_status',
  '类目统计': 'category_stats',
  '分类统计': 'category_stats',
  '用户增长': 'user_growth',
  '用户统计': 'user_growth',
  'AI洞察': 'insight_feed',
  '洞察': 'insight_feed',
  '洞察流': 'insight_feed',
  '统计卡片': 'stats_cards',
  '概览': 'stats_cards',
  '数据概览': 'stats_cards'
};

// ==================== 布局定义 ====================

export type LayoutMode = 'default' | 'compact' | 'analytics' | 'approvals' | 'custom';

// 预设布局
export const PRESET_LAYOUTS: Record<Exclude<LayoutMode, 'custom'>, WidgetId[]> = {
  default: [
    'agent_status', 'store_goal', 'quick_actions', 'pending_approvals',
    'stats_cards', 'sales_trend', 'order_status', 'category_stats',
    'user_growth', 'insight_feed'
  ],
  compact: ['agent_status', 'stats_cards', 'pending_approvals', 'insight_feed'],
  analytics: ['stats_cards', 'sales_trend', 'order_status', 'category_stats', 'user_growth'],
  approvals: ['agent_status', 'store_goal', 'pending_approvals', 'insight_feed']
};

// 布局别名
const LAYOUT_ALIASES: Record<string, LayoutMode> = {
  'default': 'default',
  '默认': 'default',
  '全部': 'default',
  'compact': 'compact',
  '紧凑': 'compact',
  '简洁': 'compact',
  'analytics': 'analytics',
  '分析': 'analytics',
  '数据分析': 'analytics',
  '报表': 'analytics',
  'approvals': 'approvals',
  '审批': 'approvals',
  '审批视图': 'approvals'
};

// ==================== 动作类型定义 ====================

export type DashboardActionType = 
  | 'configure_widgets'  // 配置组件显示
  | 'focus_widget'       // 聚焦单个组件
  | 'set_layout'         // 设置布局模式
  | 'refresh_widget'     // 刷新特定组件
  | 'set_time_range';    // 设置数据时间范围

export type TimeRange = 'today' | 'week' | 'month' | 'quarter' | 'year';

// 动作参数定义
export interface ConfigureWidgetsParams {
  show?: string[];
  hide?: string[];
}

export interface FocusWidgetParams {
  widget: string;
}

export interface SetLayoutParams {
  layout: string;
}

export interface RefreshWidgetParams {
  widgets: string[];
}

export interface SetTimeRangeParams {
  timeRange: string;
}

export type DashboardActionParams = 
  | ConfigureWidgetsParams 
  | FocusWidgetParams 
  | SetLayoutParams 
  | RefreshWidgetParams
  | SetTimeRangeParams;

// 仪表板动作接口
export interface DashboardAction {
  kind: 'dashboard_action';
  type: DashboardActionType;
  params: DashboardActionParams;
}

// ==================== 仪表板状态 ====================

export interface DashboardState {
  visibleWidgets: WidgetId[];
  layout: LayoutMode;
  focusedWidget: WidgetId | null;
  timeRange: TimeRange;
}

// 默认状态
export const DEFAULT_DASHBOARD_STATE: DashboardState = {
  visibleWidgets: PRESET_LAYOUTS.default,
  layout: 'default',
  focusedWidget: null,
  timeRange: 'week'
};

// ==================== 解析函数 ====================

/**
 * 标准化组件ID
 */
export function normalizeWidgetId(input: string): WidgetId | null {
  const normalized = input?.toLowerCase?.().trim().replace(/[-\s]/g, '_');
  if (!normalized) return null;
  
  // 直接匹配
  if (normalized in WIDGET_REGISTRY) {
    return normalized as WidgetId;
  }
  
  // 别名匹配
  if (WIDGET_ALIASES[input]) {
    return WIDGET_ALIASES[input];
  }
  if (WIDGET_ALIASES[normalized]) {
    return WIDGET_ALIASES[normalized];
  }
  
  return null;
}

/**
 * 标准化布局模式
 */
export function normalizeLayout(input: string): LayoutMode | null {
  const normalized = input?.toLowerCase?.().trim();
  if (!normalized) return null;
  
  if (normalized in PRESET_LAYOUTS) {
    return normalized as LayoutMode;
  }
  
  if (LAYOUT_ALIASES[input]) {
    return LAYOUT_ALIASES[input];
  }
  if (LAYOUT_ALIASES[normalized]) {
    return LAYOUT_ALIASES[normalized];
  }
  
  return null;
}

/**
 * 标准化时间范围
 */
export function normalizeTimeRange(input: string): TimeRange | null {
  const aliases: Record<string, TimeRange> = {
    'today': 'today',
    '今日': 'today',
    '今天': 'today',
    'week': 'week',
    '本周': 'week',
    '周': 'week',
    '7天': 'week',
    'month': 'month',
    '本月': 'month',
    '月': 'month',
    '30天': 'month',
    'quarter': 'quarter',
    '季度': 'quarter',
    '本季度': 'quarter',
    'year': 'year',
    '年': 'year',
    '本年': 'year',
    '全年': 'year'
  };
  
  const normalized = input?.toLowerCase?.().trim();
  return aliases[input] || aliases[normalized] || null;
}

/**
 * 从文本中提取仪表板动作
 */
export function extractDashboardAction(text: string): DashboardAction | null {
  if (!text || typeof text !== 'string') return null;

  // 解析标记块格式 [DASHBOARD_ACTION]...[/DASHBOARD_ACTION]
  const blockMatch = text.match(/\[DASHBOARD_ACTION\]([\s\S]*?)\[\/DASHBOARD_ACTION\]/i);
  if (blockMatch) {
    try {
      const parsed = JSON.parse(blockMatch[1].trim());
      return normalizeDashboardAction(parsed);
    } catch (e) {
      console.warn('解析 DASHBOARD_ACTION 标记块失败:', e);
    }
  }

  // 尝试解析整个文本为 JSON
  try {
    const parsed = JSON.parse(text);
    
    if (parsed.kind === 'dashboard_action') {
      return normalizeDashboardAction(parsed);
    }
    
    // 检查 metadata.actions
    if (parsed.metadata?.actions && Array.isArray(parsed.metadata.actions)) {
      for (const action of parsed.metadata.actions) {
        if (isDashboardActionType(action.type)) {
          return normalizeDashboardAction({
            kind: 'dashboard_action',
            type: action.type,
            params: action.params || action,
          });
        }
      }
    }
  } catch (e) {
    // 不是有效 JSON
  }

  // 尝试查找嵌入的 JSON 对象
  const jsonMatch = text.match(/\{[^{}]*"kind"\s*:\s*"dashboard_action"[^{}]*\}/);
  if (jsonMatch) {
    try {
      const parsed = JSON.parse(jsonMatch[0]);
      return normalizeDashboardAction(parsed);
    } catch (e) {
      // 忽略
    }
  }

  return null;
}

/**
 * 检查是否为仪表板动作类型
 */
function isDashboardActionType(type: string): type is DashboardActionType {
  return ['configure_widgets', 'focus_widget', 'set_layout', 'refresh_widget', 'set_time_range'].includes(type);
}

/**
 * 标准化仪表板动作对象
 */
function normalizeDashboardAction(raw: any): DashboardAction | null {
  if (!raw || typeof raw !== 'object') return null;

  const type = raw.type as DashboardActionType;
  if (!isDashboardActionType(type)) return null;

  const params = raw.params || raw;
  let normalizedParams: DashboardActionParams;

  switch (type) {
    case 'configure_widgets': {
      const show = (params.show || [])
        .map((w: string) => normalizeWidgetId(w))
        .filter(Boolean) as WidgetId[];
      const hide = (params.hide || [])
        .map((w: string) => normalizeWidgetId(w))
        .filter(Boolean) as WidgetId[];
      normalizedParams = { show, hide };
      break;
    }
    case 'focus_widget': {
      const widget = normalizeWidgetId(params.widget || params.focus);
      if (!widget) return null;
      normalizedParams = { widget };
      break;
    }
    case 'set_layout': {
      const layout = normalizeLayout(params.layout);
      if (!layout) return null;
      normalizedParams = { layout };
      break;
    }
    case 'refresh_widget': {
      const widgets = (params.widgets || params.refresh || [params.widget])
        .filter(Boolean)
        .map((w: string) => normalizeWidgetId(w))
        .filter(Boolean) as WidgetId[];
      normalizedParams = { widgets };
      break;
    }
    case 'set_time_range': {
      const timeRange = normalizeTimeRange(params.timeRange || params.range);
      if (!timeRange) return null;
      normalizedParams = { timeRange };
      break;
    }
    default:
      return null;
  }

  return {
    kind: 'dashboard_action',
    type,
    params: normalizedParams,
  };
}

// ==================== 执行函数 ====================

export interface DashboardExecuteResult {
  success: boolean;
  action: DashboardAction;
  newState: DashboardState;
  message: string;
}

/**
 * 执行仪表板动作
 */
export function executeDashboardAction(
  action: DashboardAction,
  currentState: DashboardState
): DashboardExecuteResult {
  const newState = { ...currentState };
  let message = '';

  try {
    switch (action.type) {
      case 'configure_widgets': {
        const params = action.params as ConfigureWidgetsParams;
        let visible = [...currentState.visibleWidgets];
        
        // 处理隐藏
        if (params.hide && params.hide.length > 0) {
          const hideSet = new Set(params.hide);
          visible = visible.filter(w => !hideSet.has(w));
        }
        
        // 处理显示
        if (params.show && params.show.length > 0) {
          const showWidgets = params.show as WidgetId[];
          // 如果指定了 show，则只显示这些组件
          if (!params.hide || params.hide.length === 0) {
            visible = showWidgets;
          } else {
            // 否则添加到现有列表
            showWidgets.forEach(w => {
              if (!visible.includes(w)) {
                visible.push(w);
              }
            });
          }
        }
        
        newState.visibleWidgets = visible;
        newState.layout = 'custom';
        message = `已更新组件显示：显示 ${visible.length} 个组件`;
        break;
      }
      
      case 'focus_widget': {
        const params = action.params as FocusWidgetParams;
        const widget = params.widget as WidgetId;
        newState.focusedWidget = widget;
        
        // 确保聚焦的组件是可见的
        if (!newState.visibleWidgets.includes(widget)) {
          newState.visibleWidgets = [...newState.visibleWidgets, widget];
        }
        
        const widgetMeta = WIDGET_REGISTRY[widget];
        message = `已聚焦到：${widgetMeta?.nameCN || widget}`;
        break;
      }
      
      case 'set_layout': {
        const params = action.params as SetLayoutParams;
        const layout = params.layout as LayoutMode;
        
        if (layout !== 'custom' && PRESET_LAYOUTS[layout]) {
          newState.visibleWidgets = [...PRESET_LAYOUTS[layout]];
          newState.layout = layout;
          newState.focusedWidget = null;
          
          const layoutNames: Record<LayoutMode, string> = {
            default: '默认布局',
            compact: '紧凑布局',
            analytics: '数据分析布局',
            approvals: '审批视图',
            custom: '自定义布局'
          };
          message = `已切换到${layoutNames[layout]}`;
        }
        break;
      }
      
      case 'refresh_widget': {
        const params = action.params as RefreshWidgetParams;
        const widgetNames = params.widgets
          .map(w => WIDGET_REGISTRY[w as WidgetId]?.nameCN || w)
          .join('、');
        message = `已刷新：${widgetNames}`;
        // 实际刷新逻辑由组件自己处理
        break;
      }
      
      case 'set_time_range': {
        const params = action.params as SetTimeRangeParams;
        newState.timeRange = params.timeRange as TimeRange;
        
        const rangeNames: Record<TimeRange, string> = {
          today: '今日',
          week: '本周',
          month: '本月',
          quarter: '本季度',
          year: '本年'
        };
        message = `数据时间范围已设置为：${rangeNames[newState.timeRange]}`;
        break;
      }
    }

    return {
      success: true,
      action,
      newState,
      message
    };
  } catch (error) {
    return {
      success: false,
      action,
      newState: currentState,
      message: `执行失败: ${error instanceof Error ? error.message : '未知错误'}`
    };
  }
}

// ==================== 校验函数 ====================

export interface DashboardValidationResult {
  ok: boolean;
  missing?: string[];
  warnings?: string[];
}

export function validateDashboardAction(action: DashboardAction): DashboardValidationResult {
  const missing: string[] = [];
  const warnings: string[] = [];

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

  if (!action.params) {
    missing.push('params');
    return { ok: false, missing };
  }

  switch (action.type) {
    case 'configure_widgets': {
      const params = action.params as ConfigureWidgetsParams;
      if ((!params.show || params.show.length === 0) && (!params.hide || params.hide.length === 0)) {
        warnings.push('未指定要显示或隐藏的组件');
      }
      break;
    }
    case 'focus_widget': {
      const params = action.params as FocusWidgetParams;
      if (!params.widget) {
        missing.push('widget');
      }
      break;
    }
    case 'set_layout': {
      const params = action.params as SetLayoutParams;
      if (!params.layout) {
        missing.push('layout');
      }
      break;
    }
    case 'refresh_widget': {
      const params = action.params as RefreshWidgetParams;
      if (!params.widgets || params.widgets.length === 0) {
        warnings.push('未指定要刷新的组件');
      }
      break;
    }
    case 'set_time_range': {
      const params = action.params as SetTimeRangeParams;
      if (!params.timeRange) {
        missing.push('timeRange');
      }
      break;
    }
  }

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

// ==================== 辅助函数 ====================

/**
 * 获取动作类型的中文描述
 */
export function getDashboardActionLabel(type: DashboardActionType): string {
  const labels: Record<DashboardActionType, string> = {
    configure_widgets: '配置组件',
    focus_widget: '聚焦组件',
    set_layout: '切换布局',
    refresh_widget: '刷新组件',
    set_time_range: '设置时间范围',
  };
  return labels[type] || type;
}

/**
 * 获取所有组件列表
 */
export function getAllWidgets(): WidgetMeta[] {
  return Object.values(WIDGET_REGISTRY);
}

/**
 * 获取所有布局列表
 */
export function getAllLayouts(): { id: LayoutMode; name: string; widgets: WidgetId[] }[] {
  return [
    { id: 'default', name: '默认布局', widgets: PRESET_LAYOUTS.default },
    { id: 'compact', name: '紧凑布局', widgets: PRESET_LAYOUTS.compact },
    { id: 'analytics', name: '数据分析', widgets: PRESET_LAYOUTS.analytics },
    { id: 'approvals', name: '审批视图', widgets: PRESET_LAYOUTS.approvals },
  ];
}
