import * as os from 'os';
import { resolveActor } from './actor.js';
import { machineId } from './machine-id.js';
import { parseSshConnection } from './session/provenance.js';
let cachedOrigin;
let cachedDeviceId;
/**
 * Stamp the shared identity floor used by both operational and activity events.
 * Explicit event payload fields may override these defaults at the call site.
 */
export function stampProvenance(env = process.env) {
    if (!cachedOrigin) {
        let osUser = 'unknown';
        try {
            osUser = os.userInfo().username;
        }
        catch {
            // A uid without a passwd entry has no attributable OS user.
        }
        const ssh = env.SSH_CONNECTION ? parseSshConnection(env.SSH_CONNECTION) : undefined;
        const actor = resolveActor();
        cachedOrigin = {
            osUser,
            transport: ssh ? 'ssh' : 'local',
            ...(ssh ? { sshClientIp: ssh.clientIp } : {}),
            actor: actor.id,
            kind: actor.kind,
        };
    }
    const provenance = {
        ...cachedOrigin,
        machineId: (cachedDeviceId ??= machineId()),
    };
    const sessionId = env.AGENT_SESSION_ID || env.AGENTS_SESSION_ID;
    if (sessionId)
        provenance.sessionId = sessionId;
    if (env.AGENTS_AGENT_NAME)
        provenance.agent = env.AGENTS_AGENT_NAME;
    if (env.AGENT_LAUNCH_ID)
        provenance.launchId = env.AGENT_LAUNCH_ID;
    if (env.AGENTS_PARENT_SESSION_ID)
        provenance.parentSessionId = env.AGENTS_PARENT_SESSION_ID;
    return provenance;
}
export function resetEventProvenanceForTest() {
    cachedOrigin = undefined;
    cachedDeviceId = undefined;
}
