/*
 * 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 } from 'node:fs';
import { join } from 'node:path';
import { generateClaudeProfileRule } from '../generators/claude-generator.js';
import { generateCodexProfileRule } from '../generators/codex-generator.js';
import { ALL_PROFILES } from '../profiles/index.js';
import { PLUGIN_VERSION } from '../version.js';
import { ensureDir, FileWriter } from './file-writer.js';
function expandForCursor(cwd, profile, writer) {
    const rulesDir = join(cwd, '.cursor', 'rules');
    const filePath = join(rulesDir, profile.ruleFile);
    if (existsSync(filePath))
        return [];
    if (!existsSync(rulesDir))
        return [];
    ensureDir(rulesDir);
    const content = applyCursorScope(injectPluginVersion(profile.ruleContent(), PLUGIN_VERSION), profile);
    writer.write(filePath, content);
    return [filePath];
}
function expandForClaude(cwd, profile, writer) {
    const rulesDir = join(cwd, '.claude', 'rules');
    const filePath = join(rulesDir, `${profile.id}.md`);
    if (existsSync(filePath))
        return [];
    if (!existsSync(rulesDir))
        return [];
    ensureDir(rulesDir);
    writer.write(filePath, generateClaudeProfileRule(profile, PLUGIN_VERSION));
    return [filePath];
}
function expandForCodex(cwd, profile, writer) {
    const codexDir = join(cwd, '.codex');
    const filePath = join(codexDir, `${profile.id}.md`);
    if (existsSync(filePath))
        return [];
    if (!existsSync(codexDir))
        return [];
    ensureDir(codexDir);
    writer.write(filePath, generateCodexProfileRule(profile, PLUGIN_VERSION));
    return [filePath];
}
function expandForJetBrains(cwd, profile, writer) {
    const promptsDir = join(cwd, '.idea', 'ai-prompts');
    const filePath = join(promptsDir, `${profile.id}.md`);
    if (existsSync(filePath))
        return [];
    if (!existsSync(promptsDir))
        return [];
    ensureDir(promptsDir);
    const header = `<!-- setup-agents: ${PLUGIN_VERSION} -->`;
    const body = stripMdcFrontmatter(profile.ruleContent());
    writer.write(filePath, [header, '', `# ${profile.label}`, '', body].join('\n'));
    return [filePath];
}
const TOOL_EXPANDERS = {
    cursor: expandForCursor,
    claude: expandForClaude,
    codex: expandForCodex,
    jetbrains: expandForJetBrains,
};
export function autoExpandProfiles(cwd, profileIds, configuredTools) {
    const allProfileMap = new Map(ALL_PROFILES.map((p) => [p.id, p]));
    const invalid = [];
    const expanded = [];
    const filesWritten = [];
    const writer = new FileWriter({
        force: true,
        log: () => { },
        warn: () => { },
    });
    for (const id of profileIds) {
        const profile = allProfileMap.get(id);
        if (!profile) {
            invalid.push(id);
            continue;
        }
        let wrote = false;
        for (const tool of configuredTools) {
            const expander = TOOL_EXPANDERS[tool];
            if (!expander)
                continue;
            const files = expander(cwd, profile, writer);
            if (files.length > 0) {
                filesWritten.push(...files);
                wrote = true;
            }
        }
        if (wrote) {
            expanded.push(id);
        }
    }
    return { expanded, filesWritten, invalid };
}
function injectPluginVersion(content, version) {
    return content.replace(/^(---\n(?:.*\n)*?)(---)/m, `$1pluginVersion: "${version}"\n$2`);
}
function applyCursorScope(content, profile) {
    const scope = profile.cursorScope ?? 'always';
    const globs = profile.globs;
    const globsLine = scope === 'auto-attach' && globs?.length ? `globs: ${globs.join(', ')}` : 'globs:';
    const alwaysApply = scope === 'always' ? 'alwaysApply: true' : 'alwaysApply: false';
    return content.replace(/^globs:.*$/m, globsLine).replace(/^alwaysApply:.*$/m, alwaysApply);
}
function stripMdcFrontmatter(content) {
    return content.replace(/^---\n[\s\S]*?---\n*/, '');
}
//# sourceMappingURL=profile-expand.js.map