#!/usr/bin/env node

const fs = require('node:fs');
const path = require('node:path');

function main(argv) {
  const args = parseArgs(argv);
  const projectRoot = process.cwd();

  assertProjectNotInitialized(projectRoot);
  createBaseStructure(projectRoot);
  writeStarterFiles(projectRoot);

  if (args.includeSamples) {
    writeSampleFiles(projectRoot);
  }

  console.log(`Initialized BDD UI consumer resources in ${projectRoot}`);
  if (args.includeSamples) {
    console.log('Included sample feature and input files.');
  }
}

function parseArgs(argv) {
  return {
    includeSamples: argv.includes('--include-samples')
  };
}

function assertProjectNotInitialized(projectRoot) {
  const conflictingPaths = [
    'resources',
    'cucumber.js',
    path.join('resources', '4-config', 'bdd-ui.config.json')
  ]
    .map((relativePath) => path.join(projectRoot, relativePath))
    .filter((targetPath) => fs.existsSync(targetPath));

  if (conflictingPaths.length > 0) {
    throw new Error(
      `Project at ${projectRoot} already appears to be initialized. Existing paths: ${conflictingPaths.join(', ')}`
    );
  }
}

function createBaseStructure(projectRoot) {
  const directories = [
    'resources',
    path.join('resources', '1-payload'),
    path.join('resources', '2-actual'),
    path.join('resources', '3-expected'),
    path.join('resources', '4-config'),
    path.join('resources', '5-input'),
    path.join('resources', 'features'),
    'support'
  ];

  for (const relativePath of directories) {
    fs.mkdirSync(path.join(projectRoot, relativePath), { recursive: true });
  }
}

function writeStarterFiles(projectRoot) {
  copyTemplateFile('templates/cucumber.js', path.join(projectRoot, 'cucumber.js'));
  copyTemplateFile(
    'templates/bdd-ui.config.json',
    path.join(projectRoot, 'resources', '4-config', 'bdd-ui.config.json')
  );
}

function writeSampleFiles(projectRoot) {
  writeFile(
    path.join(projectRoot, 'resources', 'features', 'login.feature'),
    [
      'Feature: Login',
      '',
      '  Scenario: User logs in with valid credentials',
      '    Given I log in as "standardUser"',
      '    Then the current URL should contain "/home"',
      ''
    ].join('\n')
  );

  fs.mkdirSync(path.join(projectRoot, 'resources', '5-input', 'login'), { recursive: true });
  writeFile(
    path.join(projectRoot, 'resources', '5-input', 'login', 'example-login.json'),
    `${JSON.stringify({ Username: 'standardUser.username', Password: 'standardUser.password' }, null, 2)}\n`
  );
}

function copyTemplateFile(fromRelativePath, toAbsolutePath) {
  const sourcePath = path.resolve(__dirname, '..', fromRelativePath);
  const content = fs.readFileSync(sourcePath, 'utf8');
  writeFile(toAbsolutePath, content.endsWith('\n') ? content : `${content}\n`);
}

function writeFile(filePath, content) {
  fs.writeFileSync(filePath, content, 'utf8');
}

try {
  main(process.argv.slice(2));
} catch (error) {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
}
