/**
 * io.mjs — layer-0 I/O + process-exit helpers extracted from apt-tools.mjs (C29).
 *
 * These are pure leaf helpers with zero internal dependencies. Behavior must
 * match the originals byte-for-byte; the CLI snapshot harness enforces this.
 */

import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

// Re-export the hardened atomic-write primitives so every existing call site
// (import { atomicWriteJson } from '../util/io.mjs') keeps working. See
// atomic-write.mjs for the fsync + tmp-file semantics.
export { appendJsonl, atomicWriteJson, atomicWriteText } from './atomic-write.mjs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

/**
 * Read framework package.json and return a "<name> <version>" identity string.
 * Resolves relative to this module's location so the CLI keeps its own
 * package.json as source of truth regardless of cwd.
 */
export function getVersion() {
	// src/cli/util/io.mjs → up three levels → packages/framework/package.json
	const pkgPath = resolve(__dirname, '..', '..', '..', 'package.json')
	const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
	return `${pkg.name} ${pkg.version}`
}

/**
 * Write a JSON-stringified value to stdout, followed by a trailing newline.
 * Everything apt-tools prints to stdout goes through this.
 */
export function output(data) {
	process.stdout.write(JSON.stringify(data, null, 2) + '\n')
}

/**
 * Print a structured error envelope to stdout and exit the process with
 * status 1. Used for all fatal-from-CLI conditions.
 */
export function fail(message) {
	output({ error: message })
	process.exit(1)
}
