import type { BrandProfile, GeneratedPost, PostingContextData, Project } from "@/types/workflow";
import type { WebsiteIntelligence } from "@/lib/context/website-intelligence";
import { formatBusinessContextMarkdown } from "@/lib/context/business-context";

export interface ProjectContextChunk {
  id: string;
  docType: "brand" | "audience" | "products" | "sequence" | "website" | "published";
  content: string;
}

/** Build in-memory project context documents (WHAT to post). Not persisted to vector DB in v1. */
export function buildProjectContextChunks(input: {
  project: Project;
  brand: BrandProfile;
  context?: PostingContextData;
  website?: WebsiteIntelligence | null;
  approvedPosts?: GeneratedPost[];
}): ProjectContextChunk[] {
  const chunks: ProjectContextChunk[] = [];
  const { project, brand, context, website, approvedPosts } = input;

  if (context?.businessContext) {
    chunks.push({
      id: `proj:${project.id}:business-context`,
      docType: "brand",
      content: formatBusinessContextMarkdown(context.businessContext).slice(0, 4000),
    });
  }

  if (brand.companyName || brand.tagline || brand.brandVoice) {
    chunks.push({
      id: `proj:${project.id}:brand`,
      docType: "brand",
      content: [
        brand.companyName && `Company: ${brand.companyName}`,
        brand.tagline && `Tagline: ${brand.tagline}`,
        brand.brandVoice && `Voice: ${brand.brandVoice}`,
        (brand.industry || project.industry) && `Industry: ${brand.industry || project.industry}`,
      ]
        .filter(Boolean)
        .join("\n"),
    });
  }

  if (brand.targetAudience?.trim()) {
    chunks.push({
      id: `proj:${project.id}:audience`,
      docType: "audience",
      content: brand.targetAudience.trim(),
    });
  }

  if (brand.productsServices?.trim()) {
    chunks.push({
      id: `proj:${project.id}:products`,
      docType: "products",
      content: brand.productsServices.trim(),
    });
  }

  if (project.website?.trim()) {
    chunks.push({
      id: `proj:${project.id}:website-url`,
      docType: "website",
      content: `Website: ${project.website}`,
    });
  }

  if (website?.analysisMarkdown?.trim()) {
    chunks.push({
      id: `proj:${project.id}:website-intel`,
      docType: "website",
      content: website.analysisMarkdown.slice(0, 4000),
    });
  } else if (website) {
    const parts = [
      website.title && `Title: ${website.title}`,
      website.description && `Description: ${website.description}`,
      website.primaryService && `Primary service: ${website.primaryService}`,
      website.services?.length &&
        `Services: ${website.services.map((s) => s.label).join(", ")}`,
      website.benefits?.length && `Benefits: ${website.benefits.join("; ")}`,
    ].filter(Boolean);
    if (parts.length) {
      chunks.push({
        id: `proj:${project.id}:website-intel`,
        docType: "website",
        content: parts.join("\n"),
      });
    }
  }

  if (context?.posts?.length) {
    context.posts.forEach((beat, i) => {
      if (!beat.content?.trim() && !beat.summary?.trim()) return;
      chunks.push({
        id: `proj:${project.id}:sequence:${beat.id}`,
        docType: "sequence",
        content: [`Beat ${i + 1}: ${beat.title}`, beat.summary, beat.content]
          .filter(Boolean)
          .join("\n"),
      });
    });
  }

  if (project.countries.length) {
    chunks.push({
      id: `proj:${project.id}:markets`,
      docType: "audience",
      content: `Target markets: ${project.countries.join(", ")} · Timezone: ${project.timezone}`,
    });
  }

  for (const post of approvedPosts ?? []) {
    if (post.status !== "published" && post.status !== "approved") continue;
    chunks.push({
      id: `proj:${project.id}:published:${post.id}`,
      docType: "published",
      content: post.caption.slice(0, 2000),
    });
  }

  return chunks.filter((c) => c.content.trim().length > 0);
}

export function formatProjectContextForPrompt(chunks: ProjectContextChunk[]): string {
  if (!chunks.length) return "";
  return chunks.map((c) => `### ${c.docType}\n${c.content}`).join("\n\n");
}
