import { JobContext } from '@livekit/agents';
import { TrackKind, RoomEvent, AudioFrame, AudioStream } from '@livekit/rtc-node';
import type { RemoteParticipant, RemoteTrack, RemoteTrackPublication } from '@livekit/rtc-node';
import fs from 'fs';
import path from 'path';

export class TestAgent {
  private readonly ctx: JobContext;
  private readonly combinedQueue: AudioFrame[];
  private readonly trackQueues: Map<string, AudioFrame[]>;

  constructor(ctx: JobContext) {
    this.ctx = ctx;
    this.combinedQueue = [];
    this.trackQueues = new Map();
  }

  async start(): Promise<void> {
    await this.ctx.connect();
    console.log(`Connected to room: ${this.ctx.room.name}`);

    this.ctx.room.on(RoomEvent.TrackSubscribed, (...args) => this.onTrackSubscribed(...args));
    this.ctx.addShutdownCallback(() => this.shutdown());
  }

  private onTrackSubscribed(track: RemoteTrack, _pub: RemoteTrackPublication, participant: RemoteParticipant): void {
    if (track.kind !== TrackKind.KIND_AUDIO) {
      return;
    }

    console.log(`Subscribed to ${track.kind} track from ${participant.identity}`);
    void this.processTrack(track, participant);
  }

  protected async processTrack(track: RemoteTrack, participant: RemoteParticipant): Promise<void> {
    const trackQueue: AudioFrame[] = [];
    this.trackQueues.set(participant.identity, trackQueue);

    const stream = new AudioStream(track);
    for await (const frame of stream) {
      this.combinedQueue.push(frame);
      trackQueue.push(frame);
    }
  }

  private async writeToFile(filePath: string, frames: AudioFrame[]): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      const fileStream = fs.createWriteStream(filePath);
      fileStream.on('finish', resolve);
      fileStream.on('error', reject);
      frames.forEach((frame) => fileStream.write(frame.data));
      fileStream.end();
    });
  }

  private async shutdown(): Promise<void> {
    try {
      const tempDir = path.join(process.cwd(), 'temp-audio-debug');

      const filePath = path.join(tempDir, `combined-48khz-${Date.now()}.raw`);
      await this.writeToFile(filePath, this.combinedQueue);
      console.log(`Written to combined file: ${filePath}`);

      for (const [identity, frames] of this.trackQueues.entries()) {
        const filePath = path.join(tempDir, `${identity}-48khz-${Date.now()}.raw`);
        await this.writeToFile(filePath, frames);
        console.log(`Written to track file: ${filePath}`);
      }
    } catch (err) {
      console.error({ err }, 'Error while shutting down the job');
    }
  }
}
