import commitPrompt from "./commit.txt" with { type: "text" };
import reviewPrompt from "./review.txt" with { type: "text" };

export const prompts = {
  commit: commitPrompt,
  review: reviewPrompt,
} as const;

export type PromptName = keyof typeof prompts;

export function getPrompt(name: PromptName): string {
  return prompts[name];
}

export function interpolate(
  template: string,
  variables: Record<string, any>,
): string {
  let result = template;

  for (const [key, value] of Object.entries(variables)) {
    const regex = new RegExp(`\\{${key}\\}`, "g");
    result = result.replace(regex, String(value));
  }

  result = result.replace(
    /\{([^}]+)\s*\?\s*"([^"]+)"\s*:\s*"([^"]*)"\}/g,
    (_, condition, trueText, falseText) => {
      const conditionValue = variables[condition.trim()];
      return conditionValue ? trueText : falseText;
    },
  );

  return result;
}

export function formatPrompt(
  name: PromptName,
  variables: Record<string, any>,
): string {
  const template = getPrompt(name);
  return interpolate(template, variables);
}
