import type { MasterContext } from "../intelligence/types";
import type { StoryContextSections } from "@/lib/generation/social-image";

/** Image Context Builder — visual intelligence + story sections for image generation. */
export function buildImageGenerationContext(
  master: MasterContext,
  storySections: StoryContextSections,
  captionExcerpt: string,
) {
  return {
    visualIntelligence: master.visual,
    storyIntelligence: master.story,
    brand: master.brand,
    problemTheme: storySections.problem || master.story.conflict,
    impactTheme: storySections.impact || master.story.transformation,
    brandResponse: storySections.brandResponse || master.story.solution,
    keyTheme: storySections.keyTheme || master.story.keyTheme,
    visualConcept: `${master.visual.mood}. ${master.story.letterToGodBeat.visualMood}`,
    captionExcerpt,
    narrativePhase: master.story.letterToGodBeat.title,
  };
}

export function formatImageContextPrompt(ctx: ReturnType<typeof buildImageGenerationContext>): string {
  return [
    `Narrative phase (structure only): ${ctx.narrativePhase}`,
    `Visual mood: ${ctx.visualConcept}`,
    `Photography: ${ctx.visualIntelligence.photographyStyle}`,
    `Lighting: ${ctx.visualIntelligence.lighting}`,
    `Expressions: ${ctx.visualIntelligence.expressions}`,
    `Problem theme (from website/brand — image must reflect): ${ctx.problemTheme}`,
    `Impact theme: ${ctx.impactTheme}`,
    ctx.brandResponse ? `Brand response: ${ctx.brandResponse}` : "",
    `Brand: ${ctx.brand.companyName} — ${ctx.brand.industry}`,
    ctx.brand.primaryService ? `Primary service: ${ctx.brand.primaryService}` : "",
    captionExcerptLine(ctx.captionExcerpt),
  ]
    .filter(Boolean)
    .join("\n");
}

function captionExcerptLine(excerpt: string): string {
  if (!excerpt.trim()) return "";
  return `Caption context: ${excerpt.slice(0, 200)}`;
}
