import { logger } from '../../utils/logger';

export interface ShopIsolationConfig {
  shopId: string;
  profileDir: string;
  proxy?: {
    host: string;
    port: number;
    username?: string;
    password?: string;
  };
  fingerprintPolicy: 'STRICT' | 'BALANCED' | 'LAX';
  maxConcurrency: number;
}

/**
 * [CORE_NODE_02] 店铺级隔离策略 (Shop Isolation Policy)
 * @description 保证每个店铺在独立的指纹、IP 与并发环境下运行
 */
export class ShopIsolationService {
  /**
   * 获取店铺执行上下文
   */
  static async getIsolationContext(shopId: string): Promise<ShopIsolationConfig> {
    logger.info(`[Isolation] Fetching context for Shop: ${shopId}`);

    // 实际业务中应从 cf_shop_configs 表查询
    return {
      shopId,
      profileDir: `/data/profiles/${shopId}`,
      proxy: { host: '1.2.3.4', port: 8080 },
      fingerprintPolicy: 'STRICT',
      maxConcurrency: 1 // 默认同一时间只允许一个任务
    };
  }

  /**
   * 并发约束检查
   */
  static async checkConcurrency(shopId: string): Promise<boolean> {
    logger.info(`[Isolation] Checking concurrency for Shop: ${shopId}`);
    // 实际业务中应查询 cf_tasks 表中 status=EXECUTING 且 shopId 匹配的记录数
    const currentExecuting = 0; // Mock
    const config = await this.getIsolationContext(shopId);
    
    return currentExecuting < config.maxConcurrency;
  }

  /**
   * 生成节点执行参数
   * @description 将隔离策略转化为 Playwright 可用的 launchOptions
   */
  static async generateLaunchOptions(shopId: string) {
    const config = await this.getIsolationContext(shopId);
    
    return {
      userDataDir: config.profileDir,
      proxy: config.proxy ? { server: `http://${config.proxy.host}:${config.proxy.port}` } : undefined,
      args: [
        '--disable-blink-features=AutomationControlled',
        `--user-agent=CrawlfulBot/${shopId}` // 模拟特定 UA
      ]
    };
  }
}
