import { readFile, writeFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { getTopicDir, type MemoryTopic } from "./paths.js";

export async function readTopicFiles(root: string, topic: MemoryTopic): Promise<Map<string, string>> {
  const dir = getTopicDir(root, topic);
  const files = new Map<string, string>();
  try {
    const entries = await readdir(dir, { withFileTypes: true });
    for (const entry of entries) {
      if (entry.isFile() && entry.name.endsWith('.md')) {
        const content = await readFile(join(dir, entry.name), 'utf8');
        files.set(entry.name, content);
      }
    }
  } catch {
    // Directory doesn't exist yet
  }
  return files;
}

export async function writeEntry(
  root: string,
  topic: MemoryTopic,
  title: string,
  content: string,
  tags: string[],
): Promise<void> {
  const dir = getTopicDir(root, topic);
  const tagLine = tags.length > 0 ? `> tags: ${tags.join(', ')}\n\n` : '\n';
  const entry = `## ${topic}: ${title}\n${tagLine}${content}\n`;
  const filename = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') + '.md';
  await writeFile(join(dir, filename), entry, 'utf8');
}
