import mammoth from 'mammoth';
import TurndownService from 'turndown';
import { gfm } from 'turndown-plugin-gfm';
import { BadRequestError } from '../../lib/errors';
import { createMedia, discardMedia, MEDIA_MAX_BYTES, sniffImage } from './blog-media.service';
import { checkSlug, createPost, type Actor } from './blog-posts.service';
import { LIMITS, mediaPath, postFieldsSchema } from './blog-rules';

/**
 * Word document → blog draft (docs/blog-cms-plan.md, D5), as GymCare does it.
 *
 * The team writes posts in Word in a fixed shape: an SEO table at the top
 * (field | value: URL, SEO title, Meta description, Primary keyword,
 * Secondary keywords, Featured image alt text, Author), the H1 title, a
 * byline, H2/H3 sections, a "Frequently asked questions" section (H3 question
 * + answer), a short closing call to action, and [square bracket] notes for
 * what is still to do.
 *
 * mammoth turns the .docx into HTML, turndown (with GFM tables) into Markdown,
 * and the known parts are lifted into the post's fields. Anything uncertain
 * stays in the body; bracketed notes come back as notes, not text. Embedded
 * images go through the same checks as an upload; if the draft can't be made,
 * the images it stored are removed again.
 */

export const DOCX_MAX_BYTES = 15 * 1024 * 1024;

const SEO_FIELDS: [RegExp, keyof SeoFields][] = [
  [/^(url|slug|web address|address)$/i, 'slug'],
  [/^(seo|search|meta) ?title$/i, 'metaTitle'],
  [/^(meta|search) ?description$/i, 'description'],
  [/^primary keyword$/i, 'primaryKeyword'],
  [/^secondary keywords?$/i, 'secondaryKeywords'],
  [/^(featured|cover) image alt( text)?$/i, 'coverAlt'],
  [/^author$/i, 'authorName'],
  [/^schema$/i, 'schema'],
];

interface SeoFields {
  slug?: string;
  metaTitle?: string;
  description?: string;
  primaryKeyword?: string;
  secondaryKeywords?: string;
  coverAlt?: string;
  authorName?: string;
  schema?: string;
}

function turndown() {
  const td = new TurndownService({ headingStyle: 'atx', bulletListMarker: '-', codeBlockStyle: 'fenced', emDelimiter: '*' });
  td.use(gfm);
  // Word often makes a whole heading bold; keep the heading plain.
  td.addRule('plainHeadings', {
    filter: ['h1', 'h2', 'h3', 'h4'],
    replacement: (content, node) => `\n\n${'#'.repeat(Number(node.nodeName[1]))} ${content.replace(/\*\*/g, '').trim()}\n\n`,
  });
  return td;
}

const unescape = (s: string) => s.replace(/\\([\\`*_{}[\]()#+\-.!>|])/g, '$1').trim();
const stripMd = (s: string) => unescape(s).replace(/\*\*/g, '').replace(/^\[|\]$/g, '');

/** The SEO table: the first GFM table whose rows look like field | value. */
export function extractSeoTable(md: string): { md: string; rows: [string, string][] } {
  const lines = md.split('\n');
  const start = lines.findIndex((l) => /^\|/.test(l.trim()));
  if (start === -1) return { md, rows: [] };
  let end = start;
  while (end < lines.length && /^\|/.test(lines[end].trim())) end += 1;
  const table = lines.slice(start, end);
  // Split on pipes that aren't escaped ("Title \| HostelCare" is one cell).
  const cells = (l: string) => l.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map((c) => stripMd(c));
  const header = cells(table[0]).map((c) => c.toLowerCase());
  if (!/field|setting/.test(header[0] ?? '') && !SEO_FIELDS.some(([re]) => re.test(cells(table[2] ?? '')[0] ?? ''))) return { md, rows: [] };
  // A value with a "|" in it comes back as extra cells: join them again.
  const rows = table
    .slice(2)
    .map(cells)
    .filter((r) => r.length >= 2 && r[0])
    .map((r): [string, string] => [r[0], r.slice(1).join(' | ').trim()]);
  return { md: [...lines.slice(0, start), ...lines.slice(end)].join('\n'), rows };
}

/** "## Frequently asked questions" with "### question" + answer → faqs. */
export function extractFaqs(md: string): { md: string; faqs: { q: string; a: string }[] } {
  const m = /^##\s+(frequently asked questions|faqs?)\s*$/im.exec(md);
  if (!m) return { md, faqs: [] };
  const rest = md.slice(m.index + m[0].length);
  const next = rest.search(/^##\s+/m);
  const section = next === -1 ? rest : rest.slice(0, next);
  const faqs: { q: string; a: string }[] = [];
  for (const q of section.split(/^###\s+/m).slice(1)) {
    const [question, ...answer] = q.split('\n');
    const a = answer.join('\n').trim();
    if (question.trim() && a) faqs.push({ q: stripMd(question).slice(0, LIMITS.faqs.q), a: unescape(a).replace(/\n+/g, ' ').slice(0, LIMITS.faqs.a) });
  }
  return { md: (md.slice(0, m.index) + (next === -1 ? '' : rest.slice(next))).trim(), faqs: faqs.slice(0, LIMITS.faqs.max) };
}

// "About the author" / "Source" paragraphs at the very end belong to the post.
const TAIL_RE = /^(\*{0,2}_?\*?(about the author|sources?)[:*_]|\*source)/i;

/** The last H2 section, if it is short and reads like a call to action → cta. */
export function extractCta(md: string): { md: string; cta: { heading: string; text: string } | null } {
  const idx = md.lastIndexOf('\n## ');
  if (idx === -1) return { md, cta: null };
  const [headingLine, ...bodyLines] = md.slice(idx + 1).split('\n');
  const paras = bodyLines.join('\n').split(/\n{2,}/).map((p) => p.trim()).filter(Boolean);
  const tail: string[] = [];
  while (paras.length && TAIL_RE.test(paras[paras.length - 1])) tail.unshift(paras.pop()!);
  const text = paras.join(' ');
  if (!paras.length || paras.length > 2 || text.length > 500 || !/demo|whatsapp|pricing|call|book|trial/i.test(text)) return { md, cta: null };
  return {
    md: [md.slice(0, idx).trim(), ...tail].join('\n\n'),
    cta: {
      heading: stripMd(headingLine.replace(/^##\s+/, '')).slice(0, LIMITS.cta.heading),
      text: unescape(text).replace(/\*\*/g, '').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').slice(0, LIMITS.cta.text),
    },
  };
}

/** [Author name], [Add screenshots…] → notes for the editor, out of the text. */
export function extractNotes(md: string): { md: string; notes: string[] } {
  const notes: string[] = [];
  const out = md
    .split('\n')
    .filter((line) => {
      const t = line.trim();
      if (/^\\?\[[^\]]{6,}\\?\]\.?$/.test(t)) {
        notes.push(stripMd(t));
        return false;
      }
      return true;
    })
    .join('\n');
  // Placeholders inside a line; not link texts ("[x](url)").
  const inline = [...out.matchAll(/\\?\[([A-Z][^\]\\]{3,60})\\?\](?!\()/g)].map((x) => `Placeholder in the text: [${x[1]}]`);
  return { md: out, notes: [...new Set([...notes, ...inline])] };
}

export async function importDocx(input: { body: Buffer; filename: string }, actor: Actor) {
  const { body, filename } = input;
  if (!body.length) throw new BadRequestError('Choose a Word document (.docx).', 'NO_FILE');
  if (body.length > DOCX_MAX_BYTES) throw new BadRequestError('A Word document can be at most 15 MB.', 'FILE_TOO_LARGE');
  // A .docx is a zip file.
  if (!(body[0] === 0x50 && body[1] === 0x4b && body[2] === 0x03 && body[3] === 0x04)) {
    throw new BadRequestError('That is not a Word document. Save it as .docx and try again.', 'NOT_DOCX');
  }

  const stored: string[] = [];
  const notes: string[] = [];
  let skipped = 0;
  let html: string;
  try {
    const result = await mammoth.convertToHtml(
      { buffer: body },
      {
        // mammoth's style map takes single quotes only.
        styleMap: ["p[style-name='Quote'] => blockquote:fresh", "p[style-name='Title'] => h1:fresh"],
        convertImage: mammoth.images.imgElement(async (image) => {
          const buf = Buffer.from(await image.readAsArrayBuffer());
          if (!sniffImage(buf) || buf.length > MEDIA_MAX_BYTES) {
            skipped += 1;
            return { src: '' };
          }
          try {
            const m = await createMedia({ body: buf, filename, userId: actor.id });
            stored.push(m.id);
            return { src: mediaPath(m.id), alt: '' };
          } catch {
            skipped += 1;
            return { src: '' };
          }
        }),
      },
    );
    html = result.value;
  } catch (err) {
    await discardMedia(stored);
    if (err instanceof BadRequestError) throw err;
    throw new BadRequestError("This Word document couldn't be read. Save it again as .docx and try again.", 'DOCX_UNREADABLE');
  }
  if (skipped) notes.push(`${skipped} image${skipped === 1 ? '' : 's'} in the document could not be used (only JPG, PNG or WebP up to 5 MB). Add ${skipped === 1 ? 'it' : 'them'} from the image library.`);

  try {
    // Word's tables have no header row, and the GFM rule keeps a table
    // without one as raw HTML: make each table's first row its header.
    html = html.replace(/<table>([\s\S]*?)<\/table>/g, (table) =>
      table.replace(/<tr>([\s\S]*?)<\/tr>/, (_m, row: string) => `<tr>${row.replace(/<td(\s|>)/g, '<th$1').replace(/<\/td>/g, '</th>')}</tr>`),
    );
    // Word puts a <p> in every table cell; the GFM table rule needs plain cells.
    html = html.replace(/<t([dh])([^>]*)>([\s\S]*?)<\/t\1>/g, (_m, tag: string, attrs: string, inner: string) =>
      `<t${tag}${attrs}>${inner.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '<br>').replace(/(\s*<br>\s*)+$/, '').trim()}</t${tag}>`,
    );
    let md = turndown()
      .turndown(html)
      .replace(/ /g, ' ')
      .replace(/!\[[^\]]*\]\(\s*\)/g, '') // images that were skipped
      .replace(/[ \t]+\n/g, '\n')
      .replace(/\n{3,}/g, '\n\n')
      .trim();

    const seo = extractSeoTable(md);
    md = seo.md;
    const fields: SeoFields = {};
    for (const [k, v] of seo.rows) {
      const hit = SEO_FIELDS.find(([re]) => re.test(k.trim()));
      if (hit && v) fields[hit[1]] = v;
    }
    let title = '';
    md = md.replace(/^#\s+(.+)$/m, (_m, t: string) => {
      title = stripMd(t);
      return '';
    });
    // A byline ("By … · Published … · 9 min read") → the author, if it names one.
    let byline: string | null = null;
    let bylinePlaceholder = false;
    md = md.replace(/^\*{0,2}By\s+([^·\n]+?)(?:,\s*([^·\n]+?))?\s*(?:·.*)?\*{0,2}$/m, (_m, a: string) => {
      bylinePlaceholder = /\[/.test(a);
      byline = stripMd(a);
      return '';
    });
    const faq = extractFaqs(md);
    md = faq.md;
    const noted = extractNotes(md); // before the CTA: a note in the last section would hide it
    md = noted.md;
    const cta = extractCta(md);
    md = cta.md.replace(/\n{3,}/g, '\n\n').trim();

    let slug = (fields.slug ?? '').replace(/^https?:\/\/[^/]+/i, '').replace(/^\/?(resources\/)?blogs?\//, '').replace(/^\/|\/$/g, '').trim().toLowerCase();
    if (slug) {
      const v = await checkSlug(slug);
      if (!v.available) {
        notes.push(`The document's address "${slug}" ${v.reason === 'TAKEN' ? 'is used by another post' : v.reason === 'INVALID' ? 'is not a valid address' : 'is already a page on the website'}, so one was made from the title.`);
        slug = '';
      }
    }
    const keywords = [fields.primaryKeyword, ...(fields.secondaryKeywords ?? '').split(/[,;]/)].map((k) => (k ?? '').trim()).filter(Boolean);
    const author = fields.authorName ?? (byline && !bylinePlaceholder ? byline : null);
    if (bylinePlaceholder) notes.push(`The document doesn't name the author (byline: ${byline}). Set the author.`);
    if (fields.schema) notes.push(`Schema note from the document: ${fields.schema}. The site adds Article, Breadcrumb and FAQ data itself.`);
    notes.push(fields.coverAlt ? 'Add the cover image (its description was imported).' : 'Add a cover image and its description.');
    if (fields.metaTitle && fields.metaTitle.length > LIMITS.metaTitle) notes.push(`The search title was cut to ${LIMITS.metaTitle} characters; check it reads well.`);
    if (fields.description && fields.description.length > LIMITS.description.max) notes.push(`The search description was cut to ${LIMITS.description.max} characters; check it reads well.`);
    notes.push(...noted.notes);

    // The same shape checks as a post saved in the editor.
    const parsed = postFieldsSchema.parse({
      title: (title || filename.replace(/\.docx$/i, '').replace(/[-_]+/g, ' ')).slice(0, LIMITS.title.max).padEnd(LIMITS.title.min, '.'),
      ...(slug ? { slug } : {}),
      metaTitle: fields.metaTitle?.slice(0, LIMITS.metaTitle) ?? null,
      description: fields.description?.slice(0, LIMITS.description.max) ?? null,
      bodyMd: md,
      coverAlt: fields.coverAlt?.slice(0, LIMITS.coverAlt) ?? null,
      ...(author ? { authorName: author.slice(0, LIMITS.author) } : {}),
      keywords: keywords.map((k) => k.slice(0, LIMITS.keywords.each)).slice(0, LIMITS.keywords.max),
      faqs: faq.faqs.filter((f) => f.q.length >= 5 && f.a.length >= 5),
      cta: cta.cta && cta.cta.heading.length >= 3 && cta.cta.text.length >= 10 ? cta.cta : null,
    });
    const post = await createPost(parsed, actor);
    return { post, importNotes: notes, imported: { faqs: parsed.faqs?.length ?? 0, images: stored.length, cta: !!parsed.cta, seoFields: Object.keys(fields).length } };
  } catch (err) {
    await discardMedia(stored);
    throw err;
  }
}
