import CloudBase from '@cloudbase/manager-node';
import { Credential as Credential_2 } from '@cloudbase/toolbox';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

export declare const ALL_SUPPORTED_RUNTIMES: ("Nodejs20.19" | "Nodejs18.15" | "Nodejs16.13" | "Nodejs14.18" | "Nodejs12.16" | "Nodejs10.15" | "Nodejs8.9" | "Python3.10" | "Python3.9" | "Python3.7" | "Python3.6" | "Python2.7" | "Php8.0" | "Php7.4" | "Php7.2" | "Java8" | "Java11" | "Golang1")[];

export declare type AuthFlowMode = "web" | "device";

export declare interface AuthOptions {
    authMode?: AuthFlowMode;
    clientId?: string;
    oauthEndpoint?: string;
    oauthCustom?: boolean;
}

export declare type CloudBaseOptions = NonNullable<ConstructorParameters<typeof CloudBase>[0]>;

/**
 * Create a manager with the provided CloudBase options, without using cache
 * @param cloudBaseOptions Provided CloudBase options
 * @returns CloudBase manager instance
 */
export declare function createCloudBaseManagerWithOptions(cloudBaseOptions: CloudBaseOptions): CloudBase;

/**
 * Create and configure a CloudBase MCP Server instance
 * @param options Server configuration options
 * @returns Configured McpServer instance
 *
 * @example
 * import { createCloudBaseMcpServer } from "@cloudbase/mcp-server";
 * import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 *
 * const server = createCloudBaseMcpServer({ cloudBaseOptions: {
 *  envId,    // 环境ID
 *  secretId,  // 腾讯云密钥ID
 *  secretKey, // 腾讯云密钥
 *  region, // 地域，默认是 ap-shanghai
 *  token // 临时密钥，有有效期限制，生成密钥时可控制
 * } });
 *
 * const transport = new StdioServerTransport();
 * await server.connect(transport);
 */
export declare function createCloudBaseMcpServer(options?: {
    name?: string;
    version?: string;
    enableTelemetry?: boolean;
    cloudBaseOptions?: CloudBaseOptions;
    authOptions?: AuthOptions;
    cloudMode?: boolean;
    ide?: string;
    logger?: Logger;
    pluginsEnabled?: string[];
    pluginsDisabled?: string[];
}): Promise<ExtendedMcpServer>;

export declare interface DataModel {
    id?: string;
    name: string;
    title: string;
    schema: DataModelSchema;
    envId?: string;
    status?: 'draft' | 'published';
    createdAt?: string;
    updatedAt?: string;
}

export declare interface DataModelField {
    name: string;
    type: 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object' | 'objectId' | 'file' | 'image';
    required?: boolean;
    default?: any;
    description?: string;
    validation?: {
        min?: number;
        max?: number;
        pattern?: string;
        enum?: any[];
    };
}

export declare interface DataModelSchema {
    type: 'object';
    properties: Record<string, {
        type: string;
        description?: string;
        required?: boolean;
        default?: any;
        validation?: any;
    }>;
    required?: string[];
}

export declare const DEFAULT_NODEJS_RUNTIME = "Nodejs18.15";

export declare const DEFAULT_RUNTIME = "Nodejs18.15";

export declare interface DeleteFileParams {
    cloudPath: string;
}

export declare interface DeviceFlowAuthInfo {
    user_code: string;
    verification_uri?: string;
    device_code: string;
    expires_in: number;
}

/**
 * Enable cloud mode by setting environment variable
 */
export declare function enableCloudMode(): void;

export declare interface EnsureLoginOptions extends AuthOptions {
    fromCloudBaseLoginPage?: boolean;
    ignoreEnvVars?: boolean;
    region?: string;
    serverAuthOptions?: AuthOptions;
    onDeviceCode?: (info: DeviceFlowAuthInfo) => void;
}

declare class EnvironmentManager {
    private cachedEnvId;
    private envIdPromise;
    reset(): void;
    getEnvId(): Promise<string>;
    private _fetchEnvId;
    private _setCachedEnvId;
    setEnvId(envId: string): Promise<void>;
    getCachedEnvId(): string | null;
}

export declare const envManager: EnvironmentManager;

export declare const error: (message: string, data?: object | Error) => void;

export declare interface ExtendedMcpServer extends McpServer {
    cloudBaseOptions?: CloudBaseOptions;
    authOptions?: AuthOptions;
    ide?: string;
    logger?: Logger;
    setLogger(logger: Logger): void;
}

export declare function formatRuntimeList(): string;

/**
 * 每次都实时获取最新的 token/secretId/secretKey
 */
export declare function getCloudBaseManager(options?: GetManagerOptions): Promise<CloudBase>;

/**
 * Get cloud mode status for logging/debugging
 */
export declare function getCloudModeStatus(): {
    enabled: boolean;
    source: string | null;
};

/**
 * Get the default configured CloudBase MCP Server
 */
export declare function getDefaultServer(): Promise<ExtendedMcpServer>;

export declare function getEnvId(cloudBaseOptions?: CloudBaseOptions): Promise<string>;

export declare interface GetFileInfoParams {
    cloudPath: string;
}

/**
 * Get interactive server instance (CommonJS compatible)
 */
export declare function getInteractiveServerAsync(): Promise<InteractiveServer>;

export declare function getLoginState(options?: EnsureLoginOptions): Promise<{
    secretId: string;
    secretKey: string;
    token: string | undefined;
    envId: string | undefined;
} | Credential_2>;

declare interface GetManagerOptions {
    requireEnvId?: boolean;
    cloudBaseOptions?: CloudBaseOptions;
    mcpServer?: any;
    authStrategy?: 'fail_fast' | 'ensure';
}

declare interface IdeFileDescriptor {
    path: string;
    isMcpConfig?: boolean;
}

export declare const info: (message: string, data?: object | Error) => void;

export declare interface InteractiveResult {
    type: "envId" | "clarification" | "confirmation";
    data: any;
    cancelled?: boolean;
    switch?: boolean;
    timeout?: boolean;
    timeoutDuration?: number;
}

declare class InteractiveServer {
    private app;
    private server;
    private wss;
    private port;
    private isRunning;
    private currentResolver;
    private sessionData;
    private _mcpServer;
    get mcpServer(): any;
    set mcpServer(server: any);
    private readonly DEFAULT_PORT;
    private readonly FALLBACK_PORTS;
    /** Idle timeout for HTTP/WS connections (e.g. long login). Avoids "connection disconnected" after ~1 min. */
    private static readonly SERVER_IDLE_MS;
    /** WebSocket ping interval to keep connection alive past proxies/firewalls. */
    private static readonly WS_PING_INTERVAL_MS;
    constructor(mcpServer?: any);
    private cleanup;
    /** Apply timeouts so long-lived login does not cause "connection disconnected". */
    private applyServerTimeouts;
    private setupExpress;
    private setupWebSocket;
    start(): Promise<number>;
    stop(): Promise<void>;
    collectEnvId(availableEnvs: any[], accountInfo?: {
        uin?: string;
    }, errorContext?: any, // EnvSetupContext
    manager?: any, // CloudBase manager instance for refreshing env list
    mcpServer?: any): Promise<InteractiveResult>;
    clarifyRequest(message: string, options?: string[]): Promise<InteractiveResult>;
    private escapeHtml;
    private getEnvSetupHTML;
    private getEnvSetupHTML_OLD;
    private getClarificationHTML;
    private getConfirmationHTML;
    get running(): boolean;
    get currentPort(): number;
}

/**
 * Check if MCP is running in cloud mode
 * Cloud mode is enabled by:
 * 1. Command line argument --cloud-mode
 * 2. Environment variable CLOUDBASE_MCP_CLOUD_MODE=true
 * 3. Environment variable MCP_CLOUD_MODE=true
 */
export declare function isCloudMode(): boolean;

export declare interface ListFilesParams {
    prefix: string;
    marker?: string;
}

declare type Logger = (data: {
    type: string;
    requestId?: string;
    result?: any;
    toolName?: string;
    args?: any;
    message?: string;
    duration?: number;
    [key: string]: any;
}) => void;

export declare function logout(): Promise<void>;

export { McpServer }

export declare const RAW_IDE_FILE_MAPPINGS: Record<string, IdeFileDescriptor[]>;

export declare const RECOMMENDED_RUNTIMES: {
    readonly nodejs: "Nodejs18.15";
    readonly python: "Python3.9";
    readonly php: "Php7.4";
    readonly java: "Java11";
    readonly golang: "Golang1";
};

export declare const reportToolCall: (params: {
    toolName: string;
    success: boolean;
    requestId?: string;
    duration?: number;
    error?: string;
    inputParams?: any;
    cloudBaseOptions?: CloudBaseOptions;
    ide?: string;
}) => Promise<void>;

export declare const reportToolkitLifecycle: (params: {
    event: "start" | "exit";
    duration?: number;
    exitCode?: number;
    error?: string;
    cloudBaseOptions?: CloudBaseOptions;
    ide?: string;
}) => Promise<void>;

export declare function resetCloudBaseManagerCache(): void;

/**
 * Check if a tool should be registered in cloud mode
 * @param toolName - The name of the tool
 * @returns true if the tool should be registered in current mode
 */
export declare function shouldRegisterTool(toolName: string): boolean;

/**
 * Simplify environment list data by keeping only essential fields for AI assistant
 * This reduces token consumption when returning environment lists via MCP tools
 * @param envList - Full environment list from API
 * @returns Simplified environment list with only essential fields
 */
export declare function simplifyEnvList(envList: any[]): any[];

export { StdioServerTransport }

export declare const SUPPORTED_NODEJS_RUNTIMES: readonly ["Nodejs20.19", "Nodejs18.15", "Nodejs16.13", "Nodejs14.18", "Nodejs12.16", "Nodejs10.15", "Nodejs8.9"];

export declare const SUPPORTED_RUNTIMES: {
    readonly nodejs: readonly ["Nodejs20.19", "Nodejs18.15", "Nodejs16.13", "Nodejs14.18", "Nodejs12.16", "Nodejs10.15", "Nodejs8.9"];
    readonly python: readonly ["Python3.10", "Python3.9", "Python3.7", "Python3.6", "Python2.7"];
    readonly php: readonly ["Php8.0", "Php7.4", "Php7.2"];
    readonly java: readonly ["Java8", "Java11"];
    readonly golang: readonly ["Golang1"];
};

/**
 * 数据上报类
 * 用于收集 MCP 工具使用情况和错误信息，帮助改进产品
 *
 * 隐私保护：
 * - 可通过环境变量 CLOUDBASE_MCP_TELEMETRY_DISABLED=true 完全关闭
 * - 不收集敏感信息（代码内容、具体文件路径等）
 * - 使用设备指纹而非真实用户信息
 * - 所有数据仅用于产品改进，不用于其他用途
 */
declare class TelemetryReporter {
    private deviceId;
    private userAgent;
    private additionalParams;
    private enabled;
    constructor();
    /**
     * 获取用户运行环境信息
     * 包含操作系统、Node版本和MCP版本等信息
     */
    getUserAgent(): {
        userAgent: string;
        deviceId: string;
        osType: string;
        osRelease: string;
        nodeVersion: string;
        arch: string;
        mcpVersion: string;
    };
    /**
     * 获取设备唯一标识
     * 基于主机名、CPU信息和MAC地址生成匿名设备指纹
     */
    private getDeviceId;
    /**
     * 发送HTTP请求
     */
    private postFetch;
    /**
     * 上报事件
     * @param eventCode 事件代码
     * @param eventData 事件数据
     */
    report(eventCode: string, eventData?: {
        [key: string]: any;
    }): Promise<void>;
    /**
     * 设置公共参数
     */
    addAdditionalParams(params: {
        [key: string]: any;
    }): void;
    /**
     * 检查是否启用
     */
    isEnabled(): boolean;
}

export declare const telemetryReporter: TelemetryReporter;

export declare interface ToolResponse {
    success: boolean;
    [key: string]: any;
}

export declare interface UploadFileParams {
    cloudPath: string;
    fileContent: string;
}

export declare const warn: (message: string, data?: object | Error) => void;

export { }
