"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyRtwsSeed = applyRtwsSeed;
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
const app_id_1 = require("./app-id");
function ensureRelNoTraversal(rel) {
    const normalized = rel.replace(/\\/g, '/').replace(/^\/+/g, '');
    if (normalized.includes('..')) {
        throw new Error(`Invalid path contains '..': ${rel}`);
    }
    return normalized;
}
async function writeIfMissing(fileAbs, content, overwrite) {
    try {
        if (!overwrite) {
            await promises_1.default.access(fileAbs);
            return;
        }
    }
    catch {
        // missing => proceed
    }
    await promises_1.default.mkdir(path_1.default.dirname(fileAbs), { recursive: true });
    await promises_1.default.writeFile(fileAbs, content, 'utf-8');
}
async function applyRtwsSeed(params) {
    const rtwsAppDirAbs = (0, app_id_1.resolveDomindsAppRtwsDirAbs)(params.rtwsRootAbs, params.appId);
    await promises_1.default.mkdir(rtwsAppDirAbs, { recursive: true });
    const taskdocs = params.manifest.contributes?.rtwsSeed?.taskdocs ?? [];
    for (const td of taskdocs) {
        const rel = ensureRelNoTraversal(td.path);
        if (!rel.endsWith('.tsk')) {
            throw new Error(`Invalid rtwsSeed taskdoc path (must end with .tsk): ${td.path}`);
        }
        const dirAbs = path_1.default.resolve(rtwsAppDirAbs, rel);
        await promises_1.default.mkdir(dirAbs, { recursive: true });
        if (typeof td.goals === 'string' && td.goals.trim() !== '') {
            await writeIfMissing(path_1.default.join(dirAbs, 'goals.md'), td.goals, params.overwrite);
        }
        if (typeof td.constraints === 'string' && td.constraints.trim() !== '') {
            await writeIfMissing(path_1.default.join(dirAbs, 'constraints.md'), td.constraints, params.overwrite);
        }
        if (typeof td.progress === 'string' && td.progress.trim() !== '') {
            await writeIfMissing(path_1.default.join(dirAbs, 'progress.md'), td.progress, params.overwrite);
        }
    }
}
