import { buildAuditEnvelope, emitUokAuditEvent } from "./audit.js";
import {
	getParityCommitBlockReason,
	isParityCommitBlocked,
} from "./parity-diff-capture.js";
/**
 * Downgrade mutating gitops when UOK parity has flagged an unsafe turn.
 *
 * Purpose: prevent commit/snapshot publication after a critical parity divergence
 * or a prior kernel enter without a matching exit.
 *
 * Consumer: turn git transaction recording and post-unit git execution paths.
 */
export function resolveParitySafeGitAction(args) {
	if (!isParityCommitBlocked() || args.action === "status-only") return args;
	const reason = getParityCommitBlockReason();
	return {
		action: "status-only",
		push: false,
		status: "failed",
		error: args.error ?? `gitops commit blocked: ${reason}`,
		metadata: {
			...(args.metadata ?? {}),
			commitBlocked: true,
			commitBlockReason: reason,
			requestedAction: args.action,
			requestedPush: args.push,
		},
	};
}
export function writeTurnGitTransaction(args) {
	const safe = resolveParitySafeGitAction({
		action: args.action,
		push: args.push,
		status: args.status,
		error: args.error,
		metadata: args.metadata,
	});
	emitUokAuditEvent(
		args.basePath,
		buildAuditEnvelope({
			traceId: args.traceId,
			turnId: args.turnId,
			category: "gitops",
			type: `turn-git-${args.stage}`,
			payload: {
				unitType: args.unitType,
				unitId: args.unitId,
				action: safe.action,
				push: safe.push,
				status: safe.status,
				error: safe.error,
				...(safe.metadata ?? {}),
			},
		}),
	);
}
export function writeTurnCloseoutGitRecord(basePath, record, metadata) {
	writeTurnGitTransaction({
		basePath,
		traceId: record.traceId,
		turnId: record.turnId,
		unitType: record.unitType,
		unitId: record.unitId,
		stage: "record",
		action: record.gitAction,
		push: record.gitPushed,
		status: record.failureClass === "git" ? "failed" : "ok",
		error: record.failureClass === "git" ? "git closeout failure" : undefined,
		metadata: {
			...(metadata ?? {}),
			turnStatus: record.status,
			finishedAt: record.finishedAt,
			activityFile: record.activityFile,
		},
	});
}
