const path = require('node:path');
const os = require('node:os');
const { ensureDirSync, existsSync, readJsonSync, writeJsonSync } = require('fs-extra');

const LICENSE_PATTERN = /^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;
const CONFIG_DIR = path.join(os.homedir(), '.kasy');
const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');

function isLicenseFormatValid(licenseKey) {
  return LICENSE_PATTERN.test((licenseKey || '').trim().toUpperCase());
}

function readLocalConfig() {
  if (!existsSync(CONFIG_PATH)) {
    return {};
  }

  try {
    return readJsonSync(CONFIG_PATH);
  } catch {
    return {};
  }
}

function writeLocalConfig(config) {
  ensureDirSync(CONFIG_DIR);
  writeJsonSync(CONFIG_PATH, config, { spaces: 2 });
}

function getStoredLicenseKey() {
  const config = readLocalConfig();
  return config.licenseKey || '';
}

function setStoredLicenseKey(licenseKey) {
  const config = readLocalConfig();
  writeLocalConfig({
    ...config,
    licenseKey
  });
}

function getStoredLanguage() {
  const config = readLocalConfig();
  const lang = config.language || '';
  return /^(en|pt|es)$/i.test(lang) ? lang.toLowerCase() : '';
}

function setStoredLanguage(language) {
  const config = readLocalConfig();
  writeLocalConfig({
    ...config,
    language: String(language).toLowerCase()
  });
}

module.exports = {
  CONFIG_PATH,
  isLicenseFormatValid,
  readLocalConfig,
  writeLocalConfig,
  getStoredLicenseKey,
  setStoredLicenseKey,
  getStoredLanguage,
  setStoredLanguage,
};
