import type {
  BrandProfile,
  ConnectedAccount,
  PostSequenceItem,
  PostingContextData,
  Project,
} from "@/types/workflow";
import { getSequenceContent } from "./format-sequence-context";
import { buildTextUserPrompt } from "./build-project-context";
import {
  buildMasterContext,
  buildMasterContextAppendix,
} from "./builders/master-context-builder";
import { resolveConnectedPublishPlatforms } from "@/lib/social/publish-platforms";
import { resolveWebsiteIntelligence, type WebsiteIntelligence } from "./website-intelligence";
import { buildCreativeBriefBeat } from "./creative-brief-builder";
import { renderStoryContext } from "./story-context-builder";

export interface FullProjectContextInput {
  projectId: string;
  project: Project;
  brand: BrandProfile;
  context: PostingContextData;
  sequenceItem: PostSequenceItem;
  schedule?: { postsPerDay: 1 | 2; saved: boolean };
  automation?: Record<string, boolean>;
  accounts?: ConnectedAccount[];
  website?: WebsiteIntelligence | null;
}

function resolveBeatIndex(context: PostingContextData, sequenceItem: PostSequenceItem): number {
  const idx = context.posts.findIndex((p) => p.id === sequenceItem.id);
  return idx >= 0 ? idx : 0;
}

/** Synthesize creative brief from website + brand (primary source of truth). */
function synthesizeCreativeBrief(input: {
  brand: BrandProfile;
  project: Project;
  sequenceItem: PostSequenceItem;
  context: PostingContextData;
  website: WebsiteIntelligence | null;
  beatIndex: number;
}): string {
  const beat = buildCreativeBriefBeat({
    brand: input.brand,
    project: input.project,
    beatIndex: input.beatIndex,
    website: input.website,
  });

  return renderStoryContext({
    brand: input.brand,
    project: input.project,
    beat,
    beatIndex: input.beatIndex,
    totalBeats: input.context.posts.length || 5,
    campaignName: input.context.name,
  });
}

/** Full AI context snapshot — Master Context + legacy project sections. */
export async function buildFullProjectContext(input: FullProjectContextInput): Promise<string> {
  const { master } = await buildMasterContextForGeneration(input);
  return master.markdown;
}

/** Structured master context for image, video, and scoring pipelines. */
export async function buildMasterContextForGeneration(input: FullProjectContextInput) {
  const website =
    input.website ??
    (await resolveWebsiteIntelligence(input.projectId, input.project, input.brand));

  const beatIndex = resolveBeatIndex(input.context, input.sequenceItem);
  const creativeBrief = synthesizeCreativeBrief({
    brand: input.brand,
    project: input.project,
    sequenceItem: input.sequenceItem,
    context: input.context,
    website,
    beatIndex,
  });

  const connectedPlatforms = resolveConnectedPublishPlatforms(input.accounts ?? []);

  const master = buildMasterContext({
    projectId: input.projectId,
    project: input.project,
    brand: input.brand,
    sequenceItem: input.sequenceItem,
    creativeBrief,
    beatIndex,
    schedule: input.schedule,
    automation: input.automation,
    connectedPlatforms,
    website,
  });

  return {
    master,
    website,
    appendix: buildMasterContextAppendix(master),
    beatIndex,
    creativeBrief,
  };
}

/** User-facing generation prompt — creative brief only. */
export function buildGenerationUserPrompt(
  sequenceItem: PostSequenceItem,
  input?: { companyName?: string; industry?: string },
): string {
  return buildTextUserPrompt(getSequenceContent(sequenceItem), {
    companyName: input?.companyName,
    industry: input?.industry,
  });
}
