import fs from 'fs';
import { readFile } from 'fs/promises';
import path from 'path';

export async function getReadme() {
  const readmePath = getReadmePath();
  if (!readmePath) {
    return '';
  }

  return await readFile(readmePath, 'utf8');
}

function getReadmePath(): string | undefined {
  if (process.env.README_PATH) {
    return process.env.README_PATH;
  }

  const cwd = process.env.CWD ? path.resolve(process.env.CWD) : process.cwd();
  const root = path.join(cwd, 'README.md');
  const parent = path.join(cwd, '..', 'README.md');

  if (fs.existsSync(root)) {
    return root;
  }

  if (fs.existsSync(parent)) {
    return parent;
  }

  console.warn(
    `[@5minds/processcube_docflow:getReadmePath]\t\tCould not find README.md file in ${cwd} or its parent directory.`,
  );
}
