import { z } from 'zod';

/**
 * The website blog's rules (docs/blog-cms-plan.md), in one place.
 *
 * Every rule is checked here, on the server. The editor's "Ready to publish?"
 * list only mirrors it. A post that is live or scheduled is checked in full on
 * EVERY save, not only when it is published, so it can never be saved into a
 * state that would stop the website build (GymCare's worst bug).
 *
 * The website's content schema (hostelcare-website src/content.config.js)
 * must accept everything that passes here.
 */

export const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

/** Hand-built pages under /resources/blog/ on the website (D2: they stay as they are). */
export const RESERVED_SLUGS = new Set([
  'best-hostel-management-software-india',
  'hostel-management-software-complete-guide',
  'tips-improve-hostel-management-save-time',
  'how-students-find-the-right-hostel-guide',
  'increase-hostel-occupancy-proven-ways',
  'why-cloud-based-hostel-management-is-the-future',
]);

export const LIMITS = {
  title: { min: 3, max: 160 },
  slug: { min: 3, max: 80 },
  metaTitle: 60,
  description: { min: 70, max: 160 },
  body: { min: 200, max: 200_000 },
  sections: 2,
  keywords: { min: 1, max: 20, each: 80 },
  coverAlt: 200,
  author: 80,
  toc: { entries: 30, label: 60 },
  faqs: { max: 15, q: 300, a: 1000 },
  cta: { heading: 120, text: 400 },
} as const;

/** Where the website serves a library image once its build has copied it in. */
export const mediaPath = (id: string) => `/assets/blog/cms/${id}.webp`;
const MEDIA_PATH_RE = /^\/assets\/blog\/cms\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.webp$/;

/** Turn a title into an address: lowercase words joined by hyphens. */
export function slugify(s: string): string {
  return s
    .toLowerCase()
    .normalize('NFKD')
    .replace(/[̀-ͯ]/g, '')
    .replace(/&/g, ' and ')
    .replace(/[^a-z0-9\s-]/g, '')
    .trim()
    .replace(/[\s_]+/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '')
    .slice(0, LIMITS.slug.max)
    .replace(/-$/, '');
}

/** The India date (YYYY-MM-DD) of a moment: what the site shows. */
export function istDate(d: Date): string {
  return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Kolkata', year: 'numeric', month: '2-digit', day: '2-digit' }).format(d);
}

// ── Input shapes (shape and length; the publish rules are below) ────────────

const noControl = (v: string) => !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(v);
const line = (label: string, max: number) =>
  z
    .string()
    .trim()
    .max(max, `${label} must be at most ${max} characters`)
    .refine((v) => noControl(v) && !/[\r\n]/.test(v), `${label} must be a single line`);
const optionalLine = (label: string, max: number) =>
  z.union([line(label, max), z.null()]).transform((v) => (v ? v : null));

export const postFieldsSchema = z
  .object({
    title: line('Title', LIMITS.title.max).pipe(z.string().min(LIMITS.title.min, `Title must be at least ${LIMITS.title.min} characters`)),
    slug: z
      .string()
      .trim()
      .toLowerCase()
      .min(LIMITS.slug.min, `The address must be at least ${LIMITS.slug.min} characters`)
      .max(LIMITS.slug.max, `The address must be at most ${LIMITS.slug.max} characters`)
      .regex(SLUG_RE, 'The address can only have lowercase letters, numbers and single hyphens'),
    metaTitle: optionalLine('Search title', LIMITS.metaTitle),
    description: optionalLine('Search description', LIMITS.description.max),
    bodyMd: z
      .string()
      .max(LIMITS.body.max, `The post must be at most ${LIMITS.body.max.toLocaleString('en-IN')} characters`)
      .refine(noControl, 'The post contains invalid characters')
      .transform((v) => v.replace(/\r\n?/g, '\n')),
    coverMediaId: z.union([z.string().uuid('Choose a cover image from the library'), z.null()]),
    coverAlt: optionalLine('Cover description', LIMITS.coverAlt),
    authorName: line('Author', LIMITS.author).pipe(z.string().min(2, 'Author must be at least 2 characters')),
    keywords: z
      .array(line('Keyword', LIMITS.keywords.each))
      .max(LIMITS.keywords.max, `At most ${LIMITS.keywords.max} keywords`)
      .transform((l) => l.filter((k, i) => k && l.findIndex((x) => x.toLowerCase() === k.toLowerCase()) === i)),
    toc: z
      .record(line('Sidebar label', LIMITS.toc.label))
      .refine((r) => Object.keys(r).length <= LIMITS.toc.entries, `At most ${LIMITS.toc.entries} sidebar labels`)
      .transform((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k.trim(), v]).filter(([k, v]) => k && v))),
    faqs: z
      .array(
        z.object({
          q: line('Question', LIMITS.faqs.q).pipe(z.string().min(5, 'A question must be at least 5 characters')),
          a: z.string().trim().min(5, 'An answer must be at least 5 characters').max(LIMITS.faqs.a, `An answer must be at most ${LIMITS.faqs.a} characters`).refine(noControl, 'The answer contains invalid characters'),
        }),
      )
      .max(LIMITS.faqs.max, `At most ${LIMITS.faqs.max} questions`),
    cta: z.union([
      z.object({
        heading: line('Call to action heading', LIMITS.cta.heading).pipe(z.string().min(3, 'The heading must be at least 3 characters')),
        text: line('Call to action text', LIMITS.cta.text).pipe(z.string().min(10, 'The text must be at least 10 characters')),
      }),
      z.null(),
    ]),
  })
  .partial()
  .strict();

export type PostFields = z.infer<typeof postFieldsSchema>;

// ── The body ────────────────────────────────────────────────────────────────

/** The body without code, where HTML-looking text and links are only text. */
function withoutCode(md: string): string {
  return md.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[ \t]*$/gm, '').replace(/`[^`\n]*`/g, '');
}

/** Library images the body points at, by id. */
export function bodyMediaIds(md: string): string[] {
  const ids = new Set<string>();
  for (const m of withoutCode(md).matchAll(/!\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g)) {
    const hit = MEDIA_PATH_RE.exec(m[1]);
    if (hit) ids.add(hit[1]);
  }
  return [...ids];
}

/** The "## " headings, in order: the page's sections and the sidebar's entries. */
export function sectionHeadings(md: string): string[] {
  return [...withoutCode(md).matchAll(/^##[ \t]+(.+?)[ \t#]*$/gm)].map((m) => m[1].trim());
}

const SAFE_LINK = /^(https:\/\/[^\s]+|mailto:[^\s]+|tel:\+?[0-9][0-9\s-]*|\/(?!\/)[^\s]*|#[^\s]*)$/i;

export interface Problem {
  field: string;
  message: string;
}

/** What in the body would be wrong on the live site. */
export function bodyProblems(md: string, knownMediaIds: Set<string>): Problem[] {
  const out: Problem[] = [];
  const text = withoutCode(md);
  const add = (message: string) => {
    if (!out.some((p) => p.message === message)) out.push({ field: 'bodyMd', message });
  };

  if (md.replace(/\s+/g, ' ').trim().length < LIMITS.body.min) add('The post is too short to publish.');
  if (/^#[ \t]/m.test(text)) add('Use "##" for section headings: the title is already the page heading.');
  if (sectionHeadings(md).length < LIMITS.sections) add(`Give the post at least ${LIMITS.sections} sections ("##" headings).`);

  // No raw HTML on the public site: it would run as the site's own code.
  const noAutolinks = text.replace(/<(https?:\/\/|mailto:)[^>\s]+>/gi, '');
  if (/<\/?[a-z][^>]*>|<!--|<!\[|<\?/i.test(noAutolinks)) add('Remove the HTML from the post: only Markdown is allowed.');
  if (/\bhttp:\/\//i.test(text)) add('Links must start with https://.');

  for (const m of text.matchAll(/(!?)\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g)) {
    const [, bang, url] = m;
    if (bang) {
      const hit = MEDIA_PATH_RE.exec(url);
      if (!hit) add('Insert images from the image library only.');
      else if (!knownMediaIds.has(hit[1])) add('An image in the post is no longer in the image library.');
    } else if (!SAFE_LINK.test(url)) {
      add(`This link can't be used: ${url.slice(0, 80)}. Use https://, mailto:, tel: or a site address starting with "/".`);
    }
  }
  for (const m of text.matchAll(/^[ \t]{0,3}\[[^\]]+\]:[ \t]*<?(\S+?)>?(?:[ \t]+.*)?$/gm)) {
    if (!SAFE_LINK.test(m[1])) add(`This link can't be used: ${m[1].slice(0, 80)}.`);
  }
  return out;
}

export interface PostForRules {
  title: string;
  metaTitle: string | null;
  description: string | null;
  bodyMd: string;
  coverMediaId: string | null;
  coverAlt: string | null;
  keywords: string[];
}

/** Everything between a post and the live site. Empty = ready. */
export function publishProblems(p: PostForRules, knownMediaIds: Set<string>): Problem[] {
  const out: Problem[] = [];
  if (!p.metaTitle) out.push({ field: 'metaTitle', message: `Add a search title (up to ${LIMITS.metaTitle} characters).` });
  if (!p.description || p.description.length < LIMITS.description.min) {
    out.push({ field: 'description', message: `Add a search description of ${LIMITS.description.min}–${LIMITS.description.max} characters.` });
  }
  if (p.keywords.length < LIMITS.keywords.min) out.push({ field: 'keywords', message: 'Add at least one keyword.' });
  if (!p.coverMediaId) out.push({ field: 'coverMediaId', message: 'Add a cover image.' });
  else if (!knownMediaIds.has(p.coverMediaId)) out.push({ field: 'coverMediaId', message: 'The cover image is no longer in the image library.' });
  if (p.coverMediaId && !p.coverAlt) out.push({ field: 'coverAlt', message: 'Describe the cover image (alt text).' });
  out.push(...bodyProblems(p.bodyMd, knownMediaIds));
  return out;
}
