/**
 * install/transforms/opencode.mjs — OpenCode transform.
 *
 * OpenCode quirks:
 *   - color names are converted to hex (`color: cyan` → `color: '#06b6d4'`)
 *     because OpenCode's UI rejects symbolic names.
 *   - agents strip `skills`, `memory`, `maxTurns`, `permissionMode`,
 *     `disallowedTools` (none of these have OpenCode equivalents and they
 *     trigger validation errors).
 *   - output: .opencode/agent/<name>.md and .opencode/command/<name>.md
 *     (note SINGULAR `agent` / `command`, not `agents` / `commands`).
 */

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

const STRIP = ['skills', 'memory', 'maxTurns', 'permissionMode', 'disallowedTools']

/**
 * Apply the OpenCode body+frontmatter transform. Exported so the kilo
 * transform (which has the same body invariants but different output paths)
 * can reuse it.
 *
 * @param {string} content
 * @param {string} version
 * @returns {string}
 */
export function applyOpencodeTransform(content, version) {
	const subbed = substituteVersion(content, version)
	const parsed = parseFrontmatter(subbed)
	if (!parsed.hasFrontmatter || !parsed.fm) return subbed
	stripFields(parsed.fm, STRIP)
	if (typeof parsed.fm.color === 'string') {
		const hex = colorNameToHex(parsed.fm.color)
		if (hex) parsed.fm.color = hex
		else delete parsed.fm.color
	}
	return serializeFrontmatter(parsed)
}

/**
 * @param {import('../pipeline.mjs').TransformInput} input
 * @returns {import('../pipeline.mjs').TransformOutput[]}
 */
export function transform({ canonicalContent, canonicalRelPath, version, fileType }) {
	const payload = applyOpencodeTransform(canonicalContent, version)
	if (fileType === 'skill') {
		const folder = basename(dirname(canonicalRelPath))
		return [
			{ outputPath: `agent/${folder}.md`, content: payload },
			{ outputPath: `command/${folder}.md`, content: payload },
		]
	}
	if (fileType === 'agent') {
		const file = basename(canonicalRelPath, '.md')
		return [{ outputPath: `agent/${file}.md`, content: payload }]
	}
	return []
}
