import { resolveFridayNextConfig } from "../config.js";
import { getHostOpenClawConfigSnapshot } from "../host-config.js";
import { getFridayNextRuntime } from "../runtime.js";
import { pairAccount, resolveAccountIdForDevice } from "./account-identity.js";
import { appendEvent } from "./transcript-store.js";
export function resolveAccountIdForArchive(deviceId, headerAccountId) {
    const cfg = resolveFridayNextConfig(getHostOpenClawConfigSnapshot(getFridayNextRuntime().config));
    const header = headerAccountId?.trim();
    if (header)
        return header;
    const mapped = resolveAccountIdForDevice(cfg.historyDir, deviceId);
    if (mapped)
        return mapped;
    const paired = pairAccount({ historyDir: cfg.historyDir, deviceId });
    return paired.accountId;
}
export function archiveTranscriptEvent(params) {
    try {
        const accountId = params.accountId?.trim() ||
            resolveAccountIdForArchive(params.deviceId.trim().toUpperCase(), null);
        if (!accountId)
            return;
        appendEvent({
            accountId,
            sessionKey: params.sessionKey,
            kind: params.kind,
            clientId: params.clientId ?? "server",
            payload: params.payload,
            messageId: params.messageId,
            lamport: params.lamport,
            titleHint: params.titleHint,
        });
    }
    catch {
        // best-effort archive
    }
}
