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

export interface NodeInfo {
  nodeId: string;
  version: string;
  os: string;
  shops: string[]; // 该节点管理的店铺列表
  status: 'online' | 'offline';
  lastHeartbeat: number;
}

export interface TaskReceipt {
  taskId: string;
  traceId: string;
  status: 'success' | 'failed';
  errorType?: 'RETRYABLE' | 'MANUAL_INTERVENTION';
  errorMessage?: string;
  resultData?: any;
}

/**
 * [CORE_NODE_03] 节点协议标准
 * @description 定义 Win 节点与 Hub 之间的通讯契约
 */
export class NodeProtocolService {
  /**
   * 节点注册 (register)
   */
  static async register(info: NodeInfo): Promise<boolean> {
    logger.info(`[Protocol] Node register: ${info.nodeId} (v${info.version})`);
    // 实际业务中应记录节点元数据并下发 sessionKey
    return true;
  }

  /**
   * 心跳上报 (heartbeat)
   */
  static async heartbeat(nodeId: string): Promise<void> {
    logger.info(`[Protocol] Heartbeat from node: ${nodeId}`);
    // 更新节点的 lastHeartbeat
  }

  /**
   * 拉取任务 (pull-task)
   */
  static async pullTask(nodeId: string): Promise<any | null> {
    logger.info(`[Protocol] Node ${nodeId} pulling tasks`);
    // 实际业务中应从任务队列获取匹配该节点 shopIds 的任务
    return null; 
  }

  /**
   * 上报日志 (report-log)
   */
  static async reportLog(taskId: string, log: string): Promise<void> {
    logger.info(`[Protocol] Task ${taskId} log: ${log.substring(0, 50)}...`);
    // 写入 cf_task_logs
  }

  /**
   * 完成任务 (complete-task)
   */
  static async completeTask(receipt: TaskReceipt): Promise<void> {
    logger.info(`[Protocol] Task ${receipt.taskId} completed with status: ${receipt.status}`);
    // 触发状态机跳转与对账流程
  }
}
