import {
    type IFileSystem,
    type IProjectBuildOptions,
    type IProjectCleanupOptions,
    type IProjectPackOptions,
    type IProjectRestoreOptions,
    type IProjectValidateOptions,
    type IToolLogger,
    type ProjectOperationContext,
    ProjectTool,
    ToolErrorCodes,
    ToolResult,
} from "@uipath/solutionpackager-tool-core";
import type { IProjectBundleExecutor } from "./project-bundle-executor.js";

/**
 * Browser workflow compiler tool implementation.
 * Delegates pack and validate to a bundle executor that coordinates a
 * single remote-agent invocation across all compatible projects in the
 * solution via SignalR.
 */
export class WorkflowCompilerTool extends ProjectTool {
    constructor(
        fileSystem: IFileSystem,
        logger: IToolLogger,
        private readonly bundleExecutor: IProjectBundleExecutor,
        private readonly context?: ProjectOperationContext,
    ) {
        super(fileSystem, logger);
    }

    async restoreAsync(
        _options: IProjectRestoreOptions,
        _cancellationToken?: AbortSignal,
    ): Promise<ToolResult> {
        this.logger.warn(
            "Restore operation is not supported in browser environment",
        );
        return ToolResult.success();
    }

    async validateAsync(
        options: IProjectValidateOptions,
        _cancellationToken?: AbortSignal,
    ): Promise<ToolResult> {
        if (!this.context) {
            return ToolResult.error(
                ToolErrorCodes.InternalError,
                "Validate operation requires a project operation context",
            );
        }

        return this.bundleExecutor.validateAsync(options, this.context);
    }

    async buildAsync(
        _options: IProjectBuildOptions,
        _cancellationToken?: AbortSignal,
    ): Promise<ToolResult> {
        this.logger.warn(
            "Build operation is not supported in browser environment",
        );
        return ToolResult.success();
    }

    async packAsync(
        options: IProjectPackOptions,
        _cancellationToken?: AbortSignal,
    ): Promise<ToolResult> {
        if (!this.context) {
            return ToolResult.error(
                ToolErrorCodes.InternalError,
                "Pack operation requires a project operation context",
            );
        }

        return this.bundleExecutor.packAsync(options, this.context);
    }

    async cleanupAsync(
        options: IProjectCleanupOptions,
        _cancellationToken?: AbortSignal,
    ): Promise<ToolResult> {
        if (!this.context) {
            return ToolResult.error(
                ToolErrorCodes.InternalError,
                "Cleanup operation requires a project operation context",
            );
        }

        return this.bundleExecutor.cleanupAsync(options, this.context);
    }
}
