export const dynamic = "force-dynamic";

import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { marked } from 'marked';
import createDOMPurify from 'isomorphic-dompurify';
import hljs from 'highlight.js';
import { getPostsDirectory } from '@/lib/postsDirectory';

const postsDirectory = getPostsDirectory();

// Function to get file creation date
function getFileCreationDate(filePath: string): Date {
  const stats = fs.statSync(filePath);
  return stats.birthtime ?? stats.mtime;
}

// Function to generate ID from text (matches frontend logic)
function generateId(text: string): string {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

const renderer = new marked.Renderer();

// Custom heading renderer to add IDs
renderer.heading = (text, level) => {
  const id = generateId(text);
  return `<h${level} id="${id}">${text}</h${level}>`;
};

renderer.code = (code, infostring, escaped) => {
  const lang = (infostring || '').match(/\S*/)?.[0];
  const highlighted = lang && hljs.getLanguage(lang)
    ? hljs.highlight(code, { language: lang }).value
    : hljs.highlightAuto(code).value;
  const langClass = lang ? `language-${lang}` : '';
  return `<pre><code class="hljs ${langClass}">${highlighted}</code></pre>`;
};

marked.setOptions({
  gfm: true,
  breaks: true,
  renderer,
});

// Replace top-level pinnedData logic with a function
function getPinnedData() {
  const pinnedPath = path.join(process.cwd(), 'posts', 'pinned.json');
  let pinnedData = { pinned: [], folderEmojis: {} };
  if (fs.existsSync(pinnedPath)) {
    try {
      const raw = fs.readFileSync(pinnedPath, 'utf8');
      pinnedData = JSON.parse(raw);
      if (!pinnedData.pinned) pinnedData.pinned = [];
      if (!pinnedData.folderEmojis) pinnedData.folderEmojis = {};
    } catch {
      pinnedData = { pinned: [], folderEmojis: {} };
    }
  }
  return pinnedData;
}

// Update readPostsDir to accept pinnedData as an argument
async function readPostsDir(dir: string, relDir = '', pinnedData: { pinned: string[]; folderEmojis: Record<string, string> }): Promise<any[]> {
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  const folders: any[] = [];
  const posts: any[] = [];

  for (const entry of entries) {
    // Skip the 'assets' folder
    if (entry.isDirectory() && entry.name === 'assets' && relDir === '') {
      continue;
    }
    const fullPath = path.join(dir, entry.name);
    const relPath = relDir ? path.join(relDir, entry.name) : entry.name;

    if (entry.isDirectory()) {
      const children = await readPostsDir(fullPath, relPath, pinnedData);
      // Debug log for emoji lookup
      console.log('[FOLDER EMOJI DEBUG]', { relPath, allEmojis: pinnedData.folderEmojis, emoji: pinnedData.folderEmojis[relPath] });
      const emoji = pinnedData.folderEmojis[relPath] || '📁';
      folders.push({ type: 'folder', name: entry.name, path: relPath, emoji, children });
    } else if (entry.isFile() && entry.name.endsWith('.md')) {
      posts.push(await getPostByPath(fullPath, relPath, pinnedData));
    }
  }

  // Sort posts by creation date (newest first)
  posts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

  // Folders first, then posts
  return [...folders, ...posts];
}

// Update getPostByPath to accept pinnedData
async function getPostByPath(filePath: string, relPath: string, pinnedData: { pinned: string[]; folderEmojis: Record<string, string> }) {
  const fileContents = fs.readFileSync(filePath, 'utf8');
  const { data, content } = matter(fileContents);
  const createdAt = getFileCreationDate(filePath);

  let processedContent = '';
  try {
    const rawHtml = marked.parse(content) as string;
    processedContent = createDOMPurify.sanitize(rawHtml, {
      ALLOWED_TAGS: [
        'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'p', 'a', 'ul', 'ol', 'li', 'blockquote',
        'pre', 'code', 'em', 'strong', 'del',
        'hr', 'br', 'img', 'table', 'thead', 'tbody',
        'tr', 'th', 'td', 'div', 'span', 'iframe'
      ],
      ALLOWED_ATTR: [
        'class', 'id', 'style',
        'href', 'target', 'rel',
        'src', 'alt', 'title', 'width', 'height',
        'frameborder', 'allowfullscreen'
      ],
      ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+\.\-]+(?:[^a-z+\.\-:]|$))/i
    });
  } catch (err) {
    console.error(`Error processing markdown for ${relPath}:`, err);
    processedContent = `<div class="error-message">
      <p>Error processing markdown content. Please check the console for details.</p>
      <pre>${err instanceof Error ? err.message : 'Unknown error'}</pre>
    </div>`;
  }

  return {
    type: 'post',
    slug: relPath.replace(/\.md$/, ''),
    title: data.title,
    date: data.date,
    tags: data.tags || [],
    summary: data.summary,
    content: processedContent,
    createdAt: createdAt.toISOString(),
    pinned: pinnedData.pinned.includes(relPath.replace(/\.md$/, '')),
  };
}

// Update GET handler to use fresh pinnedData
export async function GET() {
  try {
    const pinnedData = getPinnedData();
    const tree = await readPostsDir(postsDirectory, '', pinnedData);
    return NextResponse.json(tree);
  } catch (error) {
    console.error('Error loading posts:', error);
    return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 });
  }
}
 