/**
 * Settings Handler
 *
 * Handles user settings for web clients.
 */
import * as fs from 'fs';
import * as path from 'path';
import { homedir } from 'os';
// Settings directory
const SETTINGS_DIR = path.join(homedir(), '.hstudio');
const SETTINGS_FILE = path.join(SETTINGS_DIR, 'settings.json');
// Default settings
const DEFAULT_SETTINGS = {
    version: 1,
    view: {
        sidebarVisible: true,
        sidebarWidth: 250,
        sidebarActiveView: 'explorer',
        terminalVisible: false,
        terminalHeight: 200,
        aiPanelVisible: true,
        aiPanelWidth: 350,
        viewMode: 'ide',
    },
    editor: {
        fontSize: 14,
        fontFamily: '"Fira Code", "JetBrains Mono", "Consolas", monospace',
        tabSize: 2,
        wordWrap: true,
        minimap: true,
        lineNumbers: true,
    },
    theme: {
        darkMode: true,
        accentColor: '#d97757',
    },
    auth: {
        requireLogin: true,
    },
    api: {
        baseUrl: 'http://124.222.100.193:9000/aiApi',
    },
    ai: {
        promptHistory: {},
        lastUsedAgent: 'claude-cli',
        autoStartAgent: true,
    },
    recentProjects: [],
    window: {
        width: 1400,
        height: 900,
        maximized: false,
    },
};
// Settings manager
class SettingsManager {
    settings = { ...DEFAULT_SETTINGS };
    loaded = false;
    ensureSettingsDir() {
        if (!fs.existsSync(SETTINGS_DIR)) {
            fs.mkdirSync(SETTINGS_DIR, { recursive: true });
        }
    }
    load() {
        if (this.loaded)
            return this.settings;
        try {
            this.ensureSettingsDir();
            if (fs.existsSync(SETTINGS_FILE)) {
                const content = fs.readFileSync(SETTINGS_FILE, 'utf-8');
                const parsed = JSON.parse(content);
                this.settings = this.mergeSettings(DEFAULT_SETTINGS, parsed);
            }
            else {
                this.save();
            }
            this.loaded = true;
        }
        catch {
            this.settings = { ...DEFAULT_SETTINGS };
        }
        return this.settings;
    }
    mergeSettings(defaults, user) {
        const result = { ...defaults };
        for (const key in user) {
            if (user[key] !== null && typeof user[key] === 'object' && !Array.isArray(user[key])) {
                result[key] = this.mergeSettings(defaults[key] || {}, user[key]);
            }
            else {
                result[key] = user[key];
            }
        }
        return result;
    }
    save() {
        try {
            this.ensureSettingsDir();
            fs.writeFileSync(SETTINGS_FILE, JSON.stringify(this.settings, null, 2), 'utf-8');
        }
        catch {
            // Ignore save errors
        }
    }
    get() {
        if (!this.loaded) {
            this.load();
        }
        return this.settings;
    }
    update(updates) {
        this.settings = this.mergeSettings(this.settings, updates);
        this.save();
    }
    updatePath(pathStr, value) {
        const keys = pathStr.split('.');
        let current = this.settings;
        for (let i = 0; i < keys.length - 1; i++) {
            if (!(keys[i] in current)) {
                current[keys[i]] = {};
            }
            current = current[keys[i]];
        }
        current[keys[keys.length - 1]] = value;
        this.save();
    }
    getPath(pathStr) {
        const keys = pathStr.split('.');
        let current = this.settings;
        for (const key of keys) {
            if (current === undefined || current === null)
                return undefined;
            current = current[key];
        }
        return current;
    }
    reset() {
        this.settings = { ...DEFAULT_SETTINGS };
        this.save();
    }
}
const settingsManager = new SettingsManager();
// 导出 settingsManager 供其他模块使用
export { settingsManager };
// Settings handler
export function setupSettingsHandler(ws, sessionId) {
    return (msg) => {
        const { type, id, method, args } = msg;
        switch (method) {
            case 'settings:get':
                handleGet(ws, id);
                break;
            case 'settings:update':
                handleUpdate(ws, id, args);
                break;
            case 'settings:updatePath':
                handleUpdatePath(ws, id, args);
                break;
            case 'settings:getPath':
                handleGetPath(ws, id, args);
                break;
            case 'settings:addPromptHistory':
                handleAddPromptHistory(ws, id, args);
                break;
            case 'settings:getPromptHistory':
                handleGetPromptHistory(ws, id, args);
                break;
            case 'settings:reset':
                handleReset(ws, id);
                break;
            default:
                ws.send(JSON.stringify({ type: 'error', id, error: `Unknown settings method: ${method}` }));
        }
    };
}
function handleGet(ws, id) {
    const settings = settingsManager.load();
    ws.send(JSON.stringify({ type: 'response', id, result: { success: true, settings } }));
}
function handleUpdate(ws, id, args) {
    try {
        const updates = args[0];
        settingsManager.update(updates);
        ws.send(JSON.stringify({ type: 'response', id, result: { success: true } }));
    }
    catch (error) {
        ws.send(JSON.stringify({ type: 'response', id, result: { success: false, error: String(error) } }));
    }
}
function handleUpdatePath(ws, id, args) {
    try {
        const pathStr = args[0];
        const value = args[1];
        settingsManager.updatePath(pathStr, value);
        ws.send(JSON.stringify({ type: 'response', id, result: { success: true } }));
    }
    catch (error) {
        ws.send(JSON.stringify({ type: 'response', id, result: { success: false, error: String(error) } }));
    }
}
function handleGetPath(ws, id, args) {
    try {
        const pathStr = args[0];
        const value = settingsManager.getPath(pathStr);
        ws.send(JSON.stringify({ type: 'response', id, result: { success: true, value } }));
    }
    catch (error) {
        ws.send(JSON.stringify({ type: 'response', id, result: { success: false, error: String(error) } }));
    }
}
function handleAddPromptHistory(ws, id, args) {
    try {
        const agentId = args[0];
        const prompt = args[1];
        const settings = settingsManager.get();
        if (!settings.ai) {
            settings.ai = DEFAULT_SETTINGS.ai;
        }
        if (!settings.ai.promptHistory) {
            settings.ai.promptHistory = {};
        }
        const history = settings.ai.promptHistory[agentId] || [];
        // Don't duplicate
        if (history.length > 0 && history[history.length - 1] === prompt) {
            ws.send(JSON.stringify({ type: 'response', id, result: { success: true } }));
            return;
        }
        history.push(prompt);
        if (history.length > 50) {
            history.shift();
        }
        settings.ai.promptHistory[agentId] = history;
        settingsManager.save();
        ws.send(JSON.stringify({ type: 'response', id, result: { success: true } }));
    }
    catch (error) {
        ws.send(JSON.stringify({ type: 'response', id, result: { success: false, error: String(error) } }));
    }
}
function handleGetPromptHistory(ws, id, args) {
    try {
        const agentId = args[0];
        const settings = settingsManager.get();
        const history = settings.ai?.promptHistory?.[agentId] || [];
        ws.send(JSON.stringify({ type: 'response', id, result: { success: true, history } }));
    }
    catch (error) {
        ws.send(JSON.stringify({ type: 'response', id, result: { success: false, error: String(error) } }));
    }
}
function handleReset(ws, id) {
    try {
        settingsManager.reset();
        ws.send(JSON.stringify({ type: 'response', id, result: { success: true } }));
    }
    catch (error) {
        ws.send(JSON.stringify({ type: 'response', id, result: { success: false, error: String(error) } }));
    }
}
//# sourceMappingURL=settings.js.map