/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { ensureDir, writeFileAtomic } from '../services/file-writer.js';
const SA_FAST_HOOK = {
    matcher: '',
    hooks: [
        {
            type: 'command',
            command: '(command -v sa-fast >/dev/null 2>&1 && sa-fast task list --json --limit 5 && sa-fast workflow pending --json) || true',
        },
    ],
};
/**
 * Pure function that merges hook entries into an existing settings object.
 * If a hook with `sa-fast` in its command already exists, it is updated in place.
 * Otherwise the new hook is appended.
 */
export function mergeHooks(existing, hooks) {
    const result = { ...existing };
    if (!result.hooks)
        result.hooks = {};
    if (!result.hooks.UserPromptSubmit)
        result.hooks.UserPromptSubmit = [];
    const entries = [...result.hooks.UserPromptSubmit];
    for (const hook of hooks) {
        const idx = entries.findIndex((e) => e.hooks?.some((h) => h.command.includes('sa-fast')));
        if (idx >= 0) {
            entries[idx] = hook;
        }
        else {
            entries.push(hook);
        }
    }
    result.hooks = { ...result.hooks, UserPromptSubmit: entries };
    return result;
}
/**
 * Generates or merges `.claude/settings.json` with the UserPromptSubmit hook
 * that injects task/workflow state into Claude sessions.
 */
export function writeClaudeSettings(opts) {
    const { cwd, version } = opts;
    const claudeDir = join(cwd, '.claude');
    const settingsPath = join(claudeDir, 'settings.json');
    ensureDir(claudeDir);
    let settings = {};
    if (existsSync(settingsPath)) {
        try {
            settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
        }
        catch {
            settings = {};
        }
    }
    settings = mergeHooks(settings, [SA_FAST_HOOK]);
    // eslint-disable-next-line no-underscore-dangle
    settings._setupAgentsVersion = version;
    writeFileAtomic(settingsPath, JSON.stringify(settings, null, 2) + '\n');
}
//# sourceMappingURL=claude-settings.js.map