'use strict';

const { existsSync, mkdirSync, writeFileSync } = require('fs');
const { join } = require('path');

const projectRoot = process.env.INIT_CWD;

if (!projectRoot) process.exit(0);
if (process.env.CI === 'true' || process.env.CI === '1') process.exit(0);
if (projectRoot.includes('node_modules')) process.exit(0);

const configDir = join(projectRoot, '.testrelic');
const configFile = join(configDir, 'testrelic-config.json');

if (existsSync(configFile)) process.exit(0);

const template = {
  cloud: {
    apiKey: '$TESTRELIC_API_KEY',
    endpoint: 'https://platform.testrelic.ai/api/v1',
    upload: 'both',
  },
  'testrelic-repo': {
    name: 'my-project',
  },
};

try {
  mkdirSync(configDir, { recursive: true });
  writeFileSync(configFile, JSON.stringify(template, null, 2) + '\n', 'utf-8');
  process.stdout.write(
    '[testrelic] Created .testrelic/testrelic-config.json — update "testrelic-repo.name" and set TESTRELIC_API_KEY.\n',
  );
} catch (err) {
  process.stderr.write('[testrelic] Could not create .testrelic/testrelic-config.json: ' + err.message + '\n');
}
