/*
 * 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 { Messages } from '@salesforce/core';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { ALL_PROFILES } from '../../profiles/index.js';
import { readWorkspaceConfig } from '../../services/workspace-config.js';
import { SUPPORTED_TOOLS } from '../../types/index.js';
import { detectTools } from '../../util/command-helpers.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@jterrats/setup-agents', 'setup-agents.verify');
const TOOL_RULE_FILES = {
    cursor: '.cursor/rules/agent-guidelines.mdc',
    vscode: '.vscode/settings.json',
    codex: 'AGENTS.md',
    claude: 'CLAUDE.md',
    agentforce: '.a4drules/00-base-guidelines.md',
    windsurf: '.windsurfrules',
    jetbrains: '.idea/ai-prompts/setup-agents-guidelines.md',
};
export default class Verify extends SfCommand {
    static summary = messages.getMessage('summary');
    static description = messages.getMessage('description');
    static examples = messages.getMessages('examples');
    static flags = {
        rules: Flags.string({
            summary: messages.getMessage('flags.rules.summary'),
            options: SUPPORTED_TOOLS,
            helpValue: SUPPORTED_TOOLS.join('|'),
        }),
        profile: Flags.string({
            summary: messages.getMessage('flags.profile.summary'),
        }),
    };
    async run() {
        const { flags } = await this.parse(Verify);
        const cwd = process.cwd();
        const config = readWorkspaceConfig(cwd);
        if (!config && !flags.rules && !flags.profile) {
            this.warn(messages.getMessage('warn.noConfig'));
        }
        const tool = flags.rules ?? resolveActiveTool(cwd, config);
        const profileIds = flags.profile ? flags.profile.split(',').map((p) => p.trim()) : config?.profiles ?? [];
        const profiles = ALL_PROFILES.filter((p) => profileIds.includes(p.id));
        if (!tool) {
            this.warn(messages.getMessage('warn.noTool'));
            return { tool: null, profiles: profileIds, probePrompt: null, hasRules: false, cwd };
        }
        const hasRules = hasRuleFile(cwd, tool);
        if (!hasRules) {
            this.warn(messages.getMessage('warn.noRules', [tool, tool]));
        }
        const probePrompt = buildProbePrompt(tool, profiles.length > 0 ? profiles.map((p) => p.id) : profileIds);
        const toolLabel = tool;
        const profileLabel = profiles.length > 0 ? profiles.map((p) => p.label).join(', ') : profileIds.join(', ') || 'default';
        this.log(messages.getMessage('info.header', [toolLabel, profileLabel]));
        this.log('');
        this.log(messages.getMessage('info.instructions'));
        this.log('');
        this.log(messages.getMessage('info.separator'));
        this.log('');
        this.log(probePrompt);
        this.log('');
        this.log(messages.getMessage('info.separator'));
        this.log('');
        if (!hasRules) {
            this.log(messages.getMessage('info.footer'));
        }
        return { tool, profiles: profileIds, probePrompt, hasRules, cwd };
    }
}
function resolveActiveTool(cwd, config) {
    const candidates = config?.tools ?? detectTools(cwd);
    for (const tool of candidates) {
        if (hasRuleFile(cwd, tool))
            return tool;
    }
    return candidates[0] ?? null;
}
function hasRuleFile(cwd, tool) {
    const file = TOOL_RULE_FILES[tool];
    if (!file)
        return false;
    return existsSync(join(cwd, file));
}
function buildProbePrompt(tool, profileIds) {
    const constraints = PROFILE_CONSTRAINTS[profileIds[0]] ?? PROFILE_CONSTRAINTS['developer'];
    const toolHint = TOOL_HINTS[tool];
    const profileName = profileIds[0] ?? 'developer';
    return [
        'You are an AI coding assistant with active rule files for this workspace.',
        '',
        'Without writing any code, answer the following:',
        '',
        `1. What is the primary rule you must follow for the '${profileName}' profile?`,
        `2. ${constraints.question}`,
        `3. ${toolHint}`,
        '',
        'If you have active rules loaded, quote the relevant constraint verbatim from your instructions.',
        "If you cannot find the rule, say 'Rules not found' and describe what instructions you do have.",
    ].join('\n');
}
const PROFILE_CONSTRAINTS = {
    developer: { question: 'Are you allowed to put SOQL or DML inside a loop?' },
    architect: { question: 'What framework do you use for architecture diagrams in this project?' },
    qa: { question: 'What test runner and authentication helper should you use for E2E tests?' },
    devops: { question: 'What is the deployment validation command you must run before deploying?' },
    ba: { question: 'What artifact must you produce before writing acceptance criteria?' },
    pm: { question: 'What delivery metrics are you expected to track per story?' },
    mulesoft: { question: 'What MuleSoft runtime version should new projects target?' },
    ux: { question: 'What is the minimum color contrast ratio you must verify in UI work?' },
    admin: { question: 'What is the first step before making any configuration change in production?' },
    security: { question: 'What scanning tool must you run before a security review?' },
    crma: { question: 'What is the preferred dataset join strategy in CRM Analytics?' },
    data360: { question: 'What ingestion pattern should you use for batch data loads?' },
    cgcloud: { question: 'What namespace prefix must you preserve in this project?' },
    service: { question: 'What is the escalation path when a case SLA is at risk?' },
    fsl: { question: 'What scheduling policy must be respected when dispatching work orders?' },
    slack: { question: 'What API surface should you use for Slack App actions?' },
    tableau: { question: 'What data source connection type is preferred for live dashboards?' },
    ai: { question: 'What safety guardrails apply before deploying an Einstein model to production?' },
    commerce: { question: 'What storefront framework should new B2C Commerce implementations use?' },
    cpq: { question: 'What approval process must run before a quote is activated?' },
    omnistudio: { question: 'What is the preferred component for multi-step guided flows in OmniStudio?' },
    sfmc: { question: 'What data extension best practice applies to audience segmentation?' },
};
const TOOL_HINTS = {
    cursor: 'Which .mdc rule files do you have loaded for this workspace?',
    vscode: 'Do you have a GitHub Copilot instructions file active for this workspace?',
    codex: 'What instructions are in your AGENTS.md file?',
    claude: 'What instructions are in your CLAUDE.md file?',
    agentforce: 'Which .a4drules files are active in this workspace?',
    windsurf: 'What instructions are in your .windsurfrules file?',
    jetbrains: 'Which prompt files do you have loaded from .idea/ai-prompts/?',
};
//# sourceMappingURL=verify.js.map