const fs = require('fs');
const path = require('path');

const knowledgeDir = path.join(__dirname, '..', 'knowledge');
let cachedKnowledge = [];

/**
 * Load markdown files from the knowledge directory into memory.
 * @returns {Array<{name: string, content: string}>}
 */
function loadKnowledgeBase() {
  cachedKnowledge = [];

  if (!fs.existsSync(knowledgeDir)) {
    return cachedKnowledge;
  }

  const files = fs.readdirSync(knowledgeDir);

  cachedKnowledge = files
    .filter((file) => typeof file === 'string' && file.toLowerCase().endsWith('.md'))
    .map((file) => {
      const filePath = path.join(knowledgeDir, file);
      let content = '';

      try {
        content = fs.readFileSync(filePath, 'utf8');
      } catch (error) {
        // If a file cannot be read, ignore it and continue loading other files.
        content = '';
      }

      return {
        name: file,
        content
      };
    })
    .filter((entry) => entry.content.length > 0);

  return cachedKnowledge;
}

/**
 * Force a reload of the knowledge base from disk.
 * @returns {Array<{name: string, content: string}>}
 */
function reloadKnowledgeBase() {
  return loadKnowledgeBase();
}

/**
 * Get the current in-memory knowledge base.
 * If the cache is empty, it loads the knowledge base first.
 * @returns {Array<{name: string, content: string}>}
 */
function getKnowledgeBase() {
  if (!cachedKnowledge || cachedKnowledge.length === 0) {
    loadKnowledgeBase();
  }
  return cachedKnowledge;
}

module.exports = {
  loadKnowledgeBase,
  reloadKnowledgeBase,
  getKnowledgeBase
};
