import type { MasterContext, MasterContextInput } from "../intelligence/types";
import type { WebsiteIntelligence } from "../website-intelligence";
import { formatWebsiteIntelligenceMarkdown } from "../website-intelligence";
import { buildBrandIntelligence, formatBrandIntelligenceMarkdown } from "../intelligence/brand-intelligence";
import { buildStoryIntelligence, formatStoryIntelligenceMarkdown } from "../intelligence/story-intelligence";
import {
  buildCreativeIntelligence,
  formatCreativeIntelligenceMarkdown,
} from "../intelligence/creative-intelligence";
import {
  buildPlatformIntelligence,
  formatPlatformIntelligenceMarkdown,
} from "../intelligence/platform-intelligence";
import {
  buildVisualIntelligence,
  formatVisualIntelligenceMarkdown,
} from "../intelligence/visual-intelligence";
import {
  buildVideoIntelligence,
  formatVideoIntelligenceMarkdown,
} from "../intelligence/video-intelligence";
import { getStoryArcForProject, renderStoryContext } from "../story-context-builder";
import { buildCreativeBriefBeat } from "../creative-brief-builder";

/**
 * Master Context Builder — orchestrates Brand + Creative Intelligence
 * into one shared understanding for text, image, and video generation.
 *
 * The compact creative brief (Problem / Impact / Hashtags) remains the
 * primary content source; intelligence layers enrich generation without
 * replacing the posting context UI format.
 */
export function buildMasterContext(
  input: MasterContextInput & { website?: WebsiteIntelligence | null },
): MasterContext {
  const { brand, project, creativeBrief, beatIndex, connectedPlatforms, website } = input;

  const brandIntel = buildBrandIntelligence(brand, project, website);
  const arc = getStoryArcForProject(brand, project, website);
  const beat = input.beat ?? arc[beatIndex] ?? buildCreativeBriefBeat({ brand, project, beatIndex, website });
  const storyIntel = buildStoryIntelligence(beat, beatIndex, arc.length);
  const creativeIntel = buildCreativeIntelligence(beatIndex, storyIntel.emotions);
  const platforms = buildPlatformIntelligence(connectedPlatforms);
  const visualIntel = buildVisualIntelligence(brandIntel, storyIntel, website);
  const videoIntel = buildVideoIntelligence(brandIntel, storyIntel, creativeBrief);

  const markdown = formatMasterContextMarkdown({
    projectId: input.projectId,
    project,
    creativeBrief,
    brand: brandIntel,
    story: storyIntel,
    creative: creativeIntel,
    platforms,
    visual: visualIntel,
    video: videoIntel,
    website,
    schedule: input.schedule,
    automation: input.automation,
    connectedPlatforms,
  });

  return {
    creativeBrief,
    brand: brandIntel,
    story: storyIntel,
    creative: creativeIntel,
    platforms,
    visual: visualIntel,
    video: videoIntel,
    markdown,
  };
}

function formatMasterContextMarkdown(input: {
  projectId: string;
  project: MasterContextInput["project"];
  creativeBrief: string;
  brand: MasterContext["brand"];
  story: MasterContext["story"];
  creative: MasterContext["creative"];
  platforms: MasterContext["platforms"];
  visual: MasterContext["visual"];
  video: MasterContext["video"];
  website?: WebsiteIntelligence | null;
  schedule?: MasterContextInput["schedule"];
  automation?: MasterContextInput["automation"];
  connectedPlatforms?: string[];
}): string {
  const automationLines = input.automation
    ? Object.entries(input.automation)
        .filter(([, on]) => on)
        .map(([key]) => `- ${key}`)
        .join("\n")
    : "";

  return [
    `# Master Context — ${input.brand.companyName}`,
    `Project ID: ${input.projectId}`,
    "",
    "## Creative Brief (primary — grounded in website + brand; narrative act provides structure only)",
    input.creativeBrief,
    "",
    formatBrandIntelligenceMarkdown(input.brand),
    "",
    formatWebsiteIntelligenceMarkdown(input.website),
    "",
    formatStoryIntelligenceMarkdown(input.story),
    "",
    formatCreativeIntelligenceMarkdown(input.creative),
    "",
    formatPlatformIntelligenceMarkdown(input.platforms),
    "",
    formatVisualIntelligenceMarkdown(input.visual),
    "",
    formatVideoIntelligenceMarkdown(input.video),
    "",
    "## Project Snapshot",
    `Name: ${input.project.name}`,
    `Website: ${input.project.website || "Not provided"}`,
    `Industry: ${input.project.industry}`,
    `Timezone: ${input.project.timezone}`,
    `Target markets: ${input.project.countries.join(", ") || "Not specified"}`,
    `Status: ${input.project.status}`,
    "",
    "## Schedule",
    input.schedule
      ? `Posts per day: ${input.schedule.postsPerDay} (${input.schedule.saved ? "saved" : "draft"})`
      : "Not configured",
    "",
    "## Automation",
    automationLines || "None enabled",
    "",
    "## Connected Platforms",
    input.connectedPlatforms?.join(", ") || "linkedin, facebook",
  ].join("\n");
}

/** Compact appendix for LLM — intelligence summary without full markdown bulk. */
export function buildMasterContextAppendix(master: MasterContext): string {
  return [
    "## Context Engineering (website + brand primary; narrative structure for tone)",
    `Narrative phase: ${master.story.letterToGodBeat.title}`,
    `Emotions: ${master.story.emotions.join(", ")}`,
    `Tone lesson: ${master.story.lesson}`,
    `Visual mood: ${master.story.letterToGodBeat.visualMood}`,
    `Video hook: ${master.video.openingHook}`,
    `Write like: ${master.brand.writingStyle}`,
    master.brand.primaryService ? `Primary service: ${master.brand.primaryService}` : "",
  ]
    .filter(Boolean)
    .join("\n");
}
