const fs = require('node:fs');
const path = require('node:path');
const { buildConfigTemplate } = require('./config-template');

function upsertKey(content, key, value) {
  const pattern = new RegExp(`^${key}\\s*=\\s*".*"$`, 'm');
  const replacement = `${key} = "${value}"`;
  return pattern.test(content)
    ? content.replace(pattern, replacement)
    : `${content.trimEnd()}\n${replacement}\n`;
}

async function writeUserConfig({ targetRoot, answers }) {
  const configDir = path.join(targetRoot, '_rtexit');
  const configPath = path.join(configDir, 'config.user.toml');

  fs.mkdirSync(configDir, { recursive: true });

  if (!fs.existsSync(configPath)) {
    fs.writeFileSync(
      configPath,
      `${buildConfigTemplate({
        language: answers.language,
        document_output_language: answers.document_output_language,
        skill_level: '',
      })}\n`,
    );
    return configPath;
  }

  let content = fs.readFileSync(configPath, 'utf8');
  content = upsertKey(content, 'language', answers.language);
  content = upsertKey(content, 'document_output_language', answers.document_output_language);
  fs.writeFileSync(configPath, content);
  return configPath;
}

module.exports = { writeUserConfig };
