/**
 * Claude Code CLI **localSettings** management.
 *
 * The CLI reads configuration from (highest to lowest precedence)
 * `policySettings → flagSettings → localSettings → userSettings`. Writing
 * `<profile>/.claude/settings.local.json` (localSettings) is the only
 * supported way to point the CLI at a non-default `autoMemoryDirectory`
 * without either
 *   (a) polluting the user's global `~/.claude/settings.json`, or
 *   (b) committing settings to `.claude/settings.json` (which the CLI
 *       explicitly ignores for `autoMemoryDirectory` — a supply-chain
 *       hardening measure per its Zod schema).
 *
 * We keep the write surface minimal: managed fields are merged in, all
 * other fields the operator may have added manually are preserved.
 */
import fs from "node:fs";
import path from "node:path";
import { logger } from "../logger.js";
import { getClaudeAutoMemoryDir, getClaudeLocalSettingsFile, } from "./index.js";
/**
 * Keys inside `settings.local.json` that `seedClaudeAutoMemorySetting()`
 * owns. Anything else in the file is left untouched. Keep this list tight
 * — every key added here becomes something we quietly overwrite on every
 * boot, which can be surprising if an operator hand-edits the file.
 */
const MANAGED_KEYS = ["autoMemoryDirectory"];
/**
 * Load the existing file so we can merge. Returns `{}` for
 * ENOENT (first-run) and also for unreadable / unparseable / wrong-shape
 * contents. In the latter case the caller WILL overwrite the file with
 * a fresh object containing only managed keys — this is intentional
 * recovery behavior for a file we fully own, but it does mean operators
 * should not hand-edit it with comments or non-JSON content.
 */
function readExisting(file) {
    try {
        const raw = fs.readFileSync(file, "utf8");
        const parsed = JSON.parse(raw);
        if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
            return parsed;
        }
        logger.warn(`[auto-memory] ${file} is not a JSON object; replacing with a managed-only file.`);
        return {};
    }
    catch (err) {
        if (err.code === "ENOENT") {
            return {};
        }
        logger.warn(`[auto-memory] Failed to parse ${file} (${err instanceof Error ? err.message : String(err)}); replacing with a managed-only file.`);
        return {};
    }
}
/**
 * Ensure `<profile>/.claude/settings.local.json` tells the CLI to store
 * auto-memory under `<profile>/claude-auto-memory/`. No-op when the file
 * already contains the correct value.
 *
 * Safe to call on every agent boot; write is skipped unless the resolved
 * value actually changes.
 *
 * @returns `true` when the managed field is in place (either already
 *   matched, or was written successfully). `false` only when a write was
 *   attempted and the `fs.writeFile`/`mkdir` call threw — callers use
 *   this to decide whether to retry on the next CLI spawn.
 */
export function seedClaudeAutoMemorySetting() {
    const file = getClaudeLocalSettingsFile();
    const target = getClaudeAutoMemoryDir();
    const current = readExisting(file);
    // If all managed keys already have the desired value, do nothing. This
    // keeps the file bit-for-bit stable across reboots, preserving mtimes
    // for operators who watch for drift.
    if (current.autoMemoryDirectory === target) {
        return true;
    }
    // Merge: preserve any operator-added keys, overwrite only what we manage.
    const next = { ...current, autoMemoryDirectory: target };
    try {
        fs.mkdirSync(path.dirname(file), { recursive: true });
        fs.mkdirSync(target, { recursive: true });
        fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`, "utf8");
        logger.info(`[auto-memory] Set autoMemoryDirectory=${target} in ${file} (managed keys: ${MANAGED_KEYS.join(", ")}).`);
        return true;
    }
    catch (err) {
        logger.warn(`[auto-memory] Failed to seed ${file}: ${err instanceof Error ? err.message : String(err)}. CLI will fall back to its default memory path.`);
        return false;
    }
}
//# sourceMappingURL=claude-settings.js.map