import type { Order } from "../../domain/src/types";

export interface HedgeCfg { kp:number; ki:number; Qmax:number; minIntervalMs:number; }

export interface HedgeResult {
  hedged: number;
  orderId?: string;
  clientId?: string;
}

export class HedgeEngine {
  private integ=0; private last=0;
  constructor(private cfg:HedgeCfg, private place:(o:Order)=>Promise<{id:string}>, private getMid:()=>number|undefined){}
  compute(pos:number){ this.integ += pos; const raw = this.cfg.kp*pos + this.cfg.ki*this.integ; return Math.max(Math.min(raw, this.cfg.Qmax), -this.cfg.Qmax); }
  async maybeHedge(symbol:string, delta:number): Promise<HedgeResult> {
    const now=Date.now(); if (now-this.last < this.cfg.minIntervalMs) return { hedged: 0 };
    const q=this.compute(delta); if (Math.abs(q)<1e-8) return { hedged: 0 };
    const mid = this.getMid() ?? 0;
    const side = q>0? "sell":"buy";
    const clientId = `hedge-${now}`;
    const { id } = await this.place({ clientId, symbol, side: side as any, px: mid, sz: Math.abs(q), tif:"IOC" });
    this.last = now;
    return { hedged: q, orderId: id, clientId };
  }
}
