import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { existsSync } from 'node:fs';

const ARTIFACTS_ROOT = 'data/flow-artifacts';

export function getArtifactPath(flowRunId: string, stepId: string): string {
  return join(ARTIFACTS_ROOT, flowRunId, `${stepId}.md`);
}

export async function writeFlowArtifact(
  flowRunId: string,
  stepId: string,
  content: string,
): Promise<string> {
  const dir = join(ARTIFACTS_ROOT, flowRunId);
  if (!existsSync(dir)) {
    await mkdir(dir, { recursive: true });
  }
  const path = getArtifactPath(flowRunId, stepId);
  await writeFile(path, content, 'utf8');
  return path;
}
