import type { KnowledgeHit, KnowledgePlatform } from "./types";

export type RagPromptPurpose = "caption" | "image" | "video" | "chat";

const PURPOSE_LABEL: Record<RagPromptPurpose, string> = {
  caption: "caption writing",
  image: "banner / image composition",
  video: "short-form video",
  chat: "audience & strategy Q&A",
};

/** Format retrieved chunks for injection into generation or chat prompts. */
export function formatKnowledgeForPrompt(
  hits: KnowledgeHit[],
  platform: KnowledgePlatform,
  purpose: RagPromptPurpose,
): string {
  if (!hits.length) return "";

  const lines = [
    `## Platform knowledge (${platform} — ${PURPOSE_LABEL[purpose]})`,
    "Use these platform-specific patterns ONLY where they fit the project brief.",
    "This is HOW to write for the platform — not a source of company facts.",
    "Do NOT invent clients, metrics, offers, phone numbers, or results.",
    "If a fact is missing or unknown in the project/business context, leave it missing — do not fill it from this knowledge.",
    "",
  ];

  hits.forEach((h, i) => {
    lines.push(
      `### KB [${i + 1}] ${h.sectionTitle} (topic=${h.topic}, relevance=${h.score.toFixed(3)})`,
      h.content.trim(),
      "",
    );
  });

  return lines.join("\n").trim();
}

export function buildRagChatSystemPrompt(platform: KnowledgePlatform): string {
  return [
    "You are PostSync Pro's grounded social marketing assistant.",
    `Platform scope: ${platform} knowledge only (independent index — do not cite other networks).`,
    "Rules:",
    "- Use ONLY retrieved knowledge chunks + any project/brand facts supplied by the user.",
    "- If information is missing, say what is missing — do not invent statistics or client names.",
    "- Prefer actionable audience definitions, content angles, and posting patterns.",
    "- Keep answers concise and structured (bullets or short sections).",
  ].join("\n");
}

export function buildRagChatUserPrompt(input: {
  question: string;
  knowledgeBlock: string;
  projectContext?: string;
}): string {
  const parts = [
    input.knowledgeBlock,
    input.projectContext?.trim()
      ? `\n## Project / brand context\n${input.projectContext.trim()}`
      : "",
    `\n## Question\n${input.question.trim()}`,
    "\nAnswer using only the context above.",
  ];
  return parts.filter(Boolean).join("\n");
}
