/**
 * Validation rule: ensure system prompts preserve required template variables.
 *
 * When a prompt in the mcpctl-system project is updated, this rule checks
 * that all required {{var}} placeholders are still present in the content.
 */
import type { ResourceRule, RuleMeta, RuleContext, ValidationResult } from '../resource-rules.js';
import { getSystemPromptRequiredVars } from '../../bootstrap/system-project.js';

interface PromptData {
  name: string;
  content: string;
}

export const systemPromptVarsRule: ResourceRule<PromptData> = {
  name: 'system-prompt-template-vars',
  resource: 'prompt',

  match(_data: PromptData, meta: RuleMeta): boolean {
    return meta.isSystemResource === true;
  },

  async validate(data: PromptData, _ctx: RuleContext): Promise<ValidationResult> {
    const requiredVars = getSystemPromptRequiredVars(data.name);
    if (!requiredVars || requiredVars.length === 0) {
      return { valid: true };
    }

    const missing = requiredVars.filter((v) => !data.content.includes(v));
    if (missing.length > 0) {
      return {
        valid: false,
        errors: missing.map(
          (v) => `System prompt '${data.name}' requires template variable ${v}`,
        ),
      };
    }

    return { valid: true };
  },
};
