const fs = require('fs')
const path = require('path')
const os = require('os')

const CONFIG_FILE = path.join(os.homedir(), '.bild.json')
const DEFAULT_CONFIG = require('../config/default.json')

function loadConfig() {
  try {
    if (fs.existsSync(CONFIG_FILE)) {
      const content = fs.readFileSync(CONFIG_FILE, 'utf8')
      return { ...DEFAULT_CONFIG, ...JSON.parse(content) }
    }
  } catch (error) {
    console.warn('Error loading config:', error.message)
  }
  return { ...DEFAULT_CONFIG }
}

function saveConfig(config) {
  try {
    fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8')
    return true
  } catch (error) {
    console.error('Error saving config:', error.message)
    return false
  }
}

function getConfig(key) {
  const config = loadConfig()
  return key ? config[key] : config
}

function setConfig(key, value) {
  const config = loadConfig()
  config[key] = value
  saveConfig(config)
}

/**
 * Normalizes a URL by removing trailing slashes
 * @param {string} url - The URL to normalize
 * @returns {string} The normalized URL without trailing slash
 */
function normalizeUrl(url) {
  if (!url) return url
  return url.replace(/\/+$/, '')
}

module.exports = {
  loadConfig,
  saveConfig,
  getConfig,
  setConfig,
  normalizeUrl,
  CONFIG_FILE,
}

