// engine/plugin-manifest-sync.ts — Syncs planu-plugin.json version to match package.json (SPEC-590)
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
const MANIFEST_FILENAME = 'planu-plugin.json';
/**
 * Updates `planu-plugin.json` version field to `newVersion`.
 *
 * @param repoPath - Absolute path to the repository root.
 * @param newVersion - Semver string to write (e.g. "1.82.0").
 * @returns The updated manifest object.
 * @throws If the manifest file is missing or contains invalid JSON.
 */
export function syncPluginManifestVersion(repoPath, newVersion) {
    const manifestPath = join(repoPath, MANIFEST_FILENAME);
    if (!existsSync(manifestPath)) {
        throw new Error(`${MANIFEST_FILENAME} not found at ${manifestPath}. ` +
            `Create it first (see docs/plugin-marketplace.md).`);
    }
    let raw;
    try {
        raw = readFileSync(manifestPath, 'utf-8');
    }
    catch (err) {
        throw new Error(`Failed to read ${MANIFEST_FILENAME}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
    }
    let manifest;
    try {
        manifest = JSON.parse(raw);
    }
    catch (err) {
        throw new Error(`${MANIFEST_FILENAME} contains invalid JSON: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
    }
    if (!newVersion || !/^\d+\.\d+\.\d+/.test(newVersion)) {
        throw new Error(`Invalid version "${newVersion}". Must be a valid semver string (e.g. "1.82.0").`);
    }
    const updated = { ...manifest, version: newVersion };
    writeFileSync(manifestPath, JSON.stringify(updated, null, 2) + '\n', 'utf-8');
    return updated;
}
//# sourceMappingURL=plugin-manifest-sync.js.map