/**
 * audit.mjs — append-only JSONL audit log for driver invocations.
 *
 * ID-05: one file per day at .aperant/events/{YYYY-MM-DD}.jsonl.
 * One line per driver invocation:
 *   {ts, driver_id, version, manifest_sha256, trust_tier, sandbox_profile,
 *    decision: "allow|deny|requires_approval",
 *    result: "success|fail|skip"}
 *
 * Append-only — no rewrites. Each appendDriverEvent() opens the file in
 * 'a' mode and writes a single line; concurrent agents may interleave
 * lines but no line is ever overwritten.
 */

import { appendFileSync, mkdirSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'

/**
 * Compute today's events filename relative to projectDir.
 * @param {string} projectDir
 * @param {Date} [now]
 * @returns {string}
 */
export function dailyEventsPath(projectDir, now = new Date()) {
	const yyyy = now.getUTCFullYear()
	const mm = String(now.getUTCMonth() + 1).padStart(2, '0')
	const dd = String(now.getUTCDate()).padStart(2, '0')
	return join(resolve(projectDir), '.aperant/events', `${yyyy}-${mm}-${dd}.jsonl`)
}

/**
 * Append a driver-invocation audit line.
 *
 * @param {string} projectDir
 * @param {Object} entry
 * @param {string} entry.driver_id
 * @param {string} entry.version
 * @param {string} entry.manifest_sha256
 * @param {string} entry.trust_tier
 * @param {string} entry.sandbox_profile
 * @param {'allow' | 'deny' | 'requires_approval'} entry.decision
 * @param {'success' | 'fail' | 'skip'} entry.result
 * @param {string} [entry.verb] — IDL verb invoked (optional metadata)
 * @param {string} [entry.reason] — decision-rationale string (optional)
 */
export function appendDriverEvent(projectDir, entry) {
	const path = dailyEventsPath(projectDir)
	mkdirSync(dirname(path), { recursive: true })
	const line = JSON.stringify({
		ts: new Date().toISOString(),
		kind: 'driver_invocation',
		...entry,
	})
	appendFileSync(path, line + '\n', 'utf-8')
}
