"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.sanitizeFlowFilename = sanitizeFlowFilename;
exports.listFlows = listFlows;
exports.loadFlow = loadFlow;
exports.loadTrainJson = loadTrainJson;
exports.saveFlow = saveFlow;
exports.saveTrainJson = saveTrainJson;
exports.deleteFlow = deleteFlow;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
/**
 * Sanitize filename — same rules as backend/src/tracks/store.ts sanitizeTrackFilename,
 * but expects `.flow` suffix.
 *
 * Returns sanitized basename WITHOUT extension on success, null on invalid input.
 */
function sanitizeFlowFilename(raw) {
    if (typeof raw !== 'string')
        return null;
    const stripped = raw.replace(/\.flow$/i, '');
    if (stripped.length === 0 || stripped.length > 100)
        return null;
    if (!/^[a-zA-Z0-9_一-龥぀-ヿ-]+$/.test(stripped))
        return null;
    if (stripped.startsWith('.'))
        return null;
    return stripped;
}
function flowDir(projectFolder) {
    return path.join(projectFolder, '.ccweb', 'tracks');
}
function flowPath(projectFolder, basename) {
    return path.join(flowDir(projectFolder), `${basename}.flow`);
}
function trainJsonPath(projectFolder, basename) {
    return path.join(flowDir(projectFolder), `${basename}.train.json`);
}
function listFlows(projectFolder) {
    const dir = flowDir(projectFolder);
    try {
        if (!fs.existsSync(dir))
            return [];
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        return entries
            .filter((e) => e.isFile() && e.name.endsWith('.flow'))
            .map((e) => {
            const full = path.join(dir, e.name);
            const stat = fs.statSync(full);
            return {
                filename: e.name,
                basename: e.name.replace(/\.flow$/, ''),
                size: stat.size,
                mtimeMs: stat.mtimeMs,
            };
        })
            .sort((a, b) => b.mtimeMs - a.mtimeMs);
    }
    catch {
        return [];
    }
}
function loadFlow(projectFolder, basename) {
    const p = flowPath(projectFolder, basename);
    try {
        if (!fs.existsSync(p))
            return null;
        const raw = fs.readFileSync(p, 'utf8');
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
function loadTrainJson(projectFolder, basename) {
    const p = trainJsonPath(projectFolder, basename);
    try {
        if (!fs.existsSync(p))
            return null;
        const raw = fs.readFileSync(p, 'utf8');
        const parsed = JSON.parse(raw);
        if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
            return parsed;
        }
        return null;
    }
    catch {
        return null;
    }
}
/** Atomic write: temp file + rename. */
function atomicWriteJson(target, value) {
    const dir = path.dirname(target);
    try {
        fs.mkdirSync(dir, { 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;
    }
}
/** Save flow. `mode='create'` 要求文件不存在；upsert 直接覆盖。 */
function saveFlow(projectFolder, basename, flow, mode = 'upsert') {
    const target = flowPath(projectFolder, basename);
    if (mode === 'create' && fs.existsSync(target)) {
        return { ok: false, reason: 'exists' };
    }
    const ok = atomicWriteJson(target, flow);
    return ok ? { ok: true } : { ok: false, reason: 'io' };
}
function saveTrainJson(projectFolder, basename, trainJson) {
    return atomicWriteJson(trainJsonPath(projectFolder, basename), trainJson);
}
function deleteFlow(projectFolder, basename) {
    try {
        const p = flowPath(projectFolder, basename);
        const tp = trainJsonPath(projectFolder, basename);
        if (fs.existsSync(p))
            fs.unlinkSync(p);
        if (fs.existsSync(tp))
            fs.unlinkSync(tp);
        return true;
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=store.js.map