import "server-only";
import { readFileSync } from "fs";
import { join } from "path";

let cachedBase: string | null = null;

/** 讀取 lib/ai/agent.md 基底指令（所有 AI 請求都會附上） */
export function getAgentBasePrompt(): string {
  if (cachedBase !== null) return cachedBase;
  try {
    const path = join(process.cwd(), "lib/ai/agent.md");
    cachedBase = readFileSync(path, "utf-8").trim();
  } catch {
    cachedBase = "";
  }
  return cachedBase;
}

/** 將任務專屬 system prompt 與 agent.md 基底合併 */
export function withAgentSystem(rolePrompt: string): string {
  const base = getAgentBasePrompt();
  const role = rolePrompt.trim();
  return `${base}\n\n---\n\n${role}`;
}