import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';

// Truth-Everywhere Part 2 (item 8): the blog reads the REAL committed articles
// in content/articles (5 genuine pieces with honest dates), NOT the untracked
// content/blog that held the backdated 2026-03-22 orphan. Drafts are skipped so
// unfinished pieces never leak to the public index.
const BLOG_DIR = path.join(process.cwd(), 'content', 'articles');

export interface BlogPost {
  slug: string;
  title: string;
  date: string;
  description: string;
  tags: string[];
  content: string;
  readingTime: number;
}

export function getAllPosts(): BlogPost[] {
  if (!fs.existsSync(BLOG_DIR)) return [];

  const files = fs.readdirSync(BLOG_DIR).filter((f) => f.endsWith('.mdx') || f.endsWith('.md'));

  const posts = files
    .map((file) => {
      const raw = fs.readFileSync(path.join(BLOG_DIR, file), 'utf-8');
      const { data, content } = matter(raw);
      const slug = data.slug || file.replace(/\.mdx?$/, '');
      const wordCount = content.split(/\s+/).length;
      const readingTime = Math.max(1, Math.ceil(wordCount / 200));

      return {
        slug,
        title: data.title || slug,
        date: data.date || '',
        // articles carry `excerpt`; older posts used `description` — accept either
        description: data.description || data.excerpt || '',
        tags: data.tags || [],
        content,
        readingTime,
        status: data.status || 'published',
      };
    })
    // Only published pieces reach the public index — drafts never leak.
    .filter((p) => p.status !== 'draft');

  return posts
    .map(({ status, ...p }) => p)
    .sort((a, b) => (a.date > b.date ? -1 : 1));
}

export function getPostBySlug(slug: string): BlogPost | null {
  const posts = getAllPosts();
  return posts.find((p) => p.slug === slug) || null;
}

/**
 * Minimal, dependency-free markdown → HTML for our OWN committed articles
 * (headers, bold, italic, paragraphs). Content is trusted (files we author),
 * and we HTML-escape before transforming, so it's XSS-safe. The richer media
 * train (images/charts) is separate — this just stops "## Header" rendering as
 * literal hashes on the public blog.
 */
export function renderMarkdown(md: string): string {
  const esc = (s: string) => s
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  const inline = (s: string) => esc(s)
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/(^|[^*])\*([^*]+)\*(?!\*)/g, '$1<em>$2</em>');
  return md
    .trim()
    .split(/\n{2,}/)
    .map((block) => {
      const b = block.trim();
      if (b.startsWith('### ')) return `<h3>${inline(b.slice(4))}</h3>`;
      if (b.startsWith('## ')) return `<h2>${inline(b.slice(3))}</h2>`;
      if (b.startsWith('# ')) return `<h1>${inline(b.slice(2))}</h1>`;
      return `<p>${inline(b).replace(/\n/g, '<br/>')}</p>`;
    })
    .join('\n');
}
