/**
 * install/transforms/gemini.mjs — Gemini transform.
 *
 * Gemini quirks:
 *   - frontmatter strips `color` (validation error in Gemini's schema) and
 *     `tools`.
 *   - body escapes `${var}` → `\${var}` so Gemini's templateString
 *     interpolation does not fire on prose mentions of shell-style vars.
 *   - output: .gemini/agents/<name>.md and .gemini/commands/<name>.md.
 */

import { basename, dirname } from 'node:path'
import {
	parseFrontmatter,
	serializeFrontmatter,
	stripFields,
	substituteVersion,
} from './_shared.mjs'

const STRIP = ['color', 'tools']

/**
 * Escape ${...} interpolation in body text. Already-escaped (\${) sequences
 * are left alone so we don't double-escape on re-runs.
 *
 * @param {string} body
 * @returns {string}
 */
export function escapeTemplateVars(body) {
	// Negative lookbehind: only replace ${ that is NOT preceded by a backslash.
	return body.replace(/(?<!\\)\$\{/g, '\\${')
}

/**
 * @param {import('../pipeline.mjs').TransformInput} input
 * @returns {import('../pipeline.mjs').TransformOutput[]}
 */
export function transform({ canonicalContent, canonicalRelPath, version, fileType }) {
	const subbed = substituteVersion(canonicalContent, version)
	const parsed = parseFrontmatter(subbed)
	let payload
	if (parsed.hasFrontmatter && parsed.fm) {
		stripFields(parsed.fm, STRIP)
		const escapedBody = escapeTemplateVars(parsed.body)
		payload = serializeFrontmatter({ ...parsed, body: escapedBody })
	} else {
		payload = escapeTemplateVars(subbed)
	}

	if (fileType === 'skill') {
		const folder = basename(dirname(canonicalRelPath))
		return [
			{ outputPath: `agents/${folder}.md`, content: payload },
			{ outputPath: `commands/${folder}.md`, content: payload },
		]
	}
	if (fileType === 'agent') {
		const file = basename(canonicalRelPath, '.md')
		return [{ outputPath: `agents/${file}.md`, content: payload }]
	}
	return []
}
