const KASKO_CONFIG_REGEX = /window\.kaskoConfig = {([^}]+)/;
const KASKO_CONFIG_SEPARATOR_REGEX = /,/g;

/**
 * @param {string} html
 * @returns {Promise<Record<string, any>>}
 */
async function getWebappConfig(html) {
  const [, configText] = html.match(KASKO_CONFIG_REGEX) || [];

  if (!configText?.trim()) {
    throw new Error('Webapp config could not be loaded');
  }

  const config = configText.split(KASKO_CONFIG_SEPARATOR_REGEX).reduce((acc, chunk) => {
    const [key, ...value] = chunk.split(':');
    const trimmedKey = key.trim();

    if (!trimmedKey) {
      return acc;
    }

    const normalizedValue = value
      .join(':')
      .trim()
      .replace(/^[']|[']$/g, '"')
      .replace(/^kqsLang$/g, '"en"');

    acc[trimmedKey] = JSON.parse(normalizedValue);

    return acc;
  }, {});

  return config;
}

module.exports = getWebappConfig;
