import { createHash } from 'node:crypto';
import { readFile, readdir, stat } from 'node:fs/promises';
import path from 'node:path';

export const repositoryRoot = path.resolve(import.meta.dirname, '..');

export async function sha256(filePath) {
  const contents = await readFile(filePath);
  return createHash('sha256').update(contents).digest('hex');
}

export async function walk(directory, predicate = () => true) {
  const output = [];
  for (const entry of await readdir(directory)) {
    const fullPath = path.join(directory, entry);
    const details = await stat(fullPath);
    if (details.isDirectory()) output.push(...(await walk(fullPath, predicate)));
    else if (predicate(fullPath)) output.push(fullPath);
  }
  return output;
}

export function flatten(value, prefix = '', output = new Map()) {
  if (Array.isArray(value)) {
    value.forEach((entry, index) => flatten(entry, `${prefix}[${index}]`, output));
    if (value.length === 0) output.set(prefix, value);
    return output;
  }
  if (value && typeof value === 'object') {
    for (const [key, entry] of Object.entries(value)) {
      flatten(entry, prefix ? `${prefix}.${key}` : key, output);
    }
    return output;
  }
  output.set(prefix, value);
  return output;
}

export function fail(messages) {
  for (const message of messages) console.error(`ERROR: ${message}`);
  process.exitCode = 1;
}

export function pass(message) {
  console.log(`PASS: ${message}`);
}
