"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.copyToProjectCwd = copyToProjectCwd;
exports.reloadFromProjectCwd = reloadFromProjectCwd;
exports.cleanupProjectCwd = cleanupProjectCwd;
exports.filterByWhitelist = filterByWhitelist;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
// v-h: cwd 文件必须用 ccweb 私有名，不能用 `train.json` / `workflow_data.json`：
// 这两个名字在 ML 项目与 v1 任务流系统中都是常见名字，daemon 启动的
// cleanupStaleCwdFiles 会无条件 unlink → 抹掉用户业务数据 (P0)。
// v1 任务流系统已在 v-h 删除，不再需要 workflow_data.json 兼容别名。
// LLM 节点的系统指令字符串（prompt-translator）必须与此处文件名同步。
const TRAIN_JSON_NAME = '.ccweb-flow-train.json';
/**
 * Atomic write: write to .tmp.<pid>.<ts> then rename to target.
 * Returns true on success, false on any IO error.
 */
function atomicWriteJson(target, value) {
    try {
        fs.mkdirSync(path.dirname(target), { recursive: true });
        const tmp = `${target}.tmp.${process.pid}.${Date.now()}`;
        fs.writeFileSync(tmp, JSON.stringify(value, null, 2), 'utf8');
        fs.renameSync(tmp, target);
        return true;
    }
    catch {
        return false;
    }
}
/** Copy a snapshot to the project cwd as ccweb private name. */
function copyToProjectCwd(projectFolder, snapshot) {
    return atomicWriteJson(path.join(projectFolder, TRAIN_JSON_NAME), snapshot);
}
/**
 * Reload train.json after LLM call. Wait 200ms for OS buffer flush, then
 * try parsing. On failure (e.g. half-written file), wait another 500ms
 * and retry once.
 *
 * spec §8.2.
 */
async function reloadFromProjectCwd(projectFolder) {
    const target = path.join(projectFolder, TRAIN_JSON_NAME);
    await sleep(200);
    const attempt = tryReadJson(target);
    if (attempt.ok)
        return attempt;
    await sleep(500);
    return tryReadJson(target);
}
function tryReadJson(target) {
    try {
        if (!fs.existsSync(target))
            return { ok: false, error: 'train.json not found' };
        const raw = fs.readFileSync(target, 'utf8');
        const parsed = JSON.parse(raw);
        if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
            return { ok: false, error: 'train.json must be an object' };
        }
        return { ok: true, data: parsed };
    }
    catch (e) {
        return { ok: false, error: `JSON parse failed: ${e.message}` };
    }
}
/** Delete cwd `.ccweb-flow-train.json`. Idempotent. */
function cleanupProjectCwd(projectFolder) {
    try {
        fs.unlinkSync(path.join(projectFolder, TRAIN_JSON_NAME));
    }
    catch {
        /* ignore */
    }
}
/**
 * Filter a possibly LLM-mutated train.json content by the declared
 * whitelist of variable keys. Missing keys are filled with null.
 * Extra (non-whitelist) keys are discarded.
 *
 * spec §6.2 step 7 / §8.2.
 */
function filterByWhitelist(data, whitelist) {
    const out = {};
    for (const key of whitelist) {
        out[key] = key in data ? data[key] : null;
    }
    return out;
}
function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
//# sourceMappingURL=train-json-sync.js.map