/**
 * Unit closeout helper — consolidates the repeated pattern of
 * snapshotting metrics + saving activity log + extracting memories
 * that appears 6+ times in auto.ts.
 */
import { saveActivityLog } from "../activity-log.js";
import { getErrorMessage } from "../error-utils.js";
import { snapshotUnitMetrics } from "../metrics.js";
import { updateSubscriptionTokensUsed } from "../preferences-models.js";
import { logWarning } from "../workflow-logger.js";
import { writeTurnGitTransaction } from "./gitops.js";
/**
 * Snapshot metrics, save activity log, and fire-and-forget memory extraction
 * for a completed unit. Returns the activity log file path (if any).
 */
export async function closeoutUnit(
	ctx,
	basePath,
	unitType,
	unitId,
	startedAt,
	opts,
) {
	const provider = ctx.model?.provider;
	const id = ctx.model?.id;
	const modelId = provider && id ? `${provider}/${id}` : (id ?? "unknown");
	const unit = snapshotUnitMetrics(
		ctx,
		unitType,
		unitId,
		startedAt,
		modelId,
		opts,
	);
	// Track subscription token consumption for amortized cost reporting.
	// Fire-and-forget: updateSubscriptionTokensUsed is already best-effort.
	if (provider && unit && unit.tokens.total > 0) {
		updateSubscriptionTokensUsed(provider, unit.tokens.total);
	}
	const activityFile = saveActivityLog(ctx, basePath, unitType, unitId);
	if (activityFile) {
		try {
			const { buildMemoryLLMCall, extractMemoriesFromUnit } = await import(
				"../memory-extractor.js"
			);
			const { recordMemoryExtractionAttempt } = await import(
				"../memory-store.js"
			);
			const llmCallFn = buildMemoryLLMCall(ctx);
			if (llmCallFn) {
				extractMemoriesFromUnit(
					activityFile,
					unitType,
					unitId,
					llmCallFn,
				).catch((err) => {
					logWarning(
						"engine",
						`memory extraction failed for ${unitType}/${unitId}: ${err.message}`,
					);
				});
			} else {
				recordMemoryExtractionAttempt({
					unitType,
					unitId,
					activityFile,
					status: "skipped",
					reason: "llm-unavailable",
				});
			}
		} catch (err) {
			/* non-fatal */
			logWarning("engine", `operation failed: ${getErrorMessage(err)}`);
		}
	}
	if (opts?.traceId && opts.turnId && opts.gitAction && opts.gitStatus) {
		writeTurnGitTransaction({
			basePath,
			traceId: opts.traceId,
			turnId: opts.turnId,
			unitType,
			unitId,
			stage: "record",
			action: opts.gitAction,
			push: opts.gitPush === true,
			status: opts.gitStatus,
			error: opts.gitError,
			metadata: {
				activityFile,
			},
		});
	}
	return activityFile ?? undefined;
}
