import fs from 'fs';
import path from 'path';
import os from 'os';
import yaml from 'js-yaml';

const BASE_DIR = path.join(os.homedir(), 'WaifuBoards');
const CONFIG_PATH = path.join(BASE_DIR, 'config.yaml');

const DEFAULT_CONFIG = {
    library: {
        anime: null,
        manga: null,
        novels: null
    }
};

function ensureConfigFile() {
    if (!fs.existsSync(BASE_DIR)) {
        fs.mkdirSync(BASE_DIR, { recursive: true });
    }

    if (!fs.existsSync(CONFIG_PATH)) {
        fs.writeFileSync(
            CONFIG_PATH,
            yaml.dump(DEFAULT_CONFIG),
            'utf8'
        );
    }
}

export function getConfig() {
    ensureConfigFile();
    const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
    return yaml.load(raw) || DEFAULT_CONFIG;
}

export function setConfig(partialConfig) {
    ensureConfigFile();

    const current = getConfig();
    const next = deepMerge(current, partialConfig);

    fs.writeFileSync(
        CONFIG_PATH,
        yaml.dump(next),
        'utf8'
    );

    return next;
}

function deepMerge(target, source) {
    for (const key in source) {
        if (
            source[key] &&
            typeof source[key] === 'object' &&
            !Array.isArray(source[key])
        ) {
            target[key] = deepMerge(target[key] || {}, source[key]);
        } else {
            target[key] = source[key];
        }
    }
    return target;
}

module.exports = {
    ensureConfigFile,
    getConfig,
    setConfig,
};