/**
 * Operation Agent 数据迁移脚本
 * 将基础版本的数据迁移到增强版本
 */

// 基础版本数据结构
interface Store {
  id: string;
  merchantId: string;
  name: string;
  platform: string;
  platformShopId: string;
  description: string;
  status: 'active' | 'inactive' | 'pending' | 'suspended';
  created_at: string;
  updated_at: string;
}

interface Task {
  id: string;
  merchantId: string;
  storeId: string;
  taskType: 'PRICING' | 'LISTING' | 'AD_OPTIMIZATION';
  targetProducts: string[];
  constraints: {
    maxPrice?: number;
    minROI?: number;
    maxQuantity?: number;
  };
  priority: 'HIGH' | 'MEDIUM' | 'LOW';
  status: 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELLED';
  progress: number;
  description: string;
  logs?: string[];
  error?: string;
  created_at: string;
  updated_at: string;
  completed_at?: string;
}

// 增强版本数据结构
interface PlatformInfo {
  name: string;
  status: 'connected' | 'disconnected' | 'error';
  lastSync: string;
  orderCount: number;
  productCount: number;
  loginTime?: string;
  cookies?: boolean;
  proxy?: string;
}

interface TaskInfo {
  id: string;
  name: string;
  description?: string;
  platform: string;
  type: string;
  schedule: string;
  enabled: boolean;
  lastRun?: string;
  nextRun?: string;
  status: 'running' | 'success' | 'failed' | 'idle';
  progress?: number;
  result?: string;
  errorCount?: number;
  successCount?: number;
}

interface ClientInfo {
  id: string;
  name: string;
  ip: string;
  port: number;
  status: 'online' | 'offline' | 'connecting' | 'error';
  version: string;
  uptime: number;
  lastSeen: number;
  cpu: number;
  memory: number;
  disk: number;
  platform: string;
  tasks: number;
  platforms: number;
  region: string;
  group: string;
  tags: string[];
}

// 模拟基础版本数据
const mockStores: Store[] = [
  {
    id: 'store-001',
    merchantId: 'merchant-1',
    name: 'Amazon US Store',
    platform: 'amazon',
    platformShopId: 'AMZ-US-001',
    description: 'Amazon美国站点主店铺',
    status: 'active',
    created_at: '2024-01-15T08:00:00Z',
    updated_at: '2024-03-20T10:30:00Z',
  },
  {
    id: 'store-002',
    merchantId: 'merchant-1',
    name: 'Shopee SG Store',
    platform: 'shopee',
    platformShopId: 'SHP-SG-001',
    description: 'Shopee新加坡站点',
    status: 'active',
    created_at: '2024-02-10T09:00:00Z',
    updated_at: '2024-03-18T14:20:00Z',
  },
  {
    id: 'store-003',
    merchantId: 'merchant-1',
    name: 'AliExpress Store',
    platform: 'aliexpress',
    platformShopId: 'AE-001',
    description: 'AliExpress主店铺',
    status: 'pending',
    created_at: '2024-03-01T10:00:00Z',
    updated_at: '2024-03-15T16:45:00Z',
  },
];

const mockTasks: Task[] = [
  {
    id: 'task-001',
    merchantId: 'merchant-1',
    storeId: 'store-001',
    taskType: 'PRICING',
    targetProducts: ['prod-001', 'prod-002', 'prod-003'],
    constraints: { maxPrice: 100, minROI: 0.3, maxQuantity: 1000 },
    priority: 'HIGH',
    status: 'COMPLETED',
    progress: 100,
    description: '优化Amazon店铺商品定价',
    logs: [
      '任务开始: 2024-03-20T08:00:00Z',
      '正在分析商品价格: 2024-03-20T08:05:00Z',
      '正在优化定价策略: 2024-03-20T08:10:00Z',
      '任务完成: 2024-03-20T08:15:00Z',
    ],
    created_at: '2024-03-20T08:00:00Z',
    updated_at: '2024-03-20T08:15:00Z',
    completed_at: '2024-03-20T08:15:00Z',
  },
  {
    id: 'task-002',
    merchantId: 'merchant-1',
    storeId: 'store-002',
    taskType: 'LISTING',
    targetProducts: ['prod-004', 'prod-005'],
    constraints: { maxPrice: 50, maxQuantity: 500 },
    priority: 'MEDIUM',
    status: 'RUNNING',
    progress: 60,
    description: 'Shopee店铺商品上架',
    logs: [
      '任务开始: 2024-03-21T10:00:00Z',
      '正在准备商品数据: 2024-03-21T10:05:00Z',
      '正在上传商品信息: 2024-03-21T10:10:00Z',
    ],
    created_at: '2024-03-21T10:00:00Z',
    updated_at: '2024-03-21T10:20:00Z',
  },
];

// 状态转换映射
const storeStatusMap: Record<string, 'connected' | 'disconnected' | 'error'> = {
  active: 'connected',
  inactive: 'disconnected',
  pending: 'disconnected',
  suspended: 'error'
};

const taskStatusMap: Record<string, 'running' | 'success' | 'failed' | 'idle'> = {
  PENDING: 'idle',
  RUNNING: 'running',
  COMPLETED: 'success',
  FAILED: 'failed',
  CANCELLED: 'idle'
};

const taskTypeMap: Record<string, string> = {
  PRICING: 'optimize',
  LISTING: 'publish',
  AD_OPTIMIZATION: 'optimize'
};

// 迁移函数
function migrateStores(stores: Store[]): PlatformInfo[] {
  return stores.map(store => ({
    name: store.platform.charAt(0).toUpperCase() + store.platform.slice(1),
    status: storeStatusMap[store.status],
    lastSync: new Date(store.updated_at).toLocaleString(),
    orderCount: Math.floor(Math.random() * 200) + 50,
    productCount: Math.floor(Math.random() * 300) + 100,
    loginTime: new Date(store.created_at).toLocaleString(),
    cookies: store.status === 'active',
    proxy: `socks5://proxy-${store.platform}.example.com:1080`
  }));
}

function migrateTasks(tasks: Task[]): TaskInfo[] {
  return tasks.map(task => ({
    id: task.id,
    name: task.description,
    description: `目标商品: ${task.targetProducts.join(', ')}`,
    platform: task.storeId.includes('amazon') ? 'amazon' : 
              task.storeId.includes('shopee') ? 'shopee' : 'all',
    type: taskTypeMap[task.taskType],
    schedule: '0 * * * *', // 每小时执行
    enabled: true,
    lastRun: task.updated_at ? new Date(task.updated_at).toLocaleString() : undefined,
    nextRun: new Date(Date.now() + 3600000).toLocaleString(), // 1小时后
    status: taskStatusMap[task.status],
    progress: task.progress,
    errorCount: task.error ? 1 : 0,
    successCount: task.status === 'COMPLETED' ? 1 : 0
  }));
}

function createDefaultClient(): ClientInfo {
  return {
    id: 'client-1',
    name: '默认客户端',
    ip: '192.168.1.100',
    port: 8080,
    status: 'online',
    version: '2.0.0',
    uptime: 3600,
    lastSeen: Date.now(),
    cpu: 30,
    memory: 45,
    disk: 60,
    platform: 'windows',
    tasks: mockTasks.length,
    platforms: mockStores.length,
    region: '华东',
    group: '生产组',
    tags: ['default', 'production']
  };
}

// 执行迁移
const migratedPlatforms = migrateStores(mockStores);
const migratedTasks = migrateTasks(mockTasks);
const defaultClient = createDefaultClient();

// 输出迁移结果
console.log('=== 数据迁移结果 ===');
console.log('\n1. 店铺数据迁移:');
console.log(JSON.stringify(migratedPlatforms, null, 2));

console.log('\n2. 任务数据迁移:');
console.log(JSON.stringify(migratedTasks, null, 2));

console.log('\n3. 默认客户端:');
console.log(JSON.stringify(defaultClient, null, 2));

console.log('\n=== 迁移完成 ===');

// 导出迁移数据
export {
  migratedPlatforms,
  migratedTasks,
  defaultClient
};
