/*
 * 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, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ALL_PROFILES } from '../profiles/index.js';
import { SUPPORTED_TOOLS } from '../types/index.js';
import { PLUGIN_VERSION } from '../version.js';
import { ensureDir } from './file-writer.js';
export const WORKSPACE_CONFIG_DIR = '.setup-agents';
export const WORKSPACE_CONFIG_FILE = 'config.json';
const VALID_PROFILE_IDS = new Set(ALL_PROFILES.map((profile) => profile.id));
const VALID_TOOLS = new Set(SUPPORTED_TOOLS);
const VALID_MODES = new Set(['project', 'advisory']);
const VALID_CURSOR_SCOPES = new Set(['always', 'auto-attach', 'description']);
export function getWorkspaceConfigPath(cwd) {
    return join(cwd, WORKSPACE_CONFIG_DIR, WORKSPACE_CONFIG_FILE);
}
export function buildWorkspaceConfig(input) {
    const profiles = input.profiles.map((profile) => profile.id);
    return {
        version: PLUGIN_VERSION,
        mode: input.mode,
        profiles,
        tools: input.tools,
        orchestration: {
            enabled: true,
            engine: 'native',
            mode: input.mode,
            profiles,
        },
    };
}
export function writeWorkspaceConfig(cwd, config, opts) {
    const configPath = getWorkspaceConfigPath(cwd);
    if (existsSync(configPath) && !opts.force) {
        return { path: configPath, config, written: false };
    }
    ensureDir(join(cwd, WORKSPACE_CONFIG_DIR));
    writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
    return { path: configPath, config, written: true };
}
export function readWorkspaceConfig(cwd) {
    const configPath = getWorkspaceConfigPath(cwd);
    if (!existsSync(configPath))
        return null;
    return JSON.parse(readFileSync(configPath, 'utf8'));
}
export function validateWorkspaceConfig(config) {
    const errors = [];
    if (!config.version)
        errors.push('Missing version.');
    if (!VALID_MODES.has(config.mode))
        errors.push('Mode must be "project" or "advisory".');
    for (const profile of config.profiles) {
        if (!VALID_PROFILE_IDS.has(profile))
            errors.push(`Unknown profile: ${profile}.`);
    }
    for (const tool of config.tools) {
        if (!VALID_TOOLS.has(tool))
            errors.push(`Unsupported tool: ${tool}.`);
    }
    if (config.orchestration.engine !== 'native')
        errors.push('Orchestration engine must be "native".');
    if (config.orchestration.mode !== config.mode)
        errors.push('Orchestration mode must match workspace mode.');
    if (config.ruleOverrides) {
        for (const [profileId, override] of Object.entries(config.ruleOverrides)) {
            if (!VALID_PROFILE_IDS.has(profileId)) {
                errors.push(`Unknown profile in ruleOverrides: ${profileId}.`);
            }
            if (override?.scope !== undefined && !VALID_CURSOR_SCOPES.has(override.scope)) {
                errors.push(`Invalid scope "${override.scope}" for ruleOverrides.${profileId}. Must be "always", "auto-attach", or "description".`);
            }
            if (override?.globs !== undefined && !Array.isArray(override.globs)) {
                errors.push(`ruleOverrides.${profileId}.globs must be an array.`);
            }
        }
    }
    return {
        valid: errors.length === 0,
        errors,
        guidance: errors.length === 0 ? [] : ['Run `sf setup-agents init --force` to recreate the workspace config.'],
    };
}
//# sourceMappingURL=workspace-config.js.map