import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { estimateReadingTime } from '@/utils/readingTime';

// Define frontmatter types
export interface StoryFrontmatter {
  title: string;
  excerpt: string;
  createdAt: string;
}

export interface ThoughtFrontmatter {
  title: string;
  excerpt: string;
  createdAt: string;
  category: 'technology' | 'life' | 'creativity';
}

// Generate ID from filename
function generateIdFromFilename(filename: string): string {
  return filename.replace(/\.mdx$/, '').replace(/[^a-zA-Z0-9]/g, '-');
}

// Load all stories
export async function loadStories() {
  const storiesDirectory = path.join(process.cwd(), 'src/content/stories');
  const filenames = fs.readdirSync(storiesDirectory);
  
  const stories = filenames.map((filename) => {
    const filePath = path.join(storiesDirectory, filename);
    const fileContents = fs.readFileSync(filePath, 'utf8');
    const { data, content } = matter(fileContents);
    
    const frontmatter = data as StoryFrontmatter;
    const id = generateIdFromFilename(filename);
    
    return {
      id,
      title: frontmatter.title,
      excerpt: frontmatter.excerpt,
      content,
      createdAt: frontmatter.createdAt,
      readTime: estimateReadingTime(content),
    };
  });
  
  // Sort by creation date (newest first)
  return stories.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
}

// Load all thoughts
export async function loadThoughts() {
  const thoughtsDirectory = path.join(process.cwd(), 'src/content/thoughts');
  const filenames = fs.readdirSync(thoughtsDirectory);
  
  const thoughts = filenames.map((filename) => {
    const filePath = path.join(thoughtsDirectory, filename);
    const fileContents = fs.readFileSync(filePath, 'utf8');
    const { data, content } = matter(fileContents);
    
    const frontmatter = data as ThoughtFrontmatter;
    const id = generateIdFromFilename(filename);
    
    return {
      id,
      title: frontmatter.title,
      excerpt: frontmatter.excerpt,
      content,
      createdAt: frontmatter.createdAt,
      category: frontmatter.category,
      readTime: estimateReadingTime(content),
    };
  });
  
  // Sort by creation date (newest first)
  return thoughts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
}