"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SettingsManager = void 0;
const keyv_1 = __importDefault(require("keyv"));
const sqlite_1 = __importDefault(require("@keyv/sqlite"));
const path = __importStar(require("path"));
const tsyringe_1 = require("tsyringe");
const ipc_1 = require("../ipc");
const SettingsHandler_1 = require("./SettingsHandler");
const EdenSettings_1 = require("./EdenSettings");
/**
 * SettingsManager - Manages persistent settings storage for Eden and apps
 *
 * Provides namespace-isolated settings storage using SQLite backend via Keyv.
 * Settings are stored separately from app data in settings.db.
 * Key format: {appId}:{key}
 *
 * Eden system settings use appId "com.eden" which is reserved.
 */
let SettingsManager = class SettingsManager extends ipc_1.EdenEmitter {
    keyv;
    handler;
    constructor(ipcBridge, commandRegistry, appsDirectory) {
        super(ipcBridge);
        // Initialize Keyv with SQLite backend - separate from app storage
        const dbPath = path.join(appsDirectory, "settings.db");
        const sqlite = new sqlite_1.default(`sqlite://${dbPath}`);
        this.keyv = new keyv_1.default({ store: sqlite });
        // Handle errors
        this.keyv.on("error", (err) => {
            console.error("[SettingsManager] Database error:", err);
        });
        console.log(`[SettingsManager] Initialized settings storage at ${dbPath}`);
        // Create and register handler
        this.handler = new SettingsHandler_1.SettingsHandler(this);
        commandRegistry.registerManager(this.handler);
    }
    // ===================================================================
    // App Settings Methods
    // ===================================================================
    /**
     * Get the namespaced key for an app setting
     */
    getAppKey(appId, key) {
        return `${appId}:${key}`;
    }
    /**
     * Get a setting value for an app
     */
    async get(appId, key) {
        const namespacedKey = this.getAppKey(appId, key);
        const value = await this.keyv.get(namespacedKey);
        // If no value found and this is com.eden, check for default
        if (value === undefined && appId === SettingsHandler_1.EDEN_SETTINGS_APP_ID) {
            return this.getEdenDefault(key);
        }
        if (value !== undefined && typeof value !== "string") {
            console.warn(`[SettingsManager] Non-string value found for key ${key}, converting to string`);
            return String(value);
        }
        return value;
    }
    /**
     * Set a setting value for an app
     */
    async set(appId, key, value) {
        if (typeof value !== "string") {
            throw new Error(`[SettingsManager] Value must be a string, got ${typeof value}`);
        }
        const namespacedKey = this.getAppKey(appId, key);
        await this.keyv.set(namespacedKey, value);
        // Notify subscribers of the change
        this.notify("changed", { appId, key, value });
    }
    /**
     * List all setting keys for an app
     */
    async list(appId) {
        const prefix = `${appId}:`;
        const allKeys = [];
        try {
            if (this.keyv.iterator) {
                const iterator = this.keyv.iterator(undefined);
                for await (const [key] of iterator) {
                    if (typeof key === "string" && key.startsWith(prefix)) {
                        allKeys.push(key.substring(prefix.length));
                    }
                }
            }
        }
        catch (error) {
            console.warn("[SettingsManager] Iterator not supported or failed:", error);
        }
        return allKeys;
    }
    /**
     * Get all settings with values for an app
     */
    async getAll(appId) {
        // For com.eden, return all settings with defaults
        if (appId === SettingsHandler_1.EDEN_SETTINGS_APP_ID) {
            return this.getAllEdenSettings();
        }
        const keys = await this.list(appId);
        const result = {};
        for (const key of keys) {
            const value = await this.get(appId, key);
            if (value !== undefined) {
                result[key] = value;
            }
        }
        return result;
    }
    /**
     * Reset a setting to its default value
     */
    async reset(appId, key, schema) {
        // Find default value from schema
        let defaultValue;
        // For com.eden, use built-in schema
        const schemaToUse = appId === SettingsHandler_1.EDEN_SETTINGS_APP_ID ? EdenSettings_1.EDEN_SETTINGS_SCHEMA : schema;
        if (schemaToUse) {
            for (const category of schemaToUse) {
                const setting = category.settings.find((s) => s.key === key);
                if (setting) {
                    defaultValue = setting.defaultValue;
                    break;
                }
            }
        }
        if (defaultValue === undefined) {
            throw new Error(`[SettingsManager] Cannot reset key "${key}": no default value found in schema`);
        }
        await this.set(appId, key, defaultValue);
    }
    // ===================================================================
    // Eden System Settings Helpers
    // ===================================================================
    /**
     * Get Eden settings schema
     */
    getEdenSchema() {
        return EdenSettings_1.EDEN_SETTINGS_SCHEMA;
    }
    /**
     * Get the default value for an Eden setting key
     */
    getEdenDefault(key) {
        for (const category of EdenSettings_1.EDEN_SETTINGS_SCHEMA) {
            const setting = category.settings.find((s) => s.key === key);
            if (setting) {
                return setting.defaultValue;
            }
        }
        return undefined;
    }
    /**
     * Get all Eden settings with values (including defaults)
     */
    async getAllEdenSettings() {
        const result = {};
        for (const category of EdenSettings_1.EDEN_SETTINGS_SCHEMA) {
            for (const setting of category.settings) {
                const value = await this.get(SettingsHandler_1.EDEN_SETTINGS_APP_ID, setting.key);
                if (value !== undefined) {
                    result[setting.key] = value;
                }
            }
        }
        return result;
    }
};
exports.SettingsManager = SettingsManager;
exports.SettingsManager = SettingsManager = __decorate([
    (0, tsyringe_1.singleton)(),
    (0, ipc_1.EdenNamespace)("settings"),
    __param(0, (0, tsyringe_1.inject)(ipc_1.IPCBridge)),
    __param(1, (0, tsyringe_1.inject)(ipc_1.CommandRegistry)),
    __param(2, (0, tsyringe_1.inject)("appsDirectory")),
    __metadata("design:paramtypes", [ipc_1.IPCBridge,
        ipc_1.CommandRegistry, String])
], SettingsManager);
//# sourceMappingURL=SettingsManager.js.map