import { chmod, mkdir, stat } from 'node:fs/promises';
import path from 'node:path';

export const codexContainerWorkspace = '/workspace';
export const codexContainerRepo = '/workspace/repo';

export const prepareCodexWorkspaceFiles = async (args: {
  workdir: string;
  repoDir: string;
}) => {
  await mkdir(path.join(args.workdir, '.codex'), { recursive: true });
  await mkdir(path.join(args.workdir, '.config'), { recursive: true });
  await mkdir(path.join(args.workdir, '.local', 'share'), { recursive: true });

  await Promise.all([
    chmod(args.workdir, 0o755),
    chmod(args.repoDir, 0o755),
    chmod(path.join(args.workdir, '.codex'), 0o755),
    chmod(path.join(args.workdir, '.config'), 0o755),
    chmod(path.join(args.workdir, '.local'), 0o755),
    chmod(path.join(args.workdir, '.local', 'share'), 0o755),
  ]);

  const projectCodexDir = path.join(args.repoDir, '.codex');
  const projectConfig = path.join(projectCodexDir, 'config.toml');
  try {
    if ((await stat(projectCodexDir)).isDirectory()) {
      await chmod(projectCodexDir, 0o755);
    }
    if ((await stat(projectConfig)).isFile()) {
      await chmod(projectConfig, 0o644);
    }
  } catch (error) {
    const code = error && typeof error === 'object' ? 'code' in error : false;
    if (!code || (error as { code?: string }).code !== 'ENOENT') {
      throw error;
    }
  }
};
