// *****************************************************************************
// Copyright (C) 2025 EclipseSource GmbH.
//
// 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 { enableJSDOM } from '@theia/core/lib/browser/test/jsdom';
let disableJSDOM = enableJSDOM();
import { FrontendApplicationConfigProvider } from '@theia/core/lib/browser/frontend-application-config-provider';
FrontendApplicationConfigProvider.set({});

import { expect } from 'chai';
import { CancellationTokenSource } from '@theia/core';
import {
    SuggestFileContent,
    WriteFileContent,
    SuggestFileReplacements,
    SuggestFileReplacements_Simple,
    WriteFileReplacements,
    WriteFileReplacements_Simple,
    ClearFileChanges,
    GetProposedFileState,
    ReplaceContentInFileFunctionHelper,
    FileChangeSetTitleProvider,
    DefaultFileChangeSetTitleProvider,
    ReplaceContentInFileFunctionHelperV2
} from './file-changeset-functions';
import { ChatToolContext, MutableChatRequestModel, MutableChatResponseModel, MutableChatModel } from '@theia/ai-chat';
import { ChangeSet, ChangeSetElement } from '@theia/ai-chat/lib/common/change-set';
import { Container } from '@theia/core/shared/inversify';
import { WorkspaceFunctionScope } from './workspace-functions';
import { FileService } from '@theia/filesystem/lib/browser/file-service';
import { ChangeSetFileElementFactory, ChangeSetFileElement } from '@theia/ai-chat/lib/browser/change-set-file-element';
import { URI } from '@theia/core/lib/common/uri';

disableJSDOM();

describe('File Changeset Functions Cancellation Tests', () => {
    let cancellationTokenSource: CancellationTokenSource;
    let mockCtx: ChatToolContext;
    let container: Container;
    before(() => {
        disableJSDOM = enableJSDOM();
    });
    after(() => {
        // Disable JSDOM after all tests
        disableJSDOM();
    });
    beforeEach(() => {
        cancellationTokenSource = new CancellationTokenSource();

        // Create a mock change set that doesn't do anything
        const mockChangeSet: Partial<ChangeSet> = {
            addElements: (...elements: ChangeSetElement[]) => true,
            setTitle: () => { },
            removeElements: () => true,
            getElementByURI: () => undefined
        };

        // Setup mock context
        const mockRequest = {
            id: 'test-request-id',
            session: {
                id: 'test-session-id',
                changeSet: mockChangeSet as ChangeSet
            } as MutableChatModel
        } as MutableChatRequestModel;
        mockCtx = {
            cancellationToken: cancellationTokenSource.token,
            request: mockRequest,
            response: {} as MutableChatResponseModel
        };

        // Create a new container for each test
        container = new Container();

        // Mock dependencies
        const mockWorkspaceScope = {
            resolveRelativePath: () => new URI('file:///workspace/test.txt')
        } as unknown as WorkspaceFunctionScope;

        const mockFileService = {
            exists: async () => true,
            read: async () => ({ value: { toString: () => 'test content' } })
        } as unknown as FileService;

        const mockFileChangeFactory: ChangeSetFileElementFactory = () => ({
            uri: new URI('file:///workspace/test.txt'),
            type: 'modify',
            state: 'pending',
            targetState: 'new content',
            apply: async () => { },
        } as ChangeSetFileElement);

        // Register mocks in the container
        container.bind(WorkspaceFunctionScope).toConstantValue(mockWorkspaceScope);
        container.bind(FileService).toConstantValue(mockFileService);
        container.bind(ChangeSetFileElementFactory).toConstantValue(mockFileChangeFactory);
        container.bind(FileChangeSetTitleProvider).to(DefaultFileChangeSetTitleProvider).inSingletonScope();
        container.bind(ReplaceContentInFileFunctionHelper).toSelf();
        container.bind(SuggestFileContent).toSelf();
        container.bind(WriteFileContent).toSelf();
        container.bind(SuggestFileReplacements_Simple).toSelf();
        container.bind(SuggestFileReplacements).toSelf();
        container.bind(WriteFileReplacements_Simple).toSelf();
        container.bind(WriteFileReplacements).toSelf();
        container.bind(ClearFileChanges).toSelf();
        container.bind(GetProposedFileState).toSelf();
        container.bind(ReplaceContentInFileFunctionHelperV2).toSelf();
    });

    afterEach(() => {
        cancellationTokenSource.dispose();
    });

    it('SuggestFileContent should respect cancellation token', async () => {
        const suggestFileContent = container.get(SuggestFileContent);
        cancellationTokenSource.cancel();

        const handler = suggestFileContent.getTool().handler;
        const result = await handler(JSON.stringify({ path: 'test.txt', content: 'test content' }), mockCtx);

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('WriteFileContent should respect cancellation token', async () => {
        const writeFileContent = container.get(WriteFileContent);
        cancellationTokenSource.cancel();

        const handler = writeFileContent.getTool().handler;
        const result = await handler(JSON.stringify({ path: 'test.txt', content: 'test content' }), mockCtx);

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('SuggestFileReplacements_Simple should respect cancellation token', async () => {
        const suggestFileReplacementsSimple = container.get(SuggestFileReplacements_Simple);
        cancellationTokenSource.cancel();

        const handler = suggestFileReplacementsSimple.getTool().handler;
        const result = await handler(
            JSON.stringify({
                path: 'test.txt',
                replacements: [{ oldContent: 'old', newContent: 'new' }]
            }),
            mockCtx
        );

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('WriteFileReplacements_Simple should respect cancellation token', async () => {
        const writeFileReplacementsSimple = container.get(WriteFileReplacements_Simple);
        cancellationTokenSource.cancel();

        const handler = writeFileReplacementsSimple.getTool().handler;
        const result = await handler(
            JSON.stringify({
                path: 'test.txt',
                replacements: [{ oldContent: 'old', newContent: 'new' }]
            }),
            mockCtx
        );

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('WriteFileReplacements should respect cancellation token with V2 implementation', async () => {
        const writeFileReplacements = container.get(WriteFileReplacements);
        cancellationTokenSource.cancel();

        const handler = writeFileReplacements.getTool().handler;
        const result = await handler(
            JSON.stringify({
                path: 'test.txt',
                replacements: [{ oldContent: 'old', newContent: 'new', multiple: true }]
            }),
            mockCtx
        );

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('WriteFileReplacements should have correct ID', () => {
        const writeFileReplacements = container.get(WriteFileReplacements);
        expect(WriteFileReplacements.ID).to.equal('writeFileReplacements');
        expect(writeFileReplacements.getTool().id).to.equal('writeFileReplacements');
    });

    it('ClearFileChanges should respect cancellation token', async () => {
        const clearFileChanges = container.get(ClearFileChanges);
        cancellationTokenSource.cancel();

        const handler = clearFileChanges.getTool().handler;
        const result = await handler(JSON.stringify({ path: 'test.txt' }), mockCtx);

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('GetProposedFileState should respect cancellation token', async () => {
        const getProposedFileState = container.get(GetProposedFileState);
        cancellationTokenSource.cancel();

        const handler = getProposedFileState.getTool().handler;
        const result = await handler(JSON.stringify({ path: 'test.txt' }), mockCtx);

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('ReplaceContentInFileFunctionHelper should handle cancellation in common processing', async () => {
        const helper = container.get(ReplaceContentInFileFunctionHelper);
        cancellationTokenSource.cancel();

        // Test the underlying helper method through the public methods

        const result = await helper.createChangesetFromToolCall(
            JSON.stringify({
                path: 'test.txt',
                replacements: [{ oldContent: 'old', newContent: 'new' }]
            }),
            mockCtx
        );
        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');

    });

    it('SuggestFileReplacements should respect cancellation token with V2 implementation', async () => {
        const suggestFileReplacements = container.get(SuggestFileReplacements);
        cancellationTokenSource.cancel();

        const handler = suggestFileReplacements.getTool().handler;
        const result = await handler(
            JSON.stringify({
                path: 'test.txt',
                replacements: [{ oldContent: 'old', newContent: 'new', multiple: true }]
            }),
            mockCtx
        );

        const jsonResponse = typeof result === 'string' ? JSON.parse(result) : result;
        expect(jsonResponse.error).to.equal('Operation cancelled by user');
    });

    it('SuggestFileReplacements should have correct ID', () => {
        const suggestFileReplacements = container.get(SuggestFileReplacements);
        expect(SuggestFileReplacements.ID).to.equal('suggestFileReplacements');
        expect(suggestFileReplacements.getTool().id).to.equal('suggestFileReplacements');
    });
});
