import { existsSync } from 'node:fs';
import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import { expandHome } from './paths.js';
export async function readSettings(path) {
    const real = expandHome(path);
    if (!existsSync(real))
        return {};
    const raw = await readFile(real, 'utf-8');
    if (!raw.trim())
        return {};
    try {
        return JSON.parse(raw);
    }
    catch (e) {
        throw new Error(`${real} JSON 损坏: ${e.message}`);
    }
}
export async function writeSettings(path, data) {
    const real = expandHome(path);
    await mkdir(dirname(real), { recursive: true });
    let backup = '';
    if (existsSync(real)) {
        const ts = new Date().toISOString().replace(/[:.]/g, '-');
        backup = `${real}.bak-${ts}`;
        await copyFile(real, backup);
    }
    await writeFile(real, `${JSON.stringify(data, null, 2)}\n`, 'utf-8');
    return backup;
}
//# sourceMappingURL=settings.js.map