import { ICollector, CollectionResult } from '../../core/collectors';
import { logger } from '../../utils/logger';

/**
 * [BE-P101] 采集服务
 * 负责从指定URL采集商品数据，支持多平台采集器
 */

// 模拟采集器（用于开发和测试）
class MockCollector implements ICollector {
  private platform: string;

  constructor(platform: string) {
    this.platform = platform;
  }

  async collect(url: string): Promise<CollectionResult> {
    logger.info(`[MockCollector] Collecting from ${url}`);

    // 模拟延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    return {
      success: true,
      data: {
        url,
        productId: `MOCK-${Date.now()}`,
        title: `Sample Product from ${this.platform}`,
        description: 'This is a sample product description for development and testing purposes.',
        mainImage: 'https://example.com/image.jpg',
        images: [
          'https://example.com/image1.jpg',
          'https://example.com/image2.jpg',
          'https://example.com/image3.jpg',
        ],
        price: 99.99,
        currency: 'USD',
        originalPrice: 129.99,
        attributes: {
          color: 'red',
          size: 'M',
          material: 'cotton',
        },
        skus: [
          {
            skuId: 'SKU-001',
            attributes: { color: 'red', size: 'M' },
            price: 99.99,
            stock: 100,
          },
          {
            skuId: 'SKU-002',
            attributes: { color: 'blue', size: 'L' },
            price: 109.99,
            stock: 50,
          },
        ],
        shopName: 'Sample Shop',
        shopId: 'SHOP-001',
        sales: 1000,
        rating: 4.5,
        length_cm: 30,
        width_cm: 20,
        height_cm: 10,
        weight_kg: 0.5,
      },
      metadata: {
        platform: this.platform,
        url,
        timestamp: new Date().toISOString(),
        duration: 500,
      },
    };
  }

  validateUrl(url: string): boolean {
    return url.includes(this.platform.toLowerCase()) || url.includes('example.com');
  }

  parseData(rawData: any): any {
    return rawData;
  }
}

export class CrawlerService {
  private collectors: Map<string, ICollector> = new Map();

  constructor() {
    // 注册模拟采集器
    this.registerCollector('alibaba', new MockCollector('alibaba'));
    this.registerCollector('1688', new MockCollector('1688'));
    this.registerCollector('amazon', new MockCollector('amazon'));
    this.registerCollector('aliexpress', new MockCollector('aliexpress'));
  }

  /**
   * 注册采集器
   */
  registerCollector(platform: string, collector: ICollector): void {
    this.collectors.set(platform.toLowerCase(), collector);
    logger.info(`[CrawlerService] Registered collector for platform: ${platform}`);
  }

  /**
   * 采集商品数据
   */
  async crawl(url: string, platform?: string, useSandbox: boolean = false): Promise<any> {
    logger.info(`[CrawlerService] Crawling URL: ${url}, platform: ${platform}, sandbox: ${useSandbox}`);

    // 确定平台
    const targetPlatform = platform || this.detectPlatform(url);
    if (!targetPlatform) {
      throw new Error(`Cannot detect platform for URL: ${url}`);
    }

    // 获取采集器
    const collector = this.collectors.get(targetPlatform.toLowerCase());
    if (!collector) {
      throw new Error(`No collector registered for platform: ${targetPlatform}`);
    }

    // 验证URL
    if (!collector.validateUrl(url)) {
      throw new Error(`URL ${url} is not valid for platform ${targetPlatform}`);
    }

    // 执行采集
    const result = await collector.collect(url);

    if (!result.success) {
      throw new Error(`Collection failed: ${result.error}`);
    }

    return result.data;
  }

  /**
   * 批量采集
   */
  async batchCrawl(
    urls: Array<{ url: string; platform?: string }>,
    useSandbox: boolean = false
  ): Promise<Array<{ url: string; success: boolean; data?: any; error?: string }>> {
    const results = await Promise.all(
      urls.map(async ({ url, platform }) => {
        try {
          const data = await this.crawl(url, platform, useSandbox);
          return { url, success: true, data };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Unknown error';
          logger.error(`[CrawlerService] Batch crawl failed for ${url}:`, errorMessage);
          return { url, success: false, error: errorMessage };
        }
      })
    );

    return results;
  }

  /**
   * 检测平台
   */
  private detectPlatform(url: string): string | null {
    const platformPatterns: Record<string, RegExp> = {
      alibaba: /alibaba\.com|1688\.com/,
      amazon: /amazon\./,
      aliexpress: /aliexpress\.com/,
      shopee: /shopee\./,
      temu: /temu\.com/,
      tiktok: /tiktok\.com/,
    };

    for (const [platform, pattern] of Object.entries(platformPatterns)) {
      if (pattern.test(url)) {
        return platform;
      }
    }

    // 默认返回 mock 平台用于测试
    return 'alibaba';
  }

  /**
   * 获取已注册的平台列表
   */
  getRegisteredPlatforms(): string[] {
    return Array.from(this.collectors.keys());
  }
}
