/**
 * 能力同步模块 - 静态能力定义
 * 数据库 system_capabilities 表已删除，现使用纯静态配置
 */

import { ADMIN_OPERATIONS, AdminOperation } from '@/types/adminOperations';

// 页面操作定义
export const PAGE_ACTIONS = {
  navigate: {
    type: 'navigate',
    name: '导航',
    description: '导航到指定页面',
    params: [
      { name: 'tab', type: 'string', required: true, description: '目标页面标识', enum: ['home', 'overview', 'products', 'orders', 'users', 'categories', 'brands', 'banners', 'coupons', 'aftersales', 'transactions', 'marketing'] },
      { name: 'path', type: 'string', required: false, description: '完整路径' }
    ],
    examples: [
      { input: '打开商品管理', output: { type: 'navigate', params: { tab: 'products' } } },
      { input: '去订单页面', output: { type: 'navigate', params: { tab: 'orders' } } }
    ]
  },
  filter: {
    type: 'filter',
    name: '过滤',
    description: '过滤页面数据',
    params: [
      { name: 'tab', type: 'string', required: true, description: '目标页面' },
      { name: 'filters', type: 'object', required: true, description: '过滤条件' }
    ],
    examples: [
      { input: '显示待发货订单', output: { type: 'filter', params: { tab: 'orders', filters: { status: 'pending' } } } }
    ]
  },
  sort: {
    type: 'sort',
    name: '排序',
    description: '排序页面数据',
    params: [
      { name: 'tab', type: 'string', required: true, description: '目标页面' },
      { name: 'field', type: 'string', required: true, description: '排序字段' },
      { name: 'direction', type: 'string', required: true, description: '排序方向', enum: ['asc', 'desc'] }
    ],
    examples: [
      { input: '按价格排序', output: { type: 'sort', params: { tab: 'products', field: 'price', direction: 'desc' } } }
    ]
  },
  search: {
    type: 'search',
    name: '搜索',
    description: '搜索页面数据',
    params: [
      { name: 'tab', type: 'string', required: true, description: '目标页面' },
      { name: 'keyword', type: 'string', required: true, description: '搜索关键词' }
    ],
    examples: [
      { input: '搜索iPhone', output: { type: 'search', params: { tab: 'products', keyword: 'iPhone' } } }
    ]
  },
  display_data: {
    type: 'display_data',
    name: '显示数据',
    description: '高亮显示特定数据',
    params: [
      { name: 'tab', type: 'string', required: true, description: '目标页面' },
      { name: 'ids', type: 'array', required: false, description: '要高亮的ID数组' },
      { name: 'data', type: 'array', required: false, description: '直接传入的数据' }
    ],
    examples: []
  },
  set_page_state: {
    type: 'set_page_state',
    name: '设置页面状态',
    description: '综合设置页面状态',
    params: [
      { name: 'tab', type: 'string', required: true, description: '目标页面' },
      { name: 'filters', type: 'object', required: false, description: '过滤条件' },
      { name: 'sort', type: 'object', required: false, description: '排序设置' },
      { name: 'search', type: 'string', required: false, description: '搜索关键词' },
      { name: 'highlightIds', type: 'array', required: false, description: '高亮ID' }
    ],
    examples: [
      { input: '显示Apple商品并按价格排序', output: { type: 'set_page_state', params: { tab: 'products', filters: { brand: 'Apple' }, sort: { field: 'price', direction: 'desc' } } } }
    ]
  }
};

// 页面映射
export const PAGE_MAPPING = {
  home: { name: '首页/AI助理', description: 'AI对话主页' },
  overview: { name: '系统概览', description: '仪表盘' },
  products: { name: '商品管理', description: '管理商品', filterFields: ['category', 'brand', 'is_active', 'is_hot', 'lowStock'], sortFields: ['price', 'stock_quantity', 'created_at', 'monthly_sales'] },
  orders: { name: '订单管理', description: '管理订单', filterFields: ['status', 'user_id'], sortFields: ['created_at', 'total_amount'] },
  users: { name: '用户管理', description: '管理用户', filterFields: ['role'], sortFields: ['created_at', 'last_login'] },
  categories: { name: '分类管理', description: '管理分类', filterFields: ['is_active', 'parent_id'], sortFields: ['display_order', 'created_at'] },
  brands: { name: '品牌管理', description: '管理品牌', filterFields: ['is_active'], sortFields: ['display_order', 'created_at'] },
  banners: { name: '横幅管理', description: '管理横幅', filterFields: ['is_active'], sortFields: ['display_order'] },
  coupons: { name: '优惠券管理', description: '管理优惠券', filterFields: ['status', 'type'], sortFields: ['created_at', 'end_date'] },
  aftersales: { name: '售后管理', description: '处理售后', filterFields: ['status', 'type'], sortFields: ['created_at'] },
  transactions: { name: '交易管理', description: '查看交易', filterFields: [], sortFields: ['created_at'] },
  marketing: { name: '营销活动', description: '管理促销', filterFields: [], sortFields: [] }
};

// 转换 AdminOperation 为静态格式
function convertAdminOperation(op: AdminOperation): any {
  return {
    category: 'data_action',
    type: op.type,
    name: op.name,
    description: op.description,
    params: op.params,
    examples: op.examples,
    metadata: { permissions: op.permissions, operationCategory: op.category }
  };
}

// 获取所有能力（静态版本，不再访问数据库）
export function getCapabilities(): any {
  const result: any = {
    pageActions: {},
    dataActions: {},
    metadata: {}
  };

  // 页面操作
  Object.entries(PAGE_ACTIONS).forEach(([key, action]) => {
    result.pageActions[action.type] = {
      type: action.type,
      name: action.name,
      description: action.description,
      params: action.params,
      examples: action.examples
    };
  });

  // 数据操作
  Object.values(ADMIN_OPERATIONS).forEach((op) => {
    const converted = convertAdminOperation(op);
    result.dataActions[op.type] = {
      type: op.type,
      name: op.name,
      description: op.description,
      params: op.params,
      examples: op.examples,
      permissions: op.permissions,
      operationCategory: op.category
    };
  });

  // 元数据
  result.metadata = {
    page_mapping: {
      name: '页面映射',
      description: '所有管理页面的标识和信息',
      data: PAGE_MAPPING
    },
    response_format: {
      name: 'AI响应格式',
      description: '当需要执行操作时，在回复中包含标记块或JSON对象',
      actionKinds: {
        page_action: {
          description: '页面操作，用于导航、筛选、排序、搜索等',
          types: ['navigate', 'filter', 'sort', 'search', 'set_page_state', 'display_data'],
          format: '[PAGE_ACTION]{...}[/PAGE_ACTION]'
        },
        data_action: {
          description: '数据操作，用于CRUD等后端操作',
          types: Object.keys(ADMIN_OPERATIONS),
          format: '[DATA_ACTION]{...}[/DATA_ACTION]'
        }
      }
    }
  };

  return result;
}

// 兼容旧API - 同步函数现在是空操作
export async function syncCapabilitiesToDatabase(): Promise<{ success: boolean; synced: number; errors: string[] }> {
  console.log('syncCapabilitiesToDatabase: No-op (system_capabilities table removed)');
  return { success: true, synced: 0, errors: [] };
}

// 兼容旧API - 从静态配置获取
export async function getCapabilitiesFromDatabase(): Promise<any> {
  return getCapabilities();
}
