import type { BrandProfile, Project } from "@/types/workflow";
import type { WebsiteIntelligence } from "./website-intelligence";
import { buildCreativeBriefBeat, buildStoryArcFromSources } from "./creative-brief-builder";
import type { StoryArcBeat, StoryContextInput } from "./story-types";

export type { StoryArcBeat, StoryContextInput } from "./story-types";

/** @deprecated Vertical detection moved to website scrape — kept for legacy imports. */
export function isEfaxProject(brand: BrandProfile, project: Project): boolean {
  const hay = [project.name, brand.companyName, project.industry, brand.industry, project.website]
    .filter(Boolean)
    .join(" ")
    .toLowerCase();
  return /efax|e-fax|fax.?broadcast|b2b.?fax|b2befax/.test(hay);
}

/**
 * Build 5-beat arc from website + brand (primary) and narrative scaffold (structure only).
 */
export function getStoryArcForProject(
  brand: BrandProfile,
  project: Project,
  website?: WebsiteIntelligence | null,
): StoryArcBeat[] {
  return buildStoryArcFromSources(brand, project, website);
}

/** @deprecated Library themes are no longer auto-applied — use buildStoryArcFromSources (website + brand). */
export function buildLibraryStoryArc(
  brand: BrandProfile,
  project: Project,
  website?: WebsiteIntelligence | null,
): StoryArcBeat[] {
  return buildStoryArcFromSources(brand, project, website);
}

/** @deprecated Static eFax arc removed — content comes from website + brand. */
export function buildEfaxStoryArc(
  brand: BrandProfile,
  project: Project,
  website?: WebsiteIntelligence | null,
): StoryArcBeat[] {
  return buildStoryArcFromSources(brand, project, website);
}

function composeProblemLine(beat: StoryArcBeat): string {
  // Use the synthesized problem only — do NOT append summary/structureGuidance
  // (that produced unfinished scraps like "tied to t" and repeated slogans).
  const problem = beat.problem.replace(/^Problem:\s*/i, "").trim();
  const problemSentence = /[.!?]$/.test(problem) ? problem : `${problem}.`;
  return `Problem: ${problemSentence}`;
}

function composeImpactLine(beat: StoryArcBeat): string {
  const parts = beat.impact.map((line) => line.replace(/^[-•]\s*/, "").trim()).filter(Boolean);
  if (!parts.length) return "Impact:";

  if (parts.length === 1) {
    const only = /[.!?]$/.test(parts[0]!) ? parts[0]! : `${parts[0]!}.`;
    return `Impact: ${only}`;
  }

  const [lead, ...rest] = parts;
  if (rest.length === 1) {
    return `Impact: ${lead!.replace(/\.$/, "")} — ${rest[0]!.replace(/\.$/, "")}.`;
  }

  const restProse = rest
    .map((p, i) => {
      const clean = p.replace(/\.$/, "");
      return i === 0 ? clean : clean.charAt(0).toLowerCase() + clean.slice(1);
    })
    .join("; ");

  return `Impact: ${lead!.replace(/\.$/, "")} — ${restProse}.`;
}

/**
 * Compact creative brief for AI and Posting Context UI.
 * Content is synthesized from website + brand — not static templates.
 */
export function renderStoryContext(input: StoryContextInput): string {
  const { beat } = input;
  const hashtags = beat.hashtags.trim();

  const brandBlock = beat.brandResponse?.trim()
    ? [`Brand response: ${beat.brandResponse.trim()}`, ""]
    : [];

  const engagementBlock = beat.engagementQuestion?.trim()
    ? [`Engagement question: ${beat.engagementQuestion.trim()}`, ""]
    : [];

  const categoryBlock = beat.contentCategory?.trim()
    ? [`Content category: ${beat.contentCategory.trim()}`, ""]
    : [];

  const seoBlock = beat.seoKeywords?.trim()
    ? [`SEO focus: ${beat.seoKeywords.trim()}`, ""]
    : [];

  return [
    composeProblemLine(beat),
    "",
    composeImpactLine(beat),
    ...brandBlock,
    ...categoryBlock,
    ...engagementBlock,
    ...seoBlock,
    hashtags,
  ]
    .join("\n")
    .replace(/\n{3,}/g, "\n\n")
    .trim();
}

export function storyBeatToSequenceTemplate(beat: StoryArcBeat): {
  title: string;
  summary: string;
  tag: string;
} {
  return { title: beat.title, summary: beat.summary, tag: beat.tag };
}

export function buildStoryContextPreview(
  beatIndex: number,
  brand: BrandProfile,
  project: Project,
  campaignName?: string,
  website?: WebsiteIntelligence | null,
): string {
  const beat = buildCreativeBriefBeat({ brand, project, beatIndex, website });
  const arc = getStoryArcForProject(brand, project, website);

  return renderStoryContext({
    brand,
    project,
    beat,
    beatIndex,
    totalBeats: arc.length,
    campaignName: campaignName?.trim() || project.name?.trim() || "Campaign",
  });
}

/** Extract Problem / Impact / Brand response from compact or legacy markdown context. */
export function parseStoryContextSections(content: string): {
  currentStory: string;
  problem: string;
  impact: string;
  brandResponse: string;
  keyTheme: string;
  engagementQuestion: string;
  contentCategory: string;
  seoKeywords: string;
} {
  const section = (heading: string): string => {
    const re = new RegExp(`## ${heading}\\s*\\n([\\s\\S]*?)(?=\\n## |\\n---|$)`, "i");
    const match = content.match(re);
    return match?.[1]?.trim() ?? "";
  };

  const problemInline = content.match(/^Problem:\s*([\s\S]*?)(?=\n\s*\nImpact:|\nImpact:)/i);
  const impactInline = content.match(/^Impact:\s*([\s\S]*?)(?=\n\s*\nBrand|\nBrand|\n\s*\n#|\n#|$)/im);
  const impactInlineAnywhere =
    impactInline ?? content.match(/\nImpact:\s*([\s\S]*?)(?=\n\s*\nBrand|\nBrand|\n\s*\n#|\n#|$)/i);

  const brandInline =
    content.match(/^Brand response:\s*([\s\S]*?)(?=\n\s*\n#|\n#|$)/im) ??
    content.match(/\nBrand response:\s*([\s\S]*?)(?=\n\s*\n#|\n#|$)/i);

  const problem =
    problemInline?.[1]?.trim() ||
    section("Problem") ||
    content.match(/Problem:\s*(.+?)(?:\n|$)/i)?.[1]?.trim() ||
    "";

  const impact =
    impactInlineAnywhere?.[1]?.trim() ||
    section("Impact") ||
    "";

  const brandResponse =
    brandInline?.[1]?.trim() ||
    section("Brand Response") ||
    "";

  const engagementInline =
    content.match(/^Engagement question:\s*(.+)$/im) ??
    content.match(/\nEngagement question:\s*(.+)$/im);

  const engagementQuestion =
    engagementInline?.[1]?.trim() ||
    section("Engagement Question") ||
    "";

  const categoryInline =
    content.match(/^Content category:\s*(.+)$/im) ??
    content.match(/\nContent category:\s*(.+)$/im);

  const contentCategory =
    categoryInline?.[1]?.trim() ||
    section("Content Category") ||
    "";

  const seoInline =
    content.match(/^SEO focus:\s*(.+)$/im) ??
    content.match(/\nSEO focus:\s*(.+)$/im);

  const seoKeywords =
    seoInline?.[1]?.trim() ||
    section("SEO Focus") ||
    "";

  return {
    currentStory: section("Current Story") || section("Campaign Story") || problem,
    problem,
    impact,
    brandResponse,
    keyTheme: section("Key Theme"),
    engagementQuestion,
    contentCategory,
    seoKeywords,
  };
}
