import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import path from "node:path";
export const COMMAND_OUTPUT_SPILLOVER_LINE_LIMIT = 300;
export const LONG_COMMAND_LINE_LIMIT = 300;
export const MAX_COMMAND_OUTPUT_BYTES = 128 * 1024;
export function toDisplayPath(targetPath) {
    return targetPath.replace(/\\/g, "/");
}
function padDatePart(value) {
    return String(value).padStart(2, "0");
}
export function countOutputLines(output) {
    if (!output) {
        return 0;
    }
    const normalized = output.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
    const withoutTrailingLineBreak = normalized.endsWith("\n")
        ? normalized.slice(0, -1)
        : normalized;
    return withoutTrailingLineBreak
        ? withoutTrailingLineBreak.split("\n").length
        : 1;
}
function buildCommandArtifactPath(workspaceRoot, now, suffix, extension) {
    const year = now.getFullYear();
    const month = padDatePart(now.getMonth() + 1);
    const day = padDatePart(now.getDate());
    const hour = padDatePart(now.getHours());
    const minute = padDatePart(now.getMinutes());
    const timestamp = `${year}${month}${day}-${hour}${minute}${padDatePart(now.getSeconds())}-${String(now.getMilliseconds()).padStart(3, "0")}-${process.pid}-${randomUUID().slice(0, 8)}`;
    return path.join(workspaceRoot, ".agentswork", "acode", "cmd-dist", `${year}-${month}-${day}`, hour, minute, `${timestamp}-${suffix}.${extension}`);
}
export async function writeCommandArtifactFile(workspaceRoot, suffix, extension, content, now = new Date()) {
    const targetPath = buildCommandArtifactPath(workspaceRoot, now, suffix, extension);
    await fs.mkdir(path.dirname(targetPath), { recursive: true });
    await fs.writeFile(targetPath, content, "utf-8");
    return targetPath;
}
export function buildCommandOutputSpilloverContent(input) {
    return [
        `Command: ${input.commandText}`,
        `Command file: ${input.commandFilePath ?? "null"}`,
        `Command line count: ${input.commandLineCount}`,
        `CWD: ${input.cwd}`,
        `Started: ${input.startedAt.toISOString()}`,
        `Ended: ${input.endedAt.toISOString()}`,
        `Exit code: ${input.exitCode ?? "null"}`,
        `Signal: ${input.signal ?? "null"}`,
        `Timed out: ${input.timedOut}`,
        `Timed out by inactivity: ${input.inactivityTimedOut}`,
        "",
        "--- stdout ---",
        input.stdout,
        "",
        "--- stderr ---",
        input.stderr,
    ].join("\n");
}
export function formatCommandOutputSpilloverStdout(outputFilePath, outputLineCount) {
    return [
        `[ACode] 命令输出超过 ${COMMAND_OUTPUT_SPILLOVER_LINE_LIMIT} 行（共 ${outputLineCount} 行），完整输出已写入: ${toDisplayPath(outputFilePath)}`,
        "[ACode] Agent 可自行读取该文件，或在该文件中搜索需要的内容。",
        "",
    ].join("\n");
}
export function truncateOutput(value) {
    const bytes = Buffer.byteLength(value, "utf-8");
    if (bytes <= MAX_COMMAND_OUTPUT_BYTES) {
        return { text: value };
    }
    const buffer = Buffer.from(value, "utf-8");
    return {
        text: buffer.subarray(0, MAX_COMMAND_OUTPUT_BYTES).toString("utf-8") +
            `\n...[truncated after ${MAX_COMMAND_OUTPUT_BYTES} bytes]`,
    };
}
