import { constants as fsConstants } from "node:fs";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { redactClientLogs, redactDaemonLogTail } from "./bug-report-redact.js";
const DAEMON_LOG_TAIL_BYTES = 32 * 1024;
// Defaults to the intranet deployment. Override via BUG_INTAKE_URL env for
// local development against a sibling bug-intake on 127.0.0.1:6790.
const BUG_INTAKE_URL = process.env.BUG_INTAKE_URL?.replace(/\/+$/, "") || "http://172.16.12.143:6790";
async function readLogTail(logPath, maxBytes) {
    try {
        await fs.access(logPath, fsConstants.R_OK);
    }
    catch {
        return undefined;
    }
    const handle = await fs.open(logPath, "r");
    try {
        const stat = await handle.stat();
        const start = Math.max(0, stat.size - maxBytes);
        const length = stat.size - start;
        const buffer = Buffer.alloc(length);
        await handle.read(buffer, 0, length, start);
        return buffer.toString("utf8");
    }
    finally {
        await handle.close();
    }
}
export async function handleSubmitBugReport(msg, deps) {
    const { logger, getSeaworkHome, fetchLastAgentTimeline } = deps;
    const email = msg.email?.trim();
    if (!email) {
        return {
            type: "submit_bug_report_response",
            requestId: msg.requestId,
            ok: false,
            error: "missing_email",
        };
    }
    const title = msg.title?.trim() || "(no title)";
    const seaworkHome = getSeaworkHome() || path.join(os.homedir(), ".seawork");
    const daemonLogTail = await readLogTail(path.join(seaworkHome, "daemon.log"), DAEMON_LOG_TAIL_BYTES).catch((err) => {
        logger.warn({ err }, "failed to read daemon.log tail");
        return undefined;
    });
    let agentTimeline;
    if (fetchLastAgentTimeline) {
        try {
            agentTimeline = await fetchLastAgentTimeline();
        }
        catch (err) {
            logger.warn({ err }, "failed to fetch last agent timeline");
        }
    }
    const payload = {
        title,
        description: msg.description ?? "",
        email,
        clientId: msg.clientId,
        appVersion: msg.appVersion,
        device: msg.device,
        clientLogs: redactClientLogs(msg.clientLogs),
        daemonLogTail: redactDaemonLogTail(daemonLogTail),
        agentTimeline,
        attachmentIds: msg.attachmentIds,
    };
    try {
        const res = await fetch(BUG_INTAKE_URL + "/bugs", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify(payload),
        });
        if (!res.ok) {
            const text = await res.text().catch(() => "");
            logger.error({ status: res.status, text }, "bug-intake rejected payload");
            return {
                type: "submit_bug_report_response",
                requestId: msg.requestId,
                ok: false,
                error: "intake_error_" + res.status,
            };
        }
        const body = (await res.json());
        if (!body.ok) {
            return {
                type: "submit_bug_report_response",
                requestId: msg.requestId,
                ok: false,
                error: body.error ?? "intake_error",
            };
        }
        return {
            type: "submit_bug_report_response",
            requestId: msg.requestId,
            ok: true,
            issueNumber: body.issueNumber,
            issueUrl: body.issueUrl,
        };
    }
    catch (err) {
        logger.error({ err, url: BUG_INTAKE_URL }, "bug-intake fetch failed");
        return {
            type: "submit_bug_report_response",
            requestId: msg.requestId,
            ok: false,
            error: err.message || "intake_unreachable",
        };
    }
}
//# sourceMappingURL=bug-report-handler.js.map