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

export interface WorkerInfo {
  id: string;
  type: 'crawler' | 'optimizer' | 'publisher';
  status: 'idle' | 'busy' | 'offline';
  load: number; // 0-100
  lastSeen: number;
}

export interface WorkerTask {
  id: string;
  type: string;
  payload: any;
  priority: number;
  tenantId: string;
}

/**
 * [CORE_WORK_01] 容器化采集调度 (Worker Hub)
 * @description 负责管理分布式 Worker 资源池，执行任务调度与负载均衡
 */
export class WorkerHub {
  private static workers: Map<string, WorkerInfo> = new Map();
  private static taskQueue: WorkerTask[] = [];

  /**
   * 注册 Worker
   */
  static registerWorker(worker: WorkerInfo) {
    logger.info(`[WorkerHub] Registering worker: ${worker.id} (${worker.type})`);
    this.workers.set(worker.id, { ...worker, lastSeen: Date.now() });
  }

  /**
   * 提交任务到调度中心
   */
  static async submitTask(task: WorkerTask): Promise<void> {
    logger.info(`[WorkerHub] New task submitted: ${task.id} for Tenant: ${task.tenantId}`);
    this.taskQueue.push(task);
    this.dispatch();
  }

  /**
   * 静态方法：添加任务（兼容旧调用）
   */
  static async addJob(queueName: string, jobData: any, options?: any): Promise<{ id: string }> {
    const taskId = jobData.retryCount ? `job-${Date.now()}-${jobData.retryCount}` : `job-${Date.now()}`;
    const workerTask: WorkerTask = {
      id: taskId,
      type: jobData.syncType || 'unknown',
      payload: jobData,
      priority: 5,
      tenantId: jobData.syncOptions?.tenantId || 'unknown'
    };
    await this.submitTask(workerTask);
    return { id: taskId };
  }

  /**
   * 任务调度与负载均衡 (Dispatch)
   */
  private static dispatch() {
    if (this.taskQueue.length === 0) return;

    // 按优先级排序
    this.taskQueue.sort((a, b) => b.priority - a.priority);

    const task = this.taskQueue[0];
    const availableWorker = this.findBestWorker(task.type as any);

    if (availableWorker) {
      logger.info(`[WorkerHub] Dispatching task ${task.id} to worker ${availableWorker.id}`);
      this.taskQueue.shift();
      // 实际应通过 MQ 或 gRPC 发送给 Worker
      availableWorker.status = 'busy';
    } else {
      logger.warn(`[WorkerHub] No available workers for task type: ${task.type}. Task ${task.id} queued.`);
    }
  }

  /**
   * 寻找负载最低的可用 Worker
   */
  private static findBestWorker(type: 'crawler' | 'optimizer' | 'publisher'): WorkerInfo | undefined {
    return Array.from(this.workers.values())
      .filter(w => w.type === type && w.status === 'idle')
      .sort((a, b) => a.load - b.load)[0];
  }

  /**
   * 获取资源池摘要
   */
  static getPoolSummary() {
    return {
      totalWorkers: this.workers.size,
      activeWorkers: Array.from(this.workers.values()).filter(w => w.status !== 'offline').length,
      queueDepth: this.taskQueue.length
    };
  }
}
