// src/lib/mdx-utils.ts
import fs from "fs";
import path from "path";
import matter from "gray-matter";

// Set path to MDX files
const pagesDirectory = path.join(process.cwd(), "public", "pages");

// Ensure pages directory exists
function ensurePagesDirectoryExists() {
  try {
    if (!fs.existsSync(pagesDirectory)) {
      fs.mkdirSync(pagesDirectory, { recursive: true });
      console.log(`Created directory: ${pagesDirectory}`);
    }
  } catch (error) {
    console.error(`Error creating directory ${pagesDirectory}:`, error);
  }
}

// Get the list of all MDX files in the pages directory
export function getMdxFiles() {
  try {
    ensurePagesDirectoryExists();
    const fileNames = fs.readdirSync(pagesDirectory);
    return fileNames.filter((fileName) => {
      return fileName.endsWith(".mdx");
    });
  } catch (error) {
    console.error("Error reading MDX files:", error);
    return [];
  }
}

// Get all page data (metadata and content)
export function getAllPagesData() {
  try {
    const mdxFiles = getMdxFiles();

    const pagesData = mdxFiles.map((fileName) => {
      // Remove ".mdx" from file name to get slug
      const slug = fileName.replace(/\.mdx$/, "");

      // Read MDX file as string
      const fullPath = path.join(pagesDirectory, fileName);
      const fileContents = fs.readFileSync(fullPath, "utf8");

      // Use gray-matter to parse the page metadata
      const { data, content } = matter(fileContents);

      return {
        slug,
        content,
        title: data.title || slug,
        description: data.description || "",
        date: data.date || new Date(),
      };
    });

    // Sort pages by date if available
    return pagesData.sort((a, b) => {
      if (a.date && b.date) {
        return new Date(b.date).getTime() - new Date(a.date).getTime();
      }
      return 0;
    });
  } catch (error) {
    console.error("Error getting all pages data:", error);
    return [];
  }
}

// Get a specific page by its slug
export function getPageBySlug(slug: string) {
  try {
    ensurePagesDirectoryExists();

    // Check if file exists
    const fullPath = path.join(pagesDirectory, `${slug}.mdx`);
    if (!fs.existsSync(fullPath)) {
      return null;
    }

    // Read the file content
    const fileContents = fs.readFileSync(fullPath, "utf8");

    // Use gray-matter to parse the page metadata and content
    const { data, content: rawContent } = matter(fileContents);

    // Process the content to ensure it's valid MDX
    // Remove any potential null characters that could cause rendering issues
    const cleanContent =
      rawContent
        .replace(/\0/g, "")
        // Normalize line endings
        .replace(/\r\n/g, "\n")
        // Remove any BOM
        .replace(/^\uFEFF/, "")
        // Ensure content ends with newline
        .trim() + "\n";

    return {
      slug,
      content: cleanContent,
      title: data.title || slug,
      description: data.description || "",
      date: data.date ? new Date(data.date) : new Date(),
    };
  } catch (error) {
    console.error(`Error loading page for slug "${slug}":`, error);
    return null;
  }
}

// Utility function to write MDX content to a file
export function writeMdxFile(slug: string, content: string) {
  try {
    ensurePagesDirectoryExists();

    const fullPath = path.join(pagesDirectory, `${slug}.mdx`);
    fs.writeFileSync(fullPath, content, "utf8");
    return true;
  } catch (error) {
    console.error(`Error writing MDX file for slug "${slug}":`, error);
    return false;
  }
}
