const fs = require('fs');
const path = require('path');
const os = require('os');
const EventEmitter = require('events');

class ConfigManager extends EventEmitter {
    constructor() {
        super();
        this.configDir = path.join(os.homedir(), '.ollie-hub');
        this.configFile = path.join(this.configDir, 'state.json');
        this.APP_CODE = 'ollie-hub';

        this.ensureDir();
        this.config = this.loadConfig().state;
    }

    ensureDir() {
        if (!fs.existsSync(this.configDir)) {
            fs.mkdirSync(this.configDir, { recursive: true });
        }
    }

    getDefaultPort() {
        return 19099;
    }

    getPort() {
        return this.config.port || this.getDefaultPort();
    }

    loadConfig() {
        let state = {};

        if (fs.existsSync(this.configFile)) {
            try {
                state = JSON.parse(fs.readFileSync(this.configFile, 'utf8'));
            } catch (e) {
                console.error('Failed to load state file:', e);
            }
        }

        if (!state.port) {
            state.port = this.getDefaultPort();
            this.saveConfig(state);
        }

        return { state };
    }

    save() {
        try {
            fs.writeFileSync(this.configFile, JSON.stringify(this.config, null, 2), 'utf8');
            this.emit('configChanged', this.config);
        } catch (e) {
            console.error('Failed to save state file:', e);
        }
    }

    saveConfig(newConfig) {
        if (!newConfig || typeof newConfig !== 'object') return;
        this.config = { ...this.config, ...newConfig };
        this.save();
    }

    isActivated() {
        if (!this.config) return false;
        const v1 = this.config['hub-license-verified'] === true || this.config['hub-license-verified'] === 'true';
        const v2 = this.config['hub-verification'] && (this.config['hub-verification'].key || this.config['hub-verification'].licenseKey);
        return v1 || !!v2;
    }

    getConfig() {
        return this.config;
    }
}

const configManager = new ConfigManager();
module.exports = configManager;
