import { readFileSync } from "fs";
import { join } from "path";

const promptsDir = join(import.meta.dir, "../prompts");

const promptCache = new Map<string, string>();

export function loadPromptSync(name: string): string {
  const cached = promptCache.get(name);
  if (cached) return cached;

  const filePath = join(promptsDir, `${name}.txt`);
  const content = readFileSync(filePath, "utf-8");
  
  if (!content.trim()) {
    throw new Error(`Prompt file ${name}.txt is empty`);
  }
  
  promptCache.set(name, content);
  return content;
}

export async function loadPrompt(name: string): Promise<string> {
  const cached = promptCache.get(name);
  if (cached) return cached;

  const filePath = join(promptsDir, `${name}.txt`);
  const file = Bun.file(filePath);
  
  if (!await file.exists()) {
    throw new Error(`Prompt file ${name}.txt not found`);
  }
  
  const content = await file.text();
  
  if (!content.trim()) {
    throw new Error(`Prompt file ${name}.txt is empty`);
  }
  
  promptCache.set(name, content);
  return content;
}

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 async function getPrompt(name: string, variables?: Record<string, any>): Promise<string> {
  const template = await loadPrompt(name);
  return variables ? interpolate(template, variables) : template;
}

export function getPromptSync(name: string, variables?: Record<string, any>): string {
  const template = loadPromptSync(name);
  return variables ? interpolate(template, variables) : template;
}