/**
 * Enrichment Context Service
 * ──────────────────────────
 * Single source of truth for brand enrichment data (uploaded documents).
 * Any AI feature calls getEnrichmentContext() to include uploaded brand
 * docs in its prompt context.
 */

import { prisma } from "@/lib/prisma";

export interface EnrichmentContext {
  hasEnrichmentData: boolean;
  fileCount: number;
  documents: Array<{
    fileName: string;
    fileType: string;
    extractedText: string;
    uploadedAt: Date;
  }>;
  /** All docs concatenated with headers, ready for prompt injection */
  combinedText: string;
  /** Rough token estimate (~4 chars per token) */
  tokenEstimate: number;
}

const MAX_TOKENS = 50000;
const MAX_PER_DOC_CHARS = 8000; // ~2000 tokens per doc

/**
 * Get enrichment context for a brand. Returns extracted text from all
 * uploaded documents with processingStatus = "ready".
 */
export async function getEnrichmentContext(brandId: string): Promise<EnrichmentContext> {
  const files = await prisma.enrichmentFile.findMany({
    where: { brandId, processingStatus: "ready", extractedText: { not: null } },
    orderBy: { uploadedAt: "desc" },
    select: { fileName: true, fileType: true, extractedText: true, uploadedAt: true },
  });

  if (files.length === 0) {
    return { hasEnrichmentData: false, fileCount: 0, documents: [], combinedText: "", tokenEstimate: 0 };
  }

  const documents = files.map((f) => ({
    fileName: f.fileName,
    fileType: f.fileType,
    extractedText: (f.extractedText || "").slice(0, MAX_PER_DOC_CHARS),
    uploadedAt: f.uploadedAt,
  }));

  // Build combined text with headers
  let combined = "";
  let totalChars = 0;
  for (const doc of documents) {
    const header = `\n--- ${doc.fileType.toUpperCase()}: ${doc.fileName} ---\n`;
    const text = doc.extractedText;
    if (totalChars + header.length + text.length > MAX_TOKENS * 4) {
      combined += `\n[...additional documents truncated — ${documents.length - documents.indexOf(doc)} files skipped]\n`;
      break;
    }
    combined += header + text + "\n";
    totalChars += header.length + text.length;
  }

  return {
    hasEnrichmentData: true,
    fileCount: files.length,
    documents,
    combinedText: combined.trim(),
    tokenEstimate: Math.ceil(totalChars / 4),
  };
}

/**
 * Format enrichment context for inclusion in an AI prompt.
 */
export function formatEnrichmentForPrompt(ctx: EnrichmentContext): string {
  if (!ctx.hasEnrichmentData) return "";
  return [
    `BRAND ENRICHMENT DATA (${ctx.fileCount} uploaded document${ctx.fileCount !== 1 ? "s" : ""}, ~${ctx.tokenEstimate} tokens):`,
    ctx.combinedText,
  ].join("\n");
}
