/* eslint-disable no-console */
import { Sink, SinkConfig } from "./types.js";

/** Stdout sink: prints each line followed by newline. */
export class StdoutSink implements Sink {
    private buf: string[] = [];
    private flushEvery: number;

    constructor(cfg?: SinkConfig) {
        this.flushEvery = Math.max(1, cfg?.flushEvery ?? 1);
    }

    async init(): Promise<void> {
        // Nothing to initialize for stdout.
    }

    async write(line: string): Promise<void> {
        // Buffer lines to reduce write() syscalls if flushEvery > 1
        this.buf.push(line);
        if (this.buf.length >= this.flushEvery) {
            const chunk = this.buf.join("\n") + "\n";
            this.buf.length = 0;
            // Use stdout.write instead of console.log for performance
            await new Promise<void>((resolve, reject) => {
                process.stdout.write(chunk, (err) => (err ? reject(err) : resolve()));
            });
        }
    }

    async flush(): Promise<void> {
        if (this.buf.length === 0) return;
        const chunk = this.buf.join("\n") + "\n";
        this.buf.length = 0;
        await new Promise<void>((resolve, reject) => {
            process.stdout.write(chunk, (err) => (err ? reject(err) : resolve()));
        });
    }

    async close(): Promise<void> {
        await this.flush?.();
    }
}