import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { isToolPermissionConfigurable, getPermissionReason, resolveToolPermission, computeToolWithPermission, loadAdditionalToolPreferences, saveAdditionalToolPreferences, updateToolPermission, clearToolPermission, processAdditionalTools } from '../additionalToolPermissions';
// Mock localStorage
const mockLocalStorage = (() => {
    let store = {};
    return {
        getItem: (key) => store[key] || null,
        setItem: (key, value) => {
            store[key] = value;
        },
        removeItem: (key) => {
            delete store[key];
        },
        clear: () => {
            store = {};
        }
    };
})();
// Mock window.localStorage
Object.defineProperty(window, 'localStorage', {
    value: mockLocalStorage
});
describe('additionalToolPermissions', () => {
    const basicTool = {
        name: 'test_tool',
        description: 'A test tool',
        execute: async () => ({ result: 'test' })
    };
    const approvalTool = {
        name: 'approval_tool',
        description: 'A tool requiring approval',
        needsApproval: true,
        execute: async () => ({ result: 'approved' })
    };
    const conditionalApprovalTool = {
        name: 'conditional_tool',
        description: 'A tool with conditional approval',
        needsApproval: async () => true,
        execute: async () => ({ result: 'conditional' })
    };
    beforeEach(() => {
        mockLocalStorage.clear();
    });
    afterEach(() => {
        mockLocalStorage.clear();
    });
    describe('isToolPermissionConfigurable', () => {
        it('returns true for tools without needsApproval', () => {
            expect(isToolPermissionConfigurable(basicTool)).toBe(true);
        });
        it('returns false for tools with needsApproval: true', () => {
            expect(isToolPermissionConfigurable(approvalTool)).toBe(false);
        });
        it('returns false for tools with needsApproval function', () => {
            expect(isToolPermissionConfigurable(conditionalApprovalTool)).toBe(false);
        });
    });
    describe('getPermissionReason', () => {
        it('returns user configurable for basic tools', () => {
            expect(getPermissionReason(basicTool)).toBe('User configurable');
        });
        it('returns developer message for approval tools', () => {
            expect(getPermissionReason(approvalTool)).toBe('Always requires approval (set by developer)');
        });
        it('returns conditional message for conditional tools', () => {
            expect(getPermissionReason(conditionalApprovalTool)).toBe('Conditional approval required (set by developer)');
        });
    });
    describe('resolveToolPermission', () => {
        const preferences = {
            'test_tool': 'ask_first',
            'other_tool': 'disabled'
        };
        it('respects needsApproval: true', () => {
            expect(resolveToolPermission(approvalTool, preferences)).toBe('ask_first');
        });
        it('respects needsApproval function', () => {
            expect(resolveToolPermission(conditionalApprovalTool, preferences)).toBe('ask_first');
        });
        it('uses user preference for configurable tools', () => {
            expect(resolveToolPermission(basicTool, preferences)).toBe('ask_first');
        });
        it('defaults to enabled when no preference set', () => {
            expect(resolveToolPermission(basicTool, {})).toBe('enabled');
        });
    });
    describe('computeToolWithPermission', () => {
        it('computes correct state for configurable tool', () => {
            const preferences = { 'test_tool': 'disabled' };
            const result = computeToolWithPermission(basicTool, preferences);
            expect(result).toMatchObject({
                name: 'test_tool',
                description: 'A test tool',
                runtimePermission: 'disabled',
                effectivePermission: 'disabled',
                isPermissionConfigurable: true,
                permissionReason: 'User configurable'
            });
        });
        it('computes correct state for immutable tool', () => {
            const preferences = { 'approval_tool': 'enabled' };
            const result = computeToolWithPermission(approvalTool, preferences);
            expect(result).toMatchObject({
                name: 'approval_tool',
                description: 'A tool requiring approval',
                runtimePermission: undefined,
                effectivePermission: 'ask_first',
                isPermissionConfigurable: false,
                permissionReason: 'Always requires approval (set by developer)'
            });
        });
    });
    describe('localStorage integration', () => {
        it('loads empty preferences when no data stored', () => {
            const preferences = loadAdditionalToolPreferences();
            expect(preferences).toEqual({});
        });
        it('saves and loads preferences correctly', () => {
            const preferences = {
                'tool1': 'ask_first',
                'tool2': 'disabled'
            };
            saveAdditionalToolPreferences(preferences);
            const loaded = loadAdditionalToolPreferences();
            expect(loaded).toEqual(preferences);
        });
        it('handles corrupted storage gracefully', () => {
            mockLocalStorage.setItem('additional-tool-preferences', 'invalid json');
            const preferences = loadAdditionalToolPreferences();
            expect(preferences).toEqual({});
        });
        it('handles version mismatch gracefully', () => {
            mockLocalStorage.setItem('additional-tool-preferences', JSON.stringify({
                version: 999,
                preferences: { 'tool1': 'enabled' },
                lastUpdated: new Date().toISOString()
            }));
            const preferences = loadAdditionalToolPreferences();
            expect(preferences).toEqual({});
        });
    });
    describe('updateToolPermission', () => {
        it('updates and persists tool permission', () => {
            const initial = { 'tool1': 'enabled' };
            const updated = updateToolPermission('tool2', 'ask_first', initial);
            expect(updated).toEqual({
                'tool1': 'enabled',
                'tool2': 'ask_first'
            });
            // Verify persistence
            const loaded = loadAdditionalToolPreferences();
            expect(loaded).toEqual(updated);
        });
    });
    describe('clearToolPermission', () => {
        it('removes tool permission and persists', () => {
            const initial = {
                'tool1': 'enabled',
                'tool2': 'ask_first'
            };
            const updated = clearToolPermission('tool2', initial);
            expect(updated).toEqual({ 'tool1': 'enabled' });
            // Verify persistence
            const loaded = loadAdditionalToolPreferences();
            expect(loaded).toEqual(updated);
        });
    });
    describe('processAdditionalTools', () => {
        it('processes multiple tools correctly', () => {
            const tools = [basicTool, approvalTool, conditionalApprovalTool];
            const preferences = {
                'test_tool': 'disabled'
            };
            const processed = processAdditionalTools(tools, preferences);
            expect(processed).toHaveLength(3);
            expect(processed[0].effectivePermission).toBe('disabled');
            expect(processed[1].effectivePermission).toBe('ask_first');
            expect(processed[2].effectivePermission).toBe('ask_first');
        });
        it('loads preferences from storage when not provided', () => {
            saveAdditionalToolPreferences({ 'test_tool': 'ask_first' });
            const processed = processAdditionalTools([basicTool]);
            expect(processed[0].effectivePermission).toBe('ask_first');
        });
    });
});
