export interface FillRateMonitorOptions {
  windowSeconds?: number;      // 统计窗口（秒）
  minSamples?: number;          // 最小样本数
}

export interface FillEvent {
  ts: number;
  isMaker: boolean;             // true = maker fill, false = taker fill
  isSelfTrade: boolean;         // 是否自成交
  symbol: string;
}

export interface FillRateMetrics {
  totalFills: number;           // 总成交次数
  makerFills: number;           // maker 成交次数
  takerFills: number;           // taker 成交次数
  selfTrades: number;           // 自成交次数
  fillsPerMinute: number;       // 每分钟成交次数
  makerRatio: number;           // maker 成交占比 (0-1)
  selfTradeRatio: number;       // 自成交占比 (0-1)
  windowStartTs: number;        // 窗口起始时间
  windowEndTs: number;          // 窗口结束时间
}

/**
 * 监控成交率、maker/taker 占比、自成交率等 KPI
 * 用于闭环控制网格参数
 */
export class FillRateMonitor {
  private readonly windowSeconds: number;
  private readonly minSamples: number;
  private readonly history: FillEvent[] = [];

  constructor(options: FillRateMonitorOptions = {}) {
    this.windowSeconds = options.windowSeconds ?? 300;  // 默认 5 分钟窗口
    this.minSamples = options.minSamples ?? 2;          // 降低到2次成交即可启动
  }

  /**
   * 记录一次成交事件
   */
  recordFill(event: Omit<FillEvent, 'ts'> & { ts?: number }): void {
    const ts = event.ts ?? Date.now();
    this.history.push({
      ts,
      isMaker: event.isMaker,
      isSelfTrade: event.isSelfTrade,
      symbol: event.symbol
    });

    // 清理超出窗口的历史数据
    const cutoff = ts - this.windowSeconds * 1000;
    while (this.history.length > 0 && this.history[0]!.ts < cutoff) {
      this.history.shift();
    }
  }

  /**
   * 获取当前窗口内的成交率指标
   */
  getMetrics(symbol?: string): FillRateMetrics | undefined {
    if (this.history.length < this.minSamples) {
      return undefined;
    }

    // 过滤指定 symbol（如果提供）
    const relevant = symbol
      ? this.history.filter(e => e.symbol === symbol)
      : this.history;

    if (relevant.length === 0) {
      return undefined;
    }

    const totalFills = relevant.length;
    const makerFills = relevant.filter(e => e.isMaker).length;
    const takerFills = relevant.filter(e => !e.isMaker).length;
    const selfTrades = relevant.filter(e => e.isSelfTrade).length;

    const windowStartTs = relevant[0]!.ts;
    const windowEndTs = relevant[relevant.length - 1]!.ts;
    const windowMinutes = (windowEndTs - windowStartTs) / (1000 * 60);

    const fillsPerMinute = windowMinutes > 0 ? totalFills / windowMinutes : 0;
    const makerRatio = totalFills > 0 ? makerFills / totalFills : 0;
    const selfTradeRatio = totalFills > 0 ? selfTrades / totalFills : 0;

    return {
      totalFills,
      makerFills,
      takerFills,
      selfTrades,
      fillsPerMinute,
      makerRatio,
      selfTradeRatio,
      windowStartTs,
      windowEndTs
    };
  }

  /**
   * 重置历史记录
   */
  reset(): void {
    this.history.length = 0;
  }

  /**
   * 获取状态信息（用于日志）
   */
  getStatus(symbol?: string) {
    const metrics = this.getMetrics(symbol);
    return {
      historySize: this.history.length,
      windowSeconds: this.windowSeconds,
      metrics
    };
  }
}
