// *****************************************************************************
// Copyright (C) 2019 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************

import { Container, injectable } from 'inversify';
import type { IWindowsKeyMapping } from 'native-keymap';
import { Emitter, Event } from '../../common/event.js';
import { Key, KeyCode, LayoutModifiers, NormalizedKeyboardInput } from './keys.js';
import { KeyboardLayoutService } from './keyboard-layout-service.js';
import {
    KeyboardLayoutProvider, NativeKeyboardLayout, KeyboardLayoutChangeNotifier, KeyValidationInput, KeyValidator, KeyboardLayoutSource
} from '../../common/keyboard/keyboard-layout-provider.js';
import * as chai from 'chai';
import deGermanMacLayout from '../../common/keyboard/layouts/de-German-mac.json' with { type: 'json' };
import deGermanPcLayout from '../../common/keyboard/layouts/de-German-pc.json' with { type: 'json' };
import frFrenchMacLayout from '../../common/keyboard/layouts/fr-French-mac.json' with { type: 'json' };
import frFrenchPcLayout from '../../common/keyboard/layouts/fr-French-pc.json' with { type: 'json' };
import deSwissGermanPcLayout from '../../common/keyboard/layouts/de-Swiss_German-pc.json' with { type: 'json' };
import enUSMacLayout from '../../common/keyboard/layouts/en-US-mac.json' with { type: 'json' };
import enUSPcLayout from '../../common/keyboard/layouts/en-US-pc.json' with { type: 'json' };
import frBepoPcLayout from '../../common/keyboard/layouts/fr-Bepo-pc.json' with { type: 'json' };
import { OSStub, stubOS } from '../../common/test/stub-os.js';

class TestKeyboardLayoutService extends KeyboardLayoutService {
    public override getWindowsKeyCodeInterpretations(keyCode: KeyCode, input: NormalizedKeyboardInput,
        layoutModifiers: LayoutModifiers | undefined): KeyCode[] {
        return super.getWindowsKeyCodeInterpretations(keyCode, input, layoutModifiers);
    }
}

const RUSSIAN_LAYOUT: NativeKeyboardLayout = {
    info: { id: 'ru', lang: 'ru' },
    mapping: {
        KeyA: { value: 'ф', withShift: 'Ф', withAltGr: '', withShiftAltGr: '' },
        KeyC: { value: 'с', withShift: 'С', withAltGr: '', withShiftAltGr: '' },
        KeyV: { value: 'м', withShift: 'М', withAltGr: '', withShiftAltGr: '' },
        KeyS: { value: 'ы', withShift: 'Ы', withAltGr: '', withShiftAltGr: '' },
        Digit8: { value: '8', withShift: '*', withAltGr: '', withShiftAltGr: '' },
        BracketLeft: { value: 'х', withShift: 'Х', withAltGr: '', withShiftAltGr: '' },
        Comma: { value: 'б', withShift: 'Б', withAltGr: '', withShiftAltGr: '' }
    }
};

const deGermanMac = deGermanMacLayout as unknown as NativeKeyboardLayout;
const deGermanPc = deGermanPcLayout as unknown as NativeKeyboardLayout;
const frFrenchMac = frFrenchMacLayout as unknown as NativeKeyboardLayout;
const frFrenchPc = frFrenchPcLayout as unknown as NativeKeyboardLayout;
const deSwissGermanPc = deSwissGermanPcLayout as unknown as NativeKeyboardLayout;
const enUSMac = enUSMacLayout as unknown as NativeKeyboardLayout;
const enUSPc = enUSPcLayout as unknown as NativeKeyboardLayout;
const frBepoPc = frBepoPcLayout as unknown as NativeKeyboardLayout;

describe('keyboard layout service', function (): void {

    let stubOSX: OSStub;
    let stubWindows: OSStub;

    const setup = async (
        layout: NativeKeyboardLayout,
        system: 'mac' | 'win' | 'linux',
        layoutSource?: KeyboardLayoutSource,
        keyValidator?: KeyValidator
    ) => {
        switch (system) {
            case 'mac':
                stubOSX = stubOS('isOSX', true);
                stubWindows = stubOS('isWindows', false);
                break;
            case 'win':
                stubOSX = stubOS('isOSX', false);
                stubWindows = stubOS('isWindows', true);
                break;
            default:
                stubOSX = stubOS('isOSX', false);
                stubWindows = stubOS('isWindows', false);
        }
        const container = new Container();
        container.bind(KeyboardLayoutService).to(TestKeyboardLayoutService).inSingletonScope();
        @injectable()
        class MockLayoutProvider implements KeyboardLayoutProvider, KeyboardLayoutChangeNotifier {
            readonly layoutSource = layoutSource;
            emitter = new Emitter<NativeKeyboardLayout>();
            get onDidChangeNativeLayout(): Event<NativeKeyboardLayout> {
                return this.emitter.event;
            }
            getNativeLayout(): Promise<NativeKeyboardLayout> {
                return Promise.resolve(layout);
            }
        }
        container.bind(KeyboardLayoutProvider).to(MockLayoutProvider);
        container.bind(KeyboardLayoutChangeNotifier).to(MockLayoutProvider);
        if (keyValidator) {
            container.bind(KeyValidator).toConstantValue(keyValidator);
        }
        const service = container.get(KeyboardLayoutService) as TestKeyboardLayoutService;
        await service.initialize();
        return service;
    };

    afterEach(() => {
        stubOSX.restore();
        stubWindows.restore();
    });

    it('reports an unknown layout source when no source provider is configured', async () => {
        const layout: NativeKeyboardLayout = { info: { id: 'mock', lang: 'en' }, mapping: {} };
        chai.expect((await setup(layout, 'linux')).layoutSource).to.equal('unknown');
    });

    it('reports the configured layout source', async () => {
        const layout: NativeKeyboardLayout = { info: { id: 'mock', lang: 'en' }, mapping: {} };
        chai.expect((await setup(layout, 'linux', 'native-keymap')).layoutSource).to.equal('native-keymap');
    });

    it('resolves correct key bindings with German Mac layout', async () => {
        const macGerman = deGermanMac;
        const service = await setup(macGerman, 'mac');

        const toggleComment = service.resolveKeyCode(KeyCode.createKeyCode('Slash+M1'));
        chai.expect(toggleComment.toString()).to.equal('meta+7');
        chai.expect(toggleComment.character).to.equal('/');
        chai.expect(toggleComment.layoutModifiers).to.deep.equal('shift');
        chai.expect(service.getKeyboardCharacter(toggleComment.key!)).to.equal('7');

        const indentLine = service.resolveKeyCode(KeyCode.createKeyCode('BracketRight+M1'));
        chai.expect(indentLine.toString()).to.equal('meta+6');
        chai.expect(indentLine.character).to.equal(']');
        chai.expect(indentLine.layoutModifiers).to.deep.equal('altGraph');
        chai.expect(service.getKeyboardCharacter(indentLine.key!)).to.equal('6');
    });

    it('resolves correct key bindings with French Mac layout', async () => {
        const macFrench = frFrenchMac;
        const service = await setup(macFrench, 'mac');

        const toggleComment = service.resolveKeyCode(KeyCode.createKeyCode('Slash+M1'));
        chai.expect(toggleComment.toString()).to.equal('meta+.');
        chai.expect(toggleComment.character).to.equal('/');
        chai.expect(toggleComment.layoutModifiers).to.deep.equal('shift');
        chai.expect(service.getKeyboardCharacter(toggleComment.key!)).to.equal(':');

        const indentLine = service.resolveKeyCode(KeyCode.createKeyCode('BracketRight+M1'));
        chai.expect(indentLine.toString()).to.equal('meta+-');
        chai.expect(indentLine.character).to.equal(']');
        chai.expect(indentLine.layoutModifiers).to.deep.equal('shiftAltGraph');
        chai.expect(service.getKeyboardCharacter(indentLine.key!)).to.equal(')');
    });

    it('uses global layout modifier priority and a stable physical-key tie-break', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'priority', lang: 'fr' },
            mapping: {
                Backslash: { value: '*', withShift: 'µ', withAltGr: '@', withShiftAltGr: '#' },
                IntlBackslash: { value: '@', withShift: '#', withAltGr: 'µ', withShiftAltGr: '*' },
                KeyB: { value: 'x', withShift: 'X', withAltGr: '', withShiftAltGr: '' },
                KeyA: { value: 'x', withShift: 'X', withAltGr: '', withShiftAltGr: '' }
            }
        };
        const service = await setup(layout, 'linux');

        chai.expect(service.resolveKeyCode(KeyCode.parse('shift+2')).key).to.equal(Key.INTL_BACKSLASH);
        chai.expect(service.resolveKeyCode(KeyCode.parse('x')).key).to.equal(Key.KEY_A);

        const shifted = service.resolveKeyCode(KeyCode.parse('shift+x'));
        const event = service.getKeyCodeInterpretations({ key: 'X', code: 'KeyA', shiftKey: true }, 'code')
            .find(candidate => candidate.interpretation === 'layoutModifiers')!;
        chai.expect(event.dispatchString()).to.equal(shifted.dispatchString());

        const altShifted = service.resolveKeyCode(KeyCode.parse('alt+shift+x'));
        const altEvent = service.getKeyCodeInterpretations({ key: 'X', code: 'KeyA', altKey: true, shiftKey: true }, 'code')
            .find(candidate => candidate.interpretation === 'layoutModifiers')!;
        chai.expect(altEvent.dispatchString()).to.equal(altShifted.dispatchString());

        const capsLockEvent = service.getKeyCodeInterpretations({ key: 'x', code: 'KeyA', shiftKey: true }, 'code')
            .find(candidate => candidate.interpretation === 'layoutModifiers')!;
        chai.expect(capsLockEvent.dispatchString()).to.equal(shifted.dispatchString());
    });

    it('globally ranks case-folded fallback candidates', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'case-folded-priority', lang: 'en' },
            mapping: {
                KeyA: { value: 'a', withShift: 'A', withAltGr: 'ä', withShiftAltGr: '' },
                KeyB: { value: 'b', withShift: 'ä', withAltGr: '', withShiftAltGr: '' }
            }
        };
        const service = await setup(layout, 'linux');
        const resolved = service.resolveKeyCode(KeyCode.parse('[char:0xC4]'));
        chai.expect(resolved.key).to.equal(Key.KEY_B);
        chai.expect(resolved.layoutModifiers).to.deep.equal('shift');
    });

    it('matches shifted physical scan-code bindings through the command interpretation', async () => {
        const us = enUSPc;
        const service = await setup(us, 'linux');
        const physical = service.resolveKeyCode(KeyCode.parse('ctrl+shift+[BracketRight]'));
        const interpretations = service.getKeyCodeInterpretations({
            key: '}', code: 'BracketRight', ctrlKey: true, shiftKey: true
        }, 'code');
        chai.expect(physical.physical).to.be.true;
        chai.expect(interpretations.some(candidate => candidate.dispatchString() === physical.dispatchString())).to.be.true;
    });

    it('keeps BÉPO logical bindings distinct from their former US-position collisions', async () => {
        const bepo = frBepoPc;
        const service = await setup(bepo, 'linux');

        const undo = service.resolveKeyCode(KeyCode.parse('ctrl+z'));
        const outdent = service.resolveKeyCode(KeyCode.parse('ctrl+['));
        const close = service.resolveKeyCode(KeyCode.parse('ctrl+w'));
        const indent = service.resolveKeyCode(KeyCode.parse('ctrl+]'));
        chai.expect(undo.key).to.equal(Key.BRACKET_LEFT);
        chai.expect(outdent.key).to.equal(Key.DIGIT4);
        chai.expect(outdent.layoutModifiers).to.equal('altGraph');
        chai.expect(close.key).to.equal(Key.BRACKET_RIGHT);
        chai.expect(indent.key).to.equal(Key.DIGIT5);
        chai.expect(indent.layoutModifiers).to.equal('altGraph');
    });

    it('falls back to the US position for Latin letters missing from a non-Latin layout', async () => {
        const service = await setup(RUSSIAN_LAYOUT, 'linux');

        const resolved = service.resolveKeyCode(KeyCode.parse('ctrl+c'));
        chai.expect(resolved.key).to.equal(Key.KEY_C);
        chai.expect(resolved.supportedByLayout).to.be.true;
        chai.expect(resolved.layoutModifiers).to.equal('none');
        chai.expect(resolved.dispatchString()).to.equal('ctrl+c');
        chai.expect(service.getLatinLetterFallback(Key.KEY_C)).to.equal('c');
        chai.expect(service.getLatinLetterFallback(Key.DIGIT8)).to.be.undefined;
        chai.expect(service.resolveKeyCode(KeyCode.parse('с')).key).to.equal(Key.KEY_C);
        chai.expect(service.getKeyboardCharacter(Key.KEY_C)).to.equal('с');
    });

    it('absorbs Shift into the Latin fallback letter', async () => {
        const service = await setup(RUSSIAN_LAYOUT, 'linux');

        const resolved = service.resolveKeyCode(KeyCode.parse('ctrl+shift+a'));
        chai.expect(resolved.key).to.equal(Key.KEY_A);
        chai.expect(resolved.layoutModifiers).to.equal('shift');
        chai.expect(resolved.shift).to.be.false;
        chai.expect(resolved.character).to.equal('A');
    });

    it('does not fall back for punctuation on a non-Latin layout', async () => {
        const service = await setup(RUSSIAN_LAYOUT, 'linux');

        chai.expect(service.resolveKeyCode(KeyCode.parse('ctrl+[')).supportedByLayout).to.be.false;
    });

    it('does not override Latin letters produced elsewhere on the layout', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'linux');

        chai.expect(service.resolveKeyCode(KeyCode.parse('ctrl+z')).key).to.equal(Key.KEY_Y);
        chai.expect(service.getLatinLetterFallback(Key.KEY_Z)).to.be.undefined;
    });

    it('does not override letters produced in only one case on the base or Shift layer', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'one-case-only', lang: 'en' },
            mapping: {
                KeyS: { value: 'o', withShift: 'Q', withAltGr: '', withShiftAltGr: '' },
                KeyO: { value: 's', withShift: 'P', withAltGr: '', withShiftAltGr: '' }
            }
        };
        const service = await setup(layout, 'linux');

        chai.expect(service.resolveKeyCode(KeyCode.parse('o')).key).to.equal(Key.KEY_S);
        chai.expect(service.resolveKeyCode(KeyCode.parse('p')).key).to.equal(Key.KEY_O);
        chai.expect(service.resolveKeyCode(KeyCode.parse('p')).layoutModifiers).to.equal('shift');
        for (const key of [Key.KEY_O, Key.KEY_P, Key.KEY_Q, Key.KEY_S]) {
            chai.expect(service.getLatinLetterFallback(key)).to.be.undefined;
        }
    });

    it('adds a fallback when a letter is produced only on the AltGraph layer', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'altgraph-only-latin', lang: 'ru' },
            mapping: {
                KeyQ: { value: 'й', withShift: 'Й', withAltGr: 'a', withShiftAltGr: '' }
            }
        };
        const service = await setup(layout, 'linux');

        const resolved = service.resolveKeyCode(KeyCode.parse('a'));
        chai.expect(resolved.key).to.equal(Key.KEY_A);
        chai.expect(resolved.layoutModifiers).to.equal('none');
        chai.expect(service.getLatinLetterFallback(Key.KEY_A)).to.equal('a');
    });

    it('adds Latin fallbacks to Windows mappings with vkeys and character values', async () => {
        const layout: NativeKeyboardLayout = {
            ...RUSSIAN_LAYOUT,
            mapping: {
                ...RUSSIAN_LAYOUT.mapping,
                KeyC: { ...RUSSIAN_LAYOUT.mapping.KeyC, vkey: 'VK_C' } as never
            }
        };
        const service = await setup(layout, 'win');

        chai.expect(service.resolveKeyCode(KeyCode.parse('ctrl+c')).key).to.equal(Key.KEY_C);
        chai.expect(service.getLatinLetterFallback(Key.KEY_C)).to.equal('c');
    });

    it('marks printable bindings unresolved when the layout mapping is empty', async () => {
        const layout: NativeKeyboardLayout = { info: { id: 'empty', lang: 'en' }, mapping: {} };
        const service = await setup(layout, 'linux');

        chai.expect(service.resolveKeyCode(KeyCode.parse('ctrl+[')).supportedByLayout).to.be.false;
        for (const lower of 'abcdefghijklmnopqrstuvwxyz') {
            const key = Key.getKey(`Key${lower.toUpperCase()}`)!;
            chai.expect(service.resolveKeyCode(KeyCode.parse(`ctrl+${lower}`)).key).to.equal(key);
            chai.expect(service.getLatinLetterFallback(key)).to.equal(lower);
        }
        chai.expect(service.resolveKeyCode(KeyCode.parse('f1')).supportedByLayout).to.be.true;
    });

    it('marks unavailable logical characters unresolved instead of using the US position', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'missing-bracket', lang: 'en' },
            mapping: {
                KeyA: { value: 'a', withShift: 'A', withAltGr: '', withShiftAltGr: '' }
            }
        };
        const service = await setup(layout, 'linux');

        const outdent = service.resolveKeyCode(KeyCode.parse('ctrl+['));
        chai.expect(outdent.supportedByLayout).to.be.false;
        chai.expect(outdent.key).to.equal(Key.BRACKET_LEFT);
    });

    it('does not let a dead key hijack a keybinding on Mac (#17677)', async () => {
        // On macOS US Extended, Option+P is the "combining comma below" dead key whose display glyph
        // is reported as ',' by native-keymap. Since KeyP is reported before Comma, without honoring the
        // dead-key flags it would claim the ',' slot and resolve ctrlcmd+, to Cmd+Ctrl+Option+P.
        const macUSExtended: NativeKeyboardLayout = {
            info: { id: 'com.apple.keylayout.USExtended', lang: 'en' },
            mapping: {
                KeyP: {
                    value: 'p', valueIsDeadKey: false,
                    withShift: 'P', withShiftIsDeadKey: false,
                    withAltGr: ',', withAltGrIsDeadKey: true,
                    withShiftAltGr: '̦', withShiftAltGrIsDeadKey: true
                },
                Comma: {
                    value: ',', valueIsDeadKey: false,
                    withShift: '<', withShiftIsDeadKey: false,
                    withAltGr: '≤', withAltGrIsDeadKey: false,
                    withShiftAltGr: '¯', withShiftAltGrIsDeadKey: false
                }
            }
        };
        const service = await setup(macUSExtended, 'mac');

        const openSettings = service.resolveKeyCode(KeyCode.createKeyCode('Comma+M1'));
        chai.expect(openSettings.toString()).to.equal('meta+,');
        chai.expect(service.getKeyboardCharacter(openSettings.key!)).to.equal(',');
    });

    it('filters dead AltGraph mappings on Linux and Windows', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'dead-altgraph', lang: 'en' },
            mapping: {
                KeyP: {
                    value: 'p', withShift: 'P', withAltGr: '§', withShiftAltGr: '', withAltGrIsDeadKey: true, vkey: 'VK_P'
                } as IWindowsKeyMapping & { withAltGrIsDeadKey: boolean }
            }
        };
        for (const system of ['linux', 'win'] as const) {
            const service = await setup(layout, system);
            chai.expect(service.resolveKeyCode(KeyCode.parse('§')).supportedByLayout).to.be.false;
            stubOSX.restore();
            stubWindows.restore();
        }
        stubOSX = stubOS('isOSX', false);
        stubWindows = stubOS('isWindows', false);
    });

    it('retains the Windows vkey fallback for value-less mappings', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'vkey-fallback', lang: 'en' },
            mapping: { KeyA: { vkey: 'VK_A', value: '' } as never }
        };
        const service = await setup(layout, 'win');
        const resolved = service.resolveKeyCode(KeyCode.parse('a'));
        chai.expect(resolved.supportedByLayout).to.be.true;
        chai.expect(resolved.key).to.equal(Key.KEY_A);
    });

    it('absorbs authored Shift when it selects a US character or layout shift layer', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'linux');
        const legacy = service.resolveKeyCode(KeyCode.parse('ctrl+shift+['));
        chai.expect(legacy.shift).to.be.false;
        chai.expect(legacy.dispatchString()).to.equal('ctrl+7@altgraph');
    });

    it('retains authored Shift when it is not consumed by the logical character', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'linux');

        const umlaut = service.resolveKeyCode(KeyCode.parse('ctrl+shift+ü'));
        chai.expect(umlaut.dispatchString()).to.equal('shift+ctrl+[');
        chai.expect(umlaut.layoutModifiers).to.equal('none');

        chai.expect(service.resolveKeyCode(KeyCode.parse('shift+[char:0x41]')).dispatchString()).to.equal('a@shift');
        chai.expect(service.resolveKeyCode(KeyCode.parse('shift+[char:0x61]')).dispatchString()).to.equal('shift+a');
        chai.expect(service.resolveKeyCode(KeyCode.parse('ctrl+shift+a')).dispatchString()).to.equal('ctrl+a@shift');
        chai.expect(service.resolveKeyCode(KeyCode.parse('ctrl+shift+[')).dispatchString()).to.equal('ctrl+7@altgraph');
    });

    it('requires Option for a macOS Shift+AltGraph layer', async () => {
        const macUS = enUSMac;
        const service = await setup(macUS, 'mac');
        chai.expect(service.detectLayoutModifiers({ key: '±', code: 'IntlBackslash', shiftKey: true })).to.equal('shift');
        chai.expect(service.detectLayoutModifiers({ key: '±', code: 'IntlBackslash', shiftKey: true, altKey: true })).to.equal('shiftAltGraph');
    });

    it('interprets macOS Option as a command modifier besides the Option layer', async () => {
        const macUS = enUSMac;
        const service = await setup(macUS, 'mac');

        const optionShift = service.getKeyCodeInterpretations({ key: '∏', code: 'KeyP', shiftKey: true, altKey: true }, 'code');
        chai.expect(optionShift.map(candidate => candidate.dispatchString())).to.deep.equal(['shift+alt+p', 'alt+p@shift', 'p@shift@altgraph']);
        chai.expect(optionShift.map(candidate => candidate.character)).to.deep.equal(['P', 'P', '∏']);
        chai.expect(service.resolveKeyCode(KeyCode.parse('shift+alt+p')).dispatchString()).to.equal('alt+p@shift');

        const option = service.getKeyCodeInterpretations({ key: 'π', code: 'KeyP', altKey: true }, 'code');
        chai.expect(option.map(candidate => candidate.dispatchString())).to.deep.equal(['alt+p', 'p@altgraph']);
        chai.expect(option.map(candidate => candidate.character)).to.deep.equal(['p', 'π']);

        const shift = service.getKeyCodeInterpretations({ key: 'P', code: 'KeyP', shiftKey: true }, 'code');
        chai.expect(shift.map(candidate => candidate.dispatchString())).to.deep.equal(['shift+p', 'p@shift']);
    });

    it('records the base character for dead Option keys on macOS', async () => {
        const service = await setup(enUSMac, 'mac');

        const option = service.getKeyCodeInterpretations({ key: 'Dead', code: 'KeyE', altKey: true }, 'code');
        chai.expect(option).to.have.length(1);
        chai.expect(option[0].character).to.equal('e');
        chai.expect(option[0].interpretation).to.equal('commandModifiers');
        chai.expect(option[0].dispatchString()).to.equal('alt+e');

        const optionShift = service.getKeyCodeInterpretations({ key: 'Dead', code: 'KeyE', altKey: true, shiftKey: true }, 'code');
        chai.expect(optionShift.map(candidate => candidate.character)).to.deep.equal(['E', 'E']);
        chai.expect(optionShift.map(candidate => candidate.dispatchString())).to.deep.equal(['shift+alt+e', 'alt+e@shift']);

        const withoutOption = service.getKeyCodeInterpretations({ key: 'Dead', code: 'KeyE' }, 'code');
        chai.expect(withoutOption).to.have.length(1);
        chai.expect(withoutOption[0].character).to.be.undefined;
    });

    it('normalizes the character to the layout layer when Caps Lock inverts the case', async () => {
        const us = await setup(enUSPc, 'linux');
        const capsShift = us.getKeyCodeInterpretations({ key: 'p', code: 'KeyP', ctrlKey: true, shiftKey: true }, 'code');
        chai.expect(capsShift.map(candidate => candidate.character)).to.deep.equal(['P', 'P']);
        chai.expect(capsShift.map(candidate => candidate.dispatchString())).to.deep.equal(['shift+ctrl+p', 'ctrl+p@shift']);
        const shift = us.getKeyCodeInterpretations({ key: 'P', code: 'KeyP', shiftKey: true }, 'code');
        chai.expect(shift.map(candidate => candidate.character)).to.deep.equal(['P', 'P']);
        stubOSX.restore();
        stubWindows.restore();

        const german = await setup(deGermanPc, 'linux');
        const capsBase = german.getKeyCodeInterpretations({ key: 'Ü', code: 'BracketLeft', ctrlKey: true }, 'code');
        chai.expect(capsBase).to.have.length(1);
        chai.expect(capsBase[0].character).to.equal('ü');
        chai.expect(capsBase[0].dispatchString()).to.equal('ctrl+[');
    });

    it('normalizes the character to the macOS Option layer when Caps Lock inverts the case', async () => {
        const service = await setup(enUSMac, 'mac');
        const capsOption = service.getKeyCodeInterpretations({ key: 'Å', code: 'KeyA', altKey: true }, 'code');
        chai.expect(capsOption.map(candidate => candidate.character)).to.deep.equal(['a', 'å']);
        chai.expect(capsOption.map(candidate => candidate.dispatchString())).to.deep.equal(['alt+a', 'a@altgraph']);

        const capsShiftOption = service.getKeyCodeInterpretations({ key: 'å', code: 'KeyA', altKey: true, shiftKey: true }, 'code');
        chai.expect(capsShiftOption[0].character).to.equal('A');
        chai.expect(capsShiftOption[0].dispatchString()).to.equal('shift+alt+a');
    });

    it('attributes Shift to the Shift layer when input reports the base character', async () => {
        // Test automation such as Puppeteer can report the base character while Shift is held.
        const us = enUSPc;
        const service = await setup(us, 'linux');
        const input: NormalizedKeyboardInput = { key: '`', code: 'Backquote', ctrlKey: true, shiftKey: true };

        chai.expect(service.detectLayoutModifiers(input)).to.equal('shift');
        const interpretations = service.getKeyCodeInterpretations(input, 'code');
        chai.expect(interpretations.map(keyCode => keyCode.interpretation)).to.deep.equal(['commandModifiers', 'layoutModifiers']);
        chai.expect(interpretations.map(keyCode => keyCode.dispatchString())).to.deep.equal(['shift+ctrl+`', 'ctrl+`@shift']);
        chai.expect(interpretations[1].dispatchString()).to.equal(service.resolveKeyCode(KeyCode.parse('ctrl+shift+`')).dispatchString());
    });

    it('does not attribute base-character input to the Shift layer when AltGraph is active or the Shift layer is dead', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'dead-shift', lang: 'en' },
            mapping: {
                Backquote: {
                    value: '`', valueIsDeadKey: false, withShift: '~', withShiftIsDeadKey: false,
                    withAltGr: '', withAltGrIsDeadKey: false, withShiftAltGr: '', withShiftAltGrIsDeadKey: false
                },
                Equal: {
                    value: '=', valueIsDeadKey: false, withShift: '^', withShiftIsDeadKey: true,
                    withAltGr: '', withAltGrIsDeadKey: false, withShiftAltGr: '', withShiftAltGrIsDeadKey: false
                }
            }
        };
        const service = await setup(layout, 'linux');

        chai.expect(service.detectLayoutModifiers({ key: '`', code: 'Backquote', shiftKey: true, altGraph: true })).to.be.undefined;
        chai.expect(service.detectLayoutModifiers({ key: '=', code: 'Equal', shiftKey: true })).to.be.undefined;
    });

    it('normalizes the character to the Linux AltGraph layer when Caps Lock inverts the case', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'altgraph-letters', lang: 'pl' },
            mapping: { KeyL: { value: 'l', withShift: 'L', withAltGr: 'ł', withShiftAltGr: 'Ł' } }
        };
        const service = await setup(layout, 'linux');
        const capsAltGraph = service.getKeyCodeInterpretations({ key: 'Ł', code: 'KeyL', altGraph: true }, 'code');
        chai.expect(capsAltGraph).to.have.length(1);
        chai.expect(capsAltGraph[0].character).to.equal('ł');
        chai.expect(capsAltGraph[0].dispatchString()).to.equal('l@altgraph');

        const capsShiftAltGraph = service.getKeyCodeInterpretations({ key: 'ł', code: 'KeyL', shiftKey: true, altGraph: true }, 'code');
        chai.expect(capsShiftAltGraph).to.have.length(1);
        chai.expect(capsShiftAltGraph[0].character).to.equal('Ł');
    });

    it('does not add an AltGraph layer to Linux Alt+Shift input', async () => {
        const service = await setup(enUSPc, 'linux');
        chai.expect(service.getKeyCodeInterpretations({ key: 'P', code: 'KeyP', shiftKey: true, altKey: true }, 'code')
            .map(candidate => candidate.dispatchString())).to.deep.equal(['shift+alt+p', 'alt+p@shift']);
    });

    it('requires AltGraph for a Linux Shift+AltGraph layer', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'same-shift-layers', lang: 'en' },
            mapping: { KeyA: { value: 'a', withShift: 'A', withAltGr: 'ä', withShiftAltGr: 'A' } }
        };
        const service = await setup(layout, 'linux');
        chai.expect(service.detectLayoutModifiers({ key: 'A', code: 'KeyA', shiftKey: true })).to.equal('shift');
        chai.expect(service.detectLayoutModifiers({ key: 'A', code: 'KeyA', shiftKey: true, altGraph: true })).to.equal('shiftAltGraph');
    });

    it('uses Option as macOS AltGraph layer evidence', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'altgraph-evidence', lang: 'en' },
            mapping: { KeyA: { value: 'a', withShift: 'A', withAltGr: 'ä', withShiftAltGr: 'Ä' } }
        };
        const service = await setup(layout, 'mac');
        chai.expect(service.detectLayoutModifiers({ key: 'ä', code: 'KeyA', altKey: true })).to.equal('altGraph');
        chai.expect(service.detectLayoutModifiers({ key: 'ä', code: 'KeyA' })).to.be.undefined;
    });

    it('uses emulated Windows AltGraph as platform layer evidence', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'altgraph-evidence', lang: 'en' },
            mapping: { KeyA: { value: 'a', withShift: 'A', withAltGr: 'ä', withShiftAltGr: 'Ä' } }
        };
        const service = await setup(layout, 'win');
        chai.expect(service.detectLayoutModifiers({ key: 'ä', code: 'KeyA', ctrlKey: true, altKey: true })).to.equal('altGraph');
    });

    it('constructs Linux layout modifier interpretations only for participating AltGraph', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'linux');

        const participating = service.getKeyCodeInterpretations({ key: '[', code: 'Digit8', altGraph: true }, 'code');
        chai.expect(participating).to.have.length(1);
        chai.expect(participating[0].layoutModifiers).to.deep.equal('altGraph');
        chai.expect(participating[0].dispatchString()).to.equal('8@altgraph');

        const nonParticipating = service.getKeyCodeInterpretations({ key: 'o', code: 'KeyO', altGraph: true }, 'code');
        chai.expect(nonParticipating[0].layoutModifiers).to.equal('none');

        const withoutModifierEvidence = service.getKeyCodeInterpretations({ key: '[', code: 'Digit8' }, 'code');
        chai.expect(withoutModifierEvidence[0].layoutModifiers).to.equal('none');

        const withCommandAlt = service.getKeyCodeInterpretations({ key: '[', code: 'Digit8', altKey: true, altGraph: true }, 'code');
        chai.expect(withCommandAlt[0].alt).to.be.true;
        chai.expect(withCommandAlt[0].layoutModifiers).to.equal('altGraph');
    });

    it('keeps shifted printable bindings symmetric in keyCode dispatch mode', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'linux');

        const commandPalette = KeyCode.parse('ctrl+shift+p');
        const shiftedPrintable = KeyCode.parse('shift+/');
        chai.expect(service.getKeyCodeInterpretations({ key: 'P', code: 'KeyP', keyCode: Key.KEY_P.keyCode, ctrlKey: true, shiftKey: true }, 'keyCode')[0]
            .dispatchString()).to.equal(commandPalette.dispatchString());
        chai.expect(service.getKeyCodeInterpretations({ key: '/', code: 'Digit7', keyCode: Key.SLASH.keyCode, shiftKey: true }, 'keyCode')[0]
            .dispatchString()).to.equal(shiftedPrintable.dispatchString());
    });

    it('constructs command-first and layout modifier Windows interpretations', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'win');

        const interpretations = service.getKeyCodeInterpretations({
            key: '[', code: 'Digit8', ctrlKey: true, altKey: true, altGraph: false
        }, 'code');
        chai.expect(interpretations.map(code => code.interpretation)).to.deep.equal(['commandModifiers', 'layoutModifiers']);
        chai.expect(interpretations[0].dispatchString()).to.equal('alt+ctrl+8');
        chai.expect(interpretations[1].dispatchString()).to.equal('8@altgraph');

        const intentional = service.getKeyCodeInterpretations({
            key: 'f', code: 'KeyF', ctrlKey: true, altKey: true, altGraph: false
        }, 'code');
        chai.expect(intentional).to.have.length(1);
        chai.expect(intentional[0].dispatchString()).to.equal('alt+ctrl+f');

        const shiftedBinding = service.resolveKeyCode(KeyCode.parse('ctrl+shift+p'));
        const shiftedEvent = service.getKeyCodeInterpretations({ key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true }, 'code')
            .find(candidate => candidate.interpretation === 'layoutModifiers')!;
        chai.expect(shiftedBinding.supportedByLayout).to.be.true;
        chai.expect(shiftedEvent.dispatchString()).to.equal(shiftedBinding.dispatchString());
    });

    it('preserves authored command modifiers alongside explicit Windows AltGraph', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'win');
        const cases = [
            { ctrlKey: false, altKey: false, metaKey: false, expected: '8@altgraph' },
            { ctrlKey: true, altKey: false, metaKey: true, expected: 'meta+ctrl+8@altgraph' },
            { ctrlKey: false, altKey: true, metaKey: true, expected: 'meta+alt+8@altgraph' }
        ];

        for (const { expected, ...modifiers } of cases) {
            const input = { key: '[', code: 'Digit8', altGraph: true, ...modifiers };
            const keyCode = new KeyCode({
                key: Key.DIGIT8, character: '[', ctrl: input.ctrlKey, alt: input.altKey, meta: input.metaKey
            });
            const interpretations = service.getWindowsKeyCodeInterpretations(keyCode, input, 'altGraph');
            chai.expect(interpretations).to.have.length(1);
            chai.expect(interpretations[0].interpretation).to.equal('layoutModifiers');
            chai.expect(interpretations[0].dispatchString()).to.equal(expected);
        }
    });

    it('keeps legacy Windows AltGraph reporting typing-safe and preserves Meta', async () => {
        const german = deGermanPc;
        const service = await setup(german, 'win');

        for (const metaKey of [false, true]) {
            const input = { key: '[', code: 'Digit8', ctrlKey: true, altKey: true, altGraph: true, metaKey };
            const keyCode = new KeyCode({ key: Key.DIGIT8, character: '[', ctrl: true, alt: true, meta: metaKey });
            const interpretations = service.getWindowsKeyCodeInterpretations(keyCode, input, 'altGraph');
            const prefix = metaKey ? 'meta+' : '';

            chai.expect(interpretations.map(code => code.interpretation)).to.deep.equal(['commandModifiers', 'layoutModifiers']);
            chai.expect(interpretations[0].dispatchString()).to.equal(`${prefix}alt+ctrl+8`);
            chai.expect(interpretations[1].dispatchString()).to.equal(`${prefix}8@altgraph`);
        }
    });

    it('uses confirmed withAltGr output as Shift+AltGraph fallback when the shifted layer is absent', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'shift-altgraph-fallback', lang: 'en' },
            mapping: {
                Digit8: { value: '8', withShift: '*', withAltGr: '[', withShiftAltGr: '' }
            }
        };
        const service = await setup(layout, 'linux');

        chai.expect(service.detectLayoutModifiers({ key: '[', code: 'Digit8', shiftKey: true, altGraph: true }))
            .to.deep.equal('shiftAltGraph');
        chai.expect(service.detectLayoutModifiers({ key: '*', code: 'Digit8', shiftKey: true, altGraph: true }))
            .to.equal('shift');
    });

    it('passes Linux AltGraph evidence to the key validator', async () => {
        let validated: KeyValidationInput | undefined;
        const validator: KeyValidator = { validateKey: validation => validated = validation };
        const german = deGermanPc;
        const service = await setup(german, 'linux', undefined, validator);
        const input = { key: '[', code: 'Digit8', ctrlKey: true, altGraph: true, shiftKey: false };

        service.validateKeyCode(service.getKeyCodeInterpretations(input, 'code')[0], input);

        chai.expect(validated?.altGraph).to.be.true;
    });

    it('passes macOS Option evidence to the key validator', async () => {
        let validated: KeyValidationInput | undefined;
        const validator: KeyValidator = { validateKey: validation => validated = validation };
        const german = deGermanPc;
        const service = await setup(german, 'mac', undefined, validator);
        const input = { key: '[', code: 'Digit8', altKey: true, shiftKey: false };

        service.validateKeyCode(service.getKeyCodeInterpretations(input, 'code')[0], input);

        chai.expect(validated?.altGraph).to.be.true;
    });

    it('passes emulated Windows AltGraph evidence to the key validator', async () => {
        let validated: KeyValidationInput | undefined;
        const validator: KeyValidator = { validateKey: validation => validated = validation };
        const german = deGermanPc;
        const service = await setup(german, 'win', undefined, validator);
        const input = { key: '[', code: 'Digit8', ctrlKey: true, altKey: true, shiftKey: false };

        service.validateKeyCode(service.getKeyCodeInterpretations(input, 'code')[0], input);

        chai.expect(validated?.altGraph).to.be.true;
    });

    it('does not treat excluded or non-printable keys as layout modifier', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'native-shaped', lang: 'en' },
            mapping: {
                Space: { value: ' ', withShift: ' ', withAltGr: ' ', withShiftAltGr: ' ' },
                Numpad1: { value: '1', withShift: '1', withAltGr: '¹', withShiftAltGr: '¹' }
            }
        };
        const service = await setup(layout, 'linux');

        chai.expect(service.detectLayoutModifiers({ key: ' ', code: 'Space', shiftKey: true })).to.be.undefined;
        chai.expect(service.detectLayoutModifiers({ key: '¹', code: 'Numpad1', altGraph: true })).to.be.undefined;
    });

    it('ingests all Windows layout modifier layers across representative PC layouts', async () => {
        const fixtures = [
            { layout: deGermanPc, assertions: [['²', Key.DIGIT2, false, true], ['ẞ', Key.MINUS, true, true]] },
            { layout: frFrenchPc, assertions: [['€', Key.KEY_E, false, true]] },
            { layout: deSwissGermanPc, assertions: [['@', Key.DIGIT2, false, true]] },
            { layout: frBepoPc, assertions: [['Æ', Key.KEY_A, true, true]] }
        ] as const;

        for (const fixture of fixtures) {
            const service = await setup(fixture.layout, 'win');
            for (const [character, key, shift, altGraph] of fixture.assertions) {
                const resolved = service.resolveKeyCode(KeyCode.parse(character));
                chai.expect(resolved.key).to.equal(key);
                chai.expect(resolved.character).to.equal(character);
                const expected = shift ? 'shiftAltGraph' : altGraph ? 'altGraph' : 'none';
                chai.expect(resolved.layoutModifiers).to.equal(expected);
            }
            stubOSX.restore();
            stubWindows.restore();
        }
        stubOSX = stubOS('isOSX', false);
        stubWindows = stubOS('isWindows', false);
    });

    it('handles missing Windows layer values defensively', async () => {
        const layout: NativeKeyboardLayout = {
            info: { id: 'missing-windows-layers', lang: 'en' },
            mapping: { KeyA: { vkey: 'VK_A', value: 'a' } as never }
        };
        const service = await setup(layout, 'win');

        chai.expect(service.resolveKeyCode(KeyCode.parse('a')).supportedByLayout).to.be.true;
        chai.expect(service.resolveKeyCode(KeyCode.parse('§')).supportedByLayout).to.be.false;
    });

    it('resolves logical plus on US, German, and macOS layouts', async () => {
        const fixtures = [
            { layout: enUSPc, system: 'win' as const, key: Key.EQUAL, shift: true },
            { layout: deGermanPc, system: 'win' as const, key: Key.BRACKET_RIGHT, shift: false },
            { layout: enUSMac, system: 'mac' as const, key: Key.EQUAL, shift: true }
        ];
        for (const fixture of fixtures) {
            const service = await setup(fixture.layout, fixture.system);
            const resolved = service.resolveKeyCode(KeyCode.parse('[char:0x2B]'));
            chai.expect(resolved.key).to.equal(fixture.key);
            chai.expect(resolved.layoutModifiers === 'shift' || resolved.layoutModifiers === 'shiftAltGraph').to.equal(fixture.shift);
            stubOSX.restore();
            stubWindows.restore();
        }
        stubOSX = stubOS('isOSX', false);
        stubWindows = stubOS('isWindows', false);
    });

    it('resolves correct key bindings with German Windows layout', async () => {
        const winGerman = deGermanPc;
        const service = await setup(winGerman, 'win');

        const toggleComment = service.resolveKeyCode(KeyCode.createKeyCode('Slash+M1'));
        chai.expect(toggleComment.toString()).to.equal('ctrl+7');
        chai.expect(toggleComment.character).to.equal('/');
        chai.expect(toggleComment.layoutModifiers).to.deep.equal('shift');
        chai.expect(service.getKeyboardCharacter(toggleComment.key!)).to.equal('7');

        const indentLine = service.resolveKeyCode(KeyCode.createKeyCode('BracketRight+M1'));
        chai.expect(indentLine.toString()).to.equal('ctrl+9');
        chai.expect(indentLine.character).to.equal(']');
        chai.expect(indentLine.layoutModifiers).to.deep.equal('altGraph');
        chai.expect(service.getKeyboardCharacter(indentLine.key!)).to.equal('9');
    });

    it('resolves correct key bindings with French Windows layout', async () => {
        const winFrench = frFrenchPc;
        const service = await setup(winFrench, 'win');

        const toggleComment = service.resolveKeyCode(KeyCode.createKeyCode('Slash+M1'));
        chai.expect(toggleComment.toString()).to.equal('ctrl+.');
        chai.expect(toggleComment.character).to.equal('/');
        chai.expect(toggleComment.layoutModifiers).to.deep.equal('shift');
        chai.expect(service.getKeyboardCharacter(toggleComment.key!)).to.equal(':');

        const indentLine = service.resolveKeyCode(KeyCode.createKeyCode('BracketRight+M1'));
        chai.expect(indentLine.toString()).to.equal('ctrl+-');
        chai.expect(indentLine.character).to.equal(']');
        chai.expect(indentLine.layoutModifiers).to.deep.equal('altGraph');
        chai.expect(service.getKeyboardCharacter(indentLine.key!)).to.equal(')');
    });

});
