/**
 * Content export formatters.
 *
 * Converts a ContentBrief's sections into export-ready formats.
 * No real integrations yet — just structured data that's ready
 * to be sent to Google Docs, Word, or clipboard when wired up.
 */

// ─── Types ───────────────────────────────────────────────────────────────────

interface Section {
  id: string;
  type: string;
  heading?: string;
  content: string;
  order: number;
}

interface Link {
  anchorText: string;
  targetUrl: string;
  context?: string;
  category?: string;
}

interface BriefData {
  id: string;
  type: string;
  title: string;
  primaryKeyword?: string | null;
  primaryTopic?: string | null;
  brandName?: string | null;
  city?: string | null;
  service?: string | null;
  contentScore: number;
  subScores: unknown;
  sections: unknown;
  internalLinks: unknown;
  writerNotes?: string | null;
  tone: string;
  humanizationMode: boolean;
}

export interface ExportOutput {
  format: string;
  title: string;
  content: string;
  metadata: {
    briefId: string;
    type: string;
    contentScore: number;
    subScores: unknown;
    tone: string;
    humanized: boolean;
    exportedAt: string;
  };
}

// ─── Main export function ────────────────────────────────────────────────────

export function exportBrief(
  brief: BriefData,
  format: "outline" | "plaintext" | "gdocs" | "word"
): ExportOutput {
  const sections = parseSections(brief.sections);
  const links = parseLinks(brief.internalLinks);

  let content: string;

  switch (format) {
    case "outline":
      content = formatAsOutline(brief, sections, links);
      break;
    case "plaintext":
      content = formatAsPlainText(brief, sections, links);
      break;
    case "gdocs":
      content = formatForGoogleDocs(brief, sections, links);
      break;
    case "word":
      content = formatForWord(brief, sections, links);
      break;
  }

  return {
    format,
    title: brief.title,
    content,
    metadata: {
      briefId: brief.id,
      type: brief.type,
      contentScore: brief.contentScore,
      subScores: brief.subScores,
      tone: brief.tone,
      humanized: brief.humanizationMode,
      exportedAt: new Date().toISOString(),
    },
  };
}

// ─── Format: Structured Outline ──────────────────────────────────────────────
// Hierarchical outline with section types labeled

function formatAsOutline(brief: BriefData, sections: Section[], links: Link[]): string {
  const lines: string[] = [];

  lines.push(`# ${brief.title}`);
  lines.push(`Type: ${brief.type.toUpperCase()} Content Brief`);
  lines.push(`Score: ${brief.contentScore}/100`);
  lines.push(`Tone: ${brief.tone} | Humanized: ${brief.humanizationMode ? "Yes" : "No"}`);

  if (brief.primaryKeyword) lines.push(`Primary Keyword: ${brief.primaryKeyword}`);
  if (brief.primaryTopic) lines.push(`Primary Topic: ${brief.primaryTopic}`);
  if (brief.brandName) lines.push(`Brand: ${brief.brandName}`);
  if (brief.city) lines.push(`Location: ${brief.city}`);

  lines.push("");
  lines.push("---");
  lines.push("");
  lines.push("## CONTENT OUTLINE");
  lines.push("");

  for (const section of sections) {
    const indent = getIndent(section.type);
    const label = getSectionLabel(section.type);

    if (section.type === "faq") {
      lines.push(`${indent}${label}`);
      const faqs = parseFaq(section.content);
      for (const faq of faqs) {
        lines.push(`${indent}  Q: ${faq.q}`);
        lines.push(`${indent}  A: ${faq.a}`);
        lines.push("");
      }
    } else {
      lines.push(`${indent}${label}${section.heading ? `: ${section.heading}` : ""}`);
      if (section.content && section.type !== "meta_title" && section.type !== "meta_description") {
        lines.push(`${indent}  ${truncate(section.content, 200)}`);
      } else if (section.content) {
        lines.push(`${indent}  "${section.content}"`);
      }
      lines.push("");
    }
  }

  if (links.length > 0) {
    lines.push("## INTERNAL LINKS");
    lines.push("");
    for (const link of links) {
      lines.push(`  - "${link.anchorText}" → ${link.targetUrl}`);
      if (link.context) lines.push(`    ${link.context}`);
    }
    lines.push("");
  }

  if (brief.writerNotes) {
    lines.push("## WRITER NOTES");
    lines.push(brief.writerNotes);
  }

  return lines.join("\n");
}

// ─── Format: Plain Text ──────────────────────────────────────────────────────
// Clean text ready for copy/paste

function formatAsPlainText(brief: BriefData, sections: Section[], links: Link[]): string {
  const lines: string[] = [];

  for (const section of sections) {
    if (section.type === "meta_title") {
      lines.push(`Title Tag: ${section.content}`);
      lines.push("");
    } else if (section.type === "meta_description") {
      lines.push(`Meta Description: ${section.content}`);
      lines.push("");
    } else if (section.type === "faq") {
      if (section.heading) lines.push(section.heading);
      lines.push("");
      const faqs = parseFaq(section.content);
      for (const faq of faqs) {
        lines.push(`Q: ${faq.q}`);
        lines.push(`A: ${faq.a}`);
        lines.push("");
      }
    } else {
      if (section.heading) {
        lines.push(section.heading);
        lines.push("");
      }
      if (section.content) {
        lines.push(section.content);
        lines.push("");
      }
    }
  }

  if (links.length > 0) {
    lines.push("---");
    lines.push("Internal Linking Suggestions:");
    lines.push("");
    for (const link of links) {
      lines.push(`• "${link.anchorText}" → ${link.targetUrl}`);
    }
  }

  return lines.join("\n");
}

// ─── Format: Google Docs (placeholder) ───────────────────────────────────────
// Structured JSON that would be sent to Google Docs API

function formatForGoogleDocs(brief: BriefData, sections: Section[], links: Link[]): string {
  const doc = {
    _format: "google_docs_placeholder",
    _note: "This structure is ready for the Google Docs API. Wire up the googleapis package to create real documents.",
    documentTitle: brief.title,
    body: sections.map((section) => {
      if (section.type === "meta_title" || section.type === "meta_description") {
        return {
          type: "paragraph",
          style: "NORMAL_TEXT",
          text: `[${getSectionLabel(section.type)}] ${section.content}`,
          bold: true,
          fontSize: 10,
        };
      }

      if (section.type === "h1") {
        return { type: "heading", style: "HEADING_1", text: section.content };
      }

      if (section.type === "h2") {
        return { type: "heading", style: "HEADING_2", text: section.heading || section.content };
      }

      if (section.type === "h3") {
        return { type: "heading", style: "HEADING_3", text: section.heading || section.content };
      }

      if (section.type === "faq") {
        const faqs = parseFaq(section.content);
        return {
          type: "faq_block",
          heading: section.heading || "FAQ",
          style: "HEADING_2",
          items: faqs.map((f) => ({
            question: { type: "heading", style: "HEADING_3", text: f.q },
            answer: { type: "paragraph", style: "NORMAL_TEXT", text: f.a },
          })),
        };
      }

      return {
        type: "paragraph",
        style: "NORMAL_TEXT",
        text: section.content,
        heading: section.heading ? { type: "heading", style: "HEADING_2", text: section.heading } : undefined,
      };
    }),
    internalLinks: links.map((l) => ({
      anchorText: l.anchorText,
      url: l.targetUrl,
      placement: l.context,
    })),
  };

  return JSON.stringify(doc, null, 2);
}

// ─── Format: Word (placeholder) ──────────────────────────────────────────────
// Structured JSON that would be sent to docx generation library

function formatForWord(brief: BriefData, sections: Section[], links: Link[]): string {
  const doc = {
    _format: "word_docx_placeholder",
    _note: "This structure is ready for the docx npm package. Wire up 'docx' to generate real .docx files.",
    properties: {
      title: brief.title,
      creator: brief.brandName || "meSEO",
      description: `${brief.type.toUpperCase()} Content Brief — Score: ${brief.contentScore}/100`,
    },
    sections: [
      {
        children: sections.map((section) => {
          if (section.type === "h1") {
            return { type: "Heading1", text: section.content };
          }
          if (section.type === "h2" || section.type === "conversational_intro" || section.type === "question" || section.type === "answer_first" || section.type === "insight" || section.type === "summary") {
            return { type: "Heading2", text: section.heading || section.content };
          }
          if (section.type === "h3") {
            return { type: "Heading3", text: section.heading || section.content };
          }
          if (section.type === "meta_title" || section.type === "meta_description") {
            return { type: "Paragraph", text: `[${getSectionLabel(section.type)}] ${section.content}`, style: { bold: true, color: "666666" } };
          }
          if (section.type === "faq") {
            const faqs = parseFaq(section.content);
            return {
              type: "FAQBlock",
              items: faqs.map((f) => ({
                question: { type: "Heading3", text: f.q },
                answer: { type: "Paragraph", text: f.a },
              })),
            };
          }
          return { type: "Paragraph", text: section.content };
        }),
      },
      {
        children: [
          { type: "Heading2", text: "Internal Linking Suggestions" },
          ...links.map((l) => ({
            type: "Paragraph",
            text: `"${l.anchorText}" → ${l.targetUrl}`,
            style: { italics: true },
          })),
        ],
      },
    ],
  };

  return JSON.stringify(doc, null, 2);
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function parseSections(raw: unknown): Section[] {
  if (!raw) return [];
  try {
    const arr = typeof raw === "string" ? JSON.parse(raw) : raw;
    if (!Array.isArray(arr)) return [];
    return arr.map((s: Record<string, unknown>, i: number) => ({
      id: String(s.id || `s${i}`),
      type: String(s.type || "paragraph"),
      heading: s.heading ? String(s.heading) : undefined,
      content: String(s.content || ""),
      order: Number(s.order || i),
    }));
  } catch {
    return [];
  }
}

function parseLinks(raw: unknown): Link[] {
  if (!raw) return [];
  try {
    const arr = typeof raw === "string" ? JSON.parse(raw) : raw;
    if (!Array.isArray(arr)) return [];
    return arr.map((l: Record<string, unknown>) => ({
      anchorText: String(l.anchorText || l.anchor || ""),
      targetUrl: String(l.targetUrl || l.targetPage || ""),
      context: l.context ? String(l.context) : undefined,
      category: l.category ? String(l.category) : undefined,
    }));
  } catch {
    return [];
  }
}

function parseFaq(content: string): Array<{ q: string; a: string }> {
  try {
    const parsed = JSON.parse(content);
    if (Array.isArray(parsed)) return parsed;
    return [];
  } catch {
    return [];
  }
}

function getSectionLabel(type: string): string {
  const labels: Record<string, string> = {
    meta_title: "META TITLE",
    meta_description: "META DESCRIPTION",
    h1: "H1",
    h2: "H2",
    h3: "H3",
    intro: "INTRO",
    faq: "FAQ",
    conclusion: "CONCLUSION / CTA",
    cta: "CTA",
    conversational_intro: "CONVERSATIONAL INTRO",
    question: "QUESTION",
    answer_first: "ANSWER",
    insight: "INSIGHT",
    summary: "SUMMARY",
  };
  return labels[type] || type.toUpperCase();
}

function getIndent(type: string): string {
  if (type === "h3") return "      ";
  if (type === "h2" || type === "faq" || type === "question" || type === "answer_first" || type === "insight") return "    ";
  if (type === "intro" || type === "conclusion" || type === "summary" || type === "conversational_intro") return "    ";
  return "  ";
}

function truncate(text: string, max: number): string {
  return text.length > max ? text.slice(0, max) + "..." : text;
}
