const { LatestCaptionGate } = require("../transcription/stabilizer");

class CaptionDeliveryAdapter {
  async test() { throw new Error("Caption delivery test is not implemented."); }
  async start() { throw new Error("Caption delivery start is not implemented."); }
  async deliver() { throw new Error("Caption delivery is not implemented."); }
  async pause() {}
  async resume() {}
  async stop() {}
  async health() { return { healthy: false, state: "unavailable" }; }
}

class CompanionCaptionDeliveryAdapter extends CaptionDeliveryAdapter {
  constructor(send) { super(); this.send = send; this.gate = new LatestCaptionGate(); this.state = "idle"; this.testMode = false; }
  async test() { return { supported: true, mode: "simulated", note: "The companion simulates the exact outgoing native-caption stream without sending it to Twitch." }; }
  async start(options = {}) { this.testMode = Boolean(options.testMode); this.state = "running"; return this.health(); }
  async deliver(event) {
    if (this.state !== "running" || !this.gate.accept(event)) return { disposition: "obsolete_or_paused" };
    this.send("caption", { ...event, delivery: { disposition: this.testMode ? "simulated" : "forwarded_to_obs" } }, event.session_id);
    return { disposition: this.testMode ? "simulated" : "forwarded_to_obs" };
  }
  async pause() { this.state = "paused"; }
  async resume() { this.state = "running"; }
  async stop() { this.state = "idle"; }
  async health() { return { healthy: this.state !== "idle", state: this.state, adapter: "companion_obs_native", test_mode: this.testMode }; }
}

module.exports = { CaptionDeliveryAdapter, CompanionCaptionDeliveryAdapter };
