#!/usr/bin/env node
import { spawn } from 'child_process';
import { EOL } from 'os';

process.stdin.setEncoding("utf8");
var [, , ...argv] = process.argv;
var cmd = argv.length > 0 ? argv[0] : "node";
var cmdArgs = argv.length > 0 ? argv.slice(1) : ["dist/bin/cli.mjs", "feedback"];
var tick = 0;
var start = Date.now();
var logTimer = setInterval(() => {
  tick += 1;
  const elapsed = ((Date.now() - start) / 1e3).toFixed(1);
  process.stderr.write(`[progress] step=${tick} elapsed=${elapsed}s${EOL}`);
}, 1200);
function printHeader() {
  process.stdout.write(
    [
      "",
      "\u{1F4DD} Concurrent Feedback Collector",
      "   Type or paste your feedback. Submit by pressing Enter on an EMPTY line.",
      "   (EOF ends the session: Ctrl-D on macOS/Linux; Ctrl-Z then Enter on Windows.)",
      ""
    ].join(EOL) + EOL
  );
}
printHeader();
var pending = Promise.resolve();
var submissionCount = 0;
function runCommandWithInput(input) {
  submissionCount += 1;
  const n = submissionCount;
  process.stderr.write(`${EOL}[submit ${n}] launching "${cmd}" ${cmdArgs.join(" ")}${EOL}`);
  return new Promise((resolve) => {
    const child = spawn(cmd, cmdArgs, { stdio: ["pipe", "pipe", "pipe"] });
    child.stdout?.on("data", (d) => process.stderr.write(`[submit ${n}] stdout: ${d}`));
    child.stderr?.on("data", (d) => process.stderr.write(`[submit ${n}] stderr: ${d}`));
    child.on("close", (code) => {
      process.stderr.write(`[submit ${n}] exit code ${code ?? 0}${EOL}`);
      resolve(code ?? 0);
    });
    child.on("error", (err) => {
      process.stderr.write(`[submit ${n}] error: ${err.message}${EOL}`);
      resolve(1);
    });
    if (child.stdin) {
      child.stdin.write(input);
      if (!input.endsWith(EOL)) {
        child.stdin.write(EOL);
      }
      child.stdin.end();
    }
  });
}
function enqueueSubmission(input) {
  pending = pending.then(() => runCommandWithInput(input).then(() => {
  }));
  return pending;
}
var carry = "";
var buffer = "";
var lastLineWasBlank = false;
function submitBufferIfAny() {
  const content = buffer.trimEnd();
  buffer = "";
  if (content.length === 0) {
    return;
  }
  process.stdout.write(EOL + "===== SUBMITTING FEEDBACK BLOCK =====" + EOL);
  process.stdout.write(content + EOL);
  process.stdout.write("===== END BLOCK =====" + EOL);
  enqueueSubmission(content).then(() => {
    process.stdout.write(EOL + "\u2705 Submission processed. You can type another block." + EOL);
  }).catch((err) => {
    process.stderr.write(`Error submitting feedback: ${err}${EOL}`);
  });
}
process.stdin.on("data", (chunk) => {
  carry += chunk;
  const parts = carry.split(/\r?\n/);
  carry = parts.pop() ?? "";
  for (const line of parts) {
    const isBlank = line.trim().length === 0;
    if (isBlank && !lastLineWasBlank) {
      submitBufferIfAny();
      lastLineWasBlank = true;
      continue;
    }
    if (!isBlank) {
      buffer += line + EOL;
      lastLineWasBlank = false;
    } else {
      lastLineWasBlank = true;
    }
  }
});
process.stdin.on("end", async () => {
  if (carry.length) {
    buffer += carry;
  }
  submitBufferIfAny();
  await pending;
  clearInterval(logTimer);
  process.stderr.write(`${EOL}[progress] done. submissions=${submissionCount}${EOL}`);
  process.exit(0);
});
process.on("SIGINT", async () => {
  process.stderr.write(`${EOL}[progress] SIGINT received. Finalizing\u2026${EOL}`);
  submitBufferIfAny();
  await pending;
  clearInterval(logTimer);
  process.stderr.write(`[progress] done. submissions=${submissionCount}${EOL}`);
  process.exit(0);
});
process.on("uncaughtException", (err) => {
  process.stderr.write(`${EOL}[error] Uncaught exception: ${err.message}${EOL}`);
  clearInterval(logTimer);
  process.exit(1);
});
process.on("unhandledRejection", (reason) => {
  process.stderr.write(`${EOL}[error] Unhandled rejection: ${reason}${EOL}`);
  clearInterval(logTimer);
  process.exit(1);
});
//# sourceMappingURL=feedback-collector.mjs.map
//# sourceMappingURL=feedback-collector.mjs.map