import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';

export const repoRoot = process.cwd();
export const goldenDatasetDir = path.join(repoRoot, 'setup', 'golden-dataset');
export const templatesDir = path.join(repoRoot, 'setup', 'templates');

export interface CsvFile {
  header: string[];
  rows: string[][];
}

export function readJson<T>(relativePath: string): T {
  return JSON.parse(readFileSync(path.join(repoRoot, relativePath), 'utf8')) as T;
}

export function readText(relativePath: string) {
  return readFileSync(path.join(repoRoot, relativePath), 'utf8');
}

export function assertFileExists(relativePath: string) {
  assert.equal(existsSync(path.join(repoRoot, relativePath)), true, `${relativePath} should exist`);
}

export function parseCsv(relativePath: string): CsvFile {
  const content = readText(relativePath).trim();
  const [headerLine = '', ...rowLines] = content.split(/\r?\n/);
  return {
    header: headerLine.split(','),
    rows: rowLines.filter(Boolean).map((line) => line.split(','))
  };
}

export function countRows(relativePath: string) {
  return parseCsv(relativePath).rows.length;
}

export function sha256(content: string) {
  return `sha256:${createHash('sha256').update(content).digest('hex')}`;
}

export function assertHeadersMatchTemplate(fileName: string) {
  const template = parseCsv(`setup/templates/${fileName}`);
  const golden = parseCsv(`setup/golden-dataset/${fileName}`);
  assert.deepEqual(golden.header, template.header, `${fileName} header should match setup template`);
}
