/**
 * IO Helpers for auto-prompts — file loading and inlining.
 *
 * Purpose: Consolidate file I/O functions used by prompt builders. Enables
 * testable, reusable utilities for inlining files into prompts with consistent
 * formatting and fallback handling.
 *
 * Consumer: auto-prompts.js prompt builders.
 */

import { truncateAtSectionBoundary } from "./context-budget.js";
import { loadFile } from "./files.js";

/**
 * Load a file for inlining, returning formatted markdown section.
 * If file not found, returns a placeholder indicating file doesn't exist yet.
 */
export async function inlineFile(absPath, relPath, label) {
	const content = absPath ? await loadFile(absPath) : null;
	if (!content) {
		return `### ${label}\nSource: \`${relPath}\`\n\n_(not found — file does not exist yet)_`;
	}
	return `### ${label}\nSource: \`${relPath}\`\n\n${content.trim()}`;
}

/**
 * Load a file for inlining, returning null if it doesn't exist.
 * Use when the file is optional and should be omitted entirely if absent.
 */
export async function inlineFileOptional(absPath, relPath, label) {
	const content = absPath ? await loadFile(absPath) : null;
	if (!content) return null;
	return `### ${label}\nSource: \`${relPath}\`\n\n${content.trim()}`;
}

/**
 * Smart file inlining — for large files, use semantic chunking to include
 * only the most relevant portions based on the task context.
 * Falls back to full content for small files or when no query is provided.
 *
 * @param absPath Absolute file path
 * @param relPath Relative display path
 * @param label Section label
 * @param query Task description for relevance scoring (optional)
 * @param threshold Character threshold for chunking (default: 3000)
 */
export async function inlineFileSmart(
	absPath,
	relPath,
	label,
	query,
	threshold = 3000,
) {
	const content = absPath ? await loadFile(absPath) : null;
	if (!content) {
		return `### ${label}\nSource: \`${relPath}\`\n\n_(not found — file does not exist yet)_`;
	}
	// For small files or no query, include full content
	if (content.length <= threshold || !query) {
		return `### ${label}\nSource: \`${relPath}\`\n\n${content.trim()}`;
	}
	// For large files, truncate at section boundary
	const truncated = truncateAtSectionBoundary(content, threshold).content;
	return `### ${label}\nSource: \`${relPath}\`\n\n${truncated}`;
}
