/**
 * @fileoverview MCP (Model Context Protocol) Management Dashboard
 *
 * Provides a comprehensive admin interface for managing MCP servers,
 * connections, tools, and viewing execution logs.
 *
 * Uses left sidebar navigation with query string deep linking via NavigationService.
 *
 * @module MCP Dashboard
 */
import { OnDestroy, ChangeDetectorRef, AfterViewInit, OnInit } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
import { BaseDashboard } from '@memberjunction/ng-shared';
import { ResourceData } from '@memberjunction/core-entities';
import { MCPToolsService, MCPSyncState } from './services/mcp-tools.service';
import * as i0 from "@angular/core";
/**
 * Interface for MCP Server data
 */
export interface MCPServerData {
    ID: string;
    Name: string;
    Description: string | null;
    TransportType: string;
    ServerURL: string | null;
    Command: string | null;
    DefaultAuthType: string;
    Status: string;
    RateLimitPerMinute: number | null;
    RateLimitPerHour: number | null;
    LastSyncAt: Date | null;
    ConnectionCount?: number;
    ToolCount?: number;
    OAuthIssuerURL?: string | null;
    OAuthScopes?: string | null;
    OAuthMetadataCacheTTLMinutes?: number | null;
    OAuthClientID?: string | null;
    OAuthClientSecretEncrypted?: string | null;
    OAuthRequirePKCE?: boolean;
}
/**
 * Interface for MCP Connection data
 */
export interface MCPConnectionData {
    ID: string;
    MCPServerID: string;
    ServerName?: string;
    Name: string;
    Description: string | null;
    Status: string;
    CompanyID: string | null;
    CredentialID: string | null;
    AutoSyncTools: boolean;
    LogToolCalls: boolean;
    LastConnectedAt: Date | null;
    LastErrorMessage: string | null;
}
/**
 * Interface for MCP Tool data
 */
export interface MCPToolData {
    ID: string;
    MCPServerID: string;
    ServerName?: string;
    ToolName: string;
    ToolTitle: string | null;
    ToolDescription: string | null;
    InputSchema: string;
    Status: string;
    DiscoveredAt: Date;
    LastSeenAt: Date;
}
/**
 * Interface for server group (tools grouped by server)
 */
export interface MCPServerGroup {
    server: MCPServerData;
    tools: MCPToolData[];
    expanded: boolean;
}
/**
 * MCP tool summary returned by paginated GraphQL query (Part 3.2 scale path).
 * Omits heavy fields like InputSchema so thousands of rows stay light.
 */
export interface MCPToolSummary {
    ID: string;
    MCPServerID: string;
    ToolName: string;
    ToolTitle: string | null;
    ToolDescription: string | null;
    Status: string;
    ServerName: string | null;
}
/**
 * Tools view mode
 */
export type ToolsViewMode = 'card' | 'list';
/**
 * Tools sort options
 */
export type ToolsSortBy = 'name' | 'server' | 'discovered' | 'lastSeen';
/**
 * Interface for MCP Execution Log data
 */
export interface MCPExecutionLogData {
    ID: string;
    ConnectionID: string;
    ConnectionName?: string;
    ToolID: string | null;
    ToolName: string;
    Status: string;
    StartedAt: Date;
    CompletedAt: Date | null;
    DurationMs: number | null;
    UserID: string;
    UserName?: string;
    ErrorMessage: string | null;
    InputArgs?: string | null;
    Result?: string | null;
    ServerName?: string;
}
/**
 * Dashboard filter options
 */
export interface MCPDashboardFilters {
    searchTerm: string;
    serverStatus: string;
    connectionStatus: string;
    toolStatus: string;
    logStatus: string;
    /** Part 3.3 — tools tab server filter (ID of selected server, or 'all') */
    toolsServer?: string;
    /** Part 3.3 — tools tab category filter (derived from snake_case ToolName prefix, or 'all') */
    toolsCategory?: string;
    /** Part 3.6 — restrict Tools tab to favorited tools only */
    favoritesOnly?: boolean;
    /** Part 3.3 — restrict Tools tab to tools that appear in recent execution logs */
    recentOnly?: boolean;
}
/**
 * Dashboard statistics
 */
export interface MCPDashboardStats {
    totalServers: number;
    activeServers: number;
    totalConnections: number;
    activeConnections: number;
    totalTools: number;
    activeTools: number;
    recentExecutions: number;
    failedExecutions: number;
}
/**
 * Active tab type
 */
export type MCPDashboardTab = 'servers' | 'connections' | 'tools' | 'logs';
/** Parameter config for the inline test tool form */
interface TestParamConfig {
    name: string;
    type: string;
    description: string;
    required: boolean;
    enumValues: unknown[];
}
/**
 * MCP Management Dashboard Component
 *
 * Provides a tab-based interface for managing:
 * - MCP Servers
 * - MCP Connections
 * - MCP Tools
 * - Execution Logs
 */
export declare class MCPDashboardComponent extends BaseDashboard implements OnInit, AfterViewInit, OnDestroy {
    private cdr;
    private mcpToolsService;
    private readonly USER_SETTINGS_KEY;
    private settingsPersistSubject;
    private settingsLoaded;
    private metadata;
    servers: MCPServerData[];
    connections: MCPConnectionData[];
    tools: MCPToolData[];
    executionLogs: MCPExecutionLogData[];
    filteredServers: MCPServerData[];
    filteredConnections: MCPConnectionData[];
    filteredTools: MCPToolData[];
    filteredLogs: MCPExecutionLogData[];
    /** Part 3.2 — paginated tools (scales to thousands). Appended as user scrolls. */
    pagedTools: MCPToolSummary[];
    toolsTotalCount: number;
    toolsLoading: boolean;
    toolsSkip: number;
    toolsPageSize: number;
    useScalablePagination: boolean;
    /** Part 3.6 — favorited tool IDs for the current user. */
    favoritedToolIDs: Set<string>;
    /** Part 3.5 — Test dialog search string for tool combobox-style filter */
    TestToolSearch: string;
    /** Part 3.3 — derived data for the filter panel */
    toolsAvailableServers: Array<{
        ID: string;
        Name: string;
    }>;
    toolsAvailableCategories: Array<{
        category: string;
        count: number;
    }>;
    /** Part 3.4 — tool counts from GetMCPToolCounts (global, respects search) */
    toolsGlobalCount: number;
    /** Per-server tool count map used for "(N tools)" badge on group headers */
    toolCountByServer: Record<string, number>;
    /** Part 3.4 — auto-collapse threshold for server groups */
    readonly AUTO_COLLAPSE_THRESHOLD = 100;
    stats: MCPDashboardStats;
    ActiveTab: MCPDashboardTab;
    IsLoading: boolean;
    ErrorMessage: string | null;
    filters$: BehaviorSubject<MCPDashboardFilters>;
    ShowServerDialog: boolean;
    ShowConnectionDialog: boolean;
    ShowTestToolDialog: boolean;
    EditingServer: MCPServerData | null;
    EditingConnection: MCPConnectionData | null;
    ServerForm: {
        Name: string;
        Description: string;
        TransportType: string;
        ServerURL: string;
        Command: string;
        DefaultAuthType: string;
        Status: string;
        RateLimitPerMinute: number | null;
        RateLimitPerHour: number | null;
        RequestTimeoutMs: number;
    };
    ServerFormSaving: boolean;
    ServerFormError: string | null;
    readonly TransportTypes: {
        value: string;
        label: string;
    }[];
    readonly AuthTypes: {
        value: string;
        label: string;
    }[];
    ConnectionForm: {
        MCPServerID: string;
        Name: string;
        Description: string;
        BearerToken: string;
        Status: string;
    };
    ConnectionFormSaving: boolean;
    ConnectionFormError: string | null;
    TestStep: 'select' | 'configure' | 'results';
    TestToolServerID: string | null;
    TestToolConnectionID: string | null;
    TestToolID: string | null;
    TestFilteredConnections: MCPConnectionData[];
    TestFilteredTools: MCPToolData[];
    TestSelectedTool: MCPToolData | null;
    TestParamConfigs: TestParamConfig[];
    TestParamValues: Record<string, string>;
    TestIsExecuting: boolean;
    TestExecutionResult: {
        Success: boolean;
        ErrorMessage?: string;
        Result?: string;
        DurationMs?: number;
    } | null;
    ShowLogDetailPanel: boolean;
    SelectedLog: MCPExecutionLogData | null;
    ExpandedServerID: string | null;
    ExpandedConnectionID: string | null;
    LogsSortColumn: 'status' | 'server' | 'tool' | 'connection' | 'started' | 'duration' | 'error';
    LogsSortAscending: boolean;
    ToolsViewMode: ToolsViewMode;
    ToolsSortBy: ToolsSortBy;
    ToolsSortAscending: boolean;
    ServerGroups: MCPServerGroup[];
    ExpandedToolId: string | null;
    SyncStates: Map<string, MCPSyncState>;
    private syncSubscriptions;
    FilterPanelVisible: boolean;
    protected destroy$: Subject<void>;
    constructor(cdr: ChangeDetectorRef, mcpToolsService: MCPToolsService);
    ngOnInit(): Promise<void>;
    /**
     * Called by the framework when the URL query params change due to
     * browser back/forward navigation or a deep link.
     */
    protected OnQueryParamsChanged(params: Record<string, string>, source: 'popstate' | 'deeplink'): void;
    /**
     * Validates that a tab value is a valid MCPDashboardTab
     */
    private isValidTab;
    /**
     * Applies configuration params passed via NavigationService
     */
    private applyConfigurationParams;
    /**
     * Load saved user preferences from the UserInfoEngine
     */
    private loadUserPreferences;
    /**
     * Apply loaded preferences to component state
     */
    private applyUserPreferencesFromStorage;
    /**
     * Get current preferences as an object for saving
     */
    private getCurrentPreferences;
    /**
     * Persist user preferences to storage (debounced)
     */
    private saveUserPreferencesDebounced;
    /**
     * Actually persist user preferences to the UserInfoEngine
     */
    private persistUserPreferences;
    GetResourceDisplayName(data: ResourceData): Promise<string>;
    GetResourceIconClass(data: ResourceData): Promise<string>;
    protected initDashboard(): void;
    protected loadData(): void;
    ngAfterViewInit(): void;
    ngOnDestroy(): void;
    /**
     * Loads all dashboard data using MCPEngine for cached entities
     * and RunView for execution logs (historical data loaded on-demand)
     * @param forceRefresh - If true, forces MCPEngine to reload from database (use after sync operations)
     */
    loadAllData(forceRefresh?: boolean): Promise<void>;
    private enrichServerData;
    private enrichConnectionData;
    private enrichToolData;
    private enrichLogData;
    /**
     * Maps database log entity to UI interface format
     * Handles column name differences between DB schema and UI interface
     */
    private mapLogFromDatabase;
    private calculateStats;
    private setupFilterSubscription;
    applyFilters(): void;
    onSearchChange(term: string): void;
    onStatusFilterChange(filterType: string, value: string): void;
    /**
     * Toggle filter panel visibility
     */
    toggleFilterPanel(): void;
    /**
     * Handle filter changes from the filter panel component
     */
    onFiltersChange(filters: MCPDashboardFilters): void;
    /** Inlined filter panel — single-field update helper */
    onFilterFieldChange(field: keyof MCPDashboardFilters, value: unknown): void;
    /** Count of non-default filter dimensions, used for "Filters (N)" badge */
    activeFilterCount(): number;
    /** Derive category list (snake_case prefix) + counts from the currently loaded tools. */
    computeCategoriesFromTools(): Array<{
        category: string;
        count: number;
    }>;
    resetAllFilters(): void;
    /** Reset only the popover filters — leave searchTerm (toolbar) untouched. */
    resetPopoverFilters(): void;
    /** Tools-tab view-mode options for the shared <mj-view-toggle>. */
    readonly toolsViewOptions: {
        key: string;
        icon: string;
        title: string;
    }[];
    /** Tab config consumed by the centralized <mj-tab-nav>. */
    get mcpTabs(): import('@memberjunction/ng-ui-components').TabConfig[];
    /** Active filter count excluding searchTerm (surfaced separately via toolbar mj-page-search). */
    get ActiveFilterCount(): number;
    /** Values record consumed by the centralized <mj-filter-panel>, scoped to the current tab. */
    get mcpFilterValues(): Record<string, unknown>;
    /** Field config built dynamically based on the active tab. */
    get mcpFilterFields(): import('@memberjunction/ng-ui-components').FilterFieldConfig[];
    /** Receive updated values from <mj-filter-panel> and propagate to filters$. */
    onFilterValuesChange(values: Record<string, unknown>): void;
    /** Update searchTerm from the toolbar mj-page-search. */
    onSearchTermChange(value: string): void;
    /**
     * Get the current filtered count based on active tab
     */
    get CurrentFilteredCount(): number;
    /**
     * Get the total count based on active tab
     */
    get CurrentTotalCount(): number;
    /**
     * Get current filters value (non-observable)
     */
    get CurrentFilters(): MCPDashboardFilters;
    /**
     * Sets the active tab and updates URL for deep linking
     */
    setActiveTab(tab: MCPDashboardTab): void;
    createServer(): void;
    editServer(server: MCPServerData): void;
    deleteServer(server: MCPServerData): Promise<void>;
    /**
     * Internal helper to delete a tool by ID without confirmation
     */
    private deleteToolInternal;
    /**
     * Internal helper to delete a connection by ID without confirmation.
     * Handles deletion of all related records that don't have ON DELETE CASCADE:
     * - MCP Tool Execution Logs
     * - OAuth Authorization States
     * - OAuth Client Registrations
     * - OAuth Tokens
     */
    private deleteConnectionInternal;
    onServerDialogClose(result: {
        saved: boolean;
    }): Promise<void>;
    cancelServerForm(): void;
    saveServerForm(): Promise<void>;
    createConnection(): void;
    cancelConnectionForm(): void;
    saveConnectionForm(): Promise<void>;
    editConnection(connection: MCPConnectionData): void;
    deleteConnection(connection: MCPConnectionData): Promise<void>;
    onConnectionDialogClose(result: {
        saved: boolean;
    }): Promise<void>;
    /**
     * Toggle tool card expansion for details view
     */
    toggleToolExpand(tool: MCPToolData): void;
    /**
     * Check if a tool card is expanded
     */
    isToolExpanded(tool: MCPToolData): boolean;
    /**
     * Set tools view mode (card or list)
     */
    setToolsViewMode(mode: ToolsViewMode): void;
    /**
     * Set tools sort option
     */
    setToolsSort(sortBy: ToolsSortBy): void;
    /**
     * Toggle server group expansion
     */
    toggleServerGroup(group: MCPServerGroup): void;
    /**
     * Build server groups from tools data
     */
    private buildServerGroups;
    /**
     * Sort tools array in place
     */
    private sortTools;
    /**
     * Get total tool count across all groups
     */
    get TotalToolCount(): number;
    /**
     * Open Test Tool dialog
     */
    openTestToolDialog(tool?: MCPToolData, connection?: MCPConnectionData): void;
    /**
     * Close Test Tool dialog
     */
    onTestToolDialogClose(): void;
    private testUpdateFilteredLists;
    onTestServerChange(value: string): void;
    onTestConnectionChange(value: string): void;
    onTestToolSelectChange(value: string): void;
    get TestCanProceed(): boolean;
    testProceedToConfig(): void;
    private testParseSchema;
    testSetParam(name: string, value: string): void;
    get TestIsValid(): boolean;
    testExecuteTool(): Promise<void>;
    testGoBack(): void;
    testRunAgain(): void;
    testCloseDialog(): void;
    formatTestResult(result: unknown): string;
    /**
     * Part 3.2 — loads a page of tools via the paginated resolver.
     * Uses the same GraphQLDataProvider + gql pattern as testExecuteTool above.
     */
    loadToolsPage(reset?: boolean): Promise<void>;
    onToolsScrolledIndexChange(index: number): void;
    /** Native-scroll infinite-load: triggers next page when user nears the bottom */
    onToolsScrollNative(event: Event): void;
    toggleScalableMode(enabled: boolean): void;
    /**
     * Part 3.4 — fetch global + per-server + per-category counts (used for badges
     * and to populate the category filter dropdown). Respects current search filter.
     */
    loadToolCounts(): Promise<void>;
    /** Part 3.4 — returns tool count for a server (falls back to ServerGroups length for legacy view) */
    getServerToolCount(serverID: string): number;
    trackPagedTool(_index: number, tool: MCPToolSummary): string;
    /** Part 3.6 — Scale mode display. When a client-side filter (Favorites/Recently-used) is active,
     *  bypass server pagination and filter the fully-loaded local `this.tools` list so the filter
     *  considers ALL tools, not just the current 50-row page. */
    get visiblePagedTools(): MCPToolSummary[];
    /** Scale-mode denominator. In bypass-pagination mode (favorites/recent filters), the user
     *  sees the fully filtered local list, so the "of N" reflects that filtered total.
     *  Otherwise we show the server-side total for the current query. */
    scaleDenominator(): number;
    /** Part 3.5 — recently used tool IDs derived from execution logs (dedup, max 5) */
    get TestRecentToolIDs(): string[];
    /** Part 3.5 — Test dialog combobox: filtered tools with recent-first ordering */
    get TestComboboxTools(): MCPToolData[];
    isRecentTestTool(toolID: string): boolean;
    onTestToolSearchChange(value: string): void;
    pickTestTool(toolID: string): void;
    /**
     * Part 3.6 — load the current user's favorited tool IDs.
     */
    loadFavorites(): Promise<void>;
    isFavorited(toolID: string): boolean;
    /** Part 3.3 — set of tool IDs seen in recent execution logs (last N unique). */
    recentToolIDSet(): Set<string>;
    toggleFavorite(toolID: string, event?: Event): Promise<void>;
    formatLogJson(value: string | null | undefined): string;
    /**
     * Parse and return input schema as formatted JSON
     */
    getFormattedInputSchema(tool: MCPToolData): string;
    /**
     * Get parameter count from input schema
     */
    getParamCount(tool: MCPToolData): number;
    /**
     * Get required parameter count from input schema
     */
    getRequiredParamCount(tool: MCPToolData): number;
    /**
     * Syncs tools for a specific connection
     */
    syncConnectionTools(connection: MCPConnectionData): Promise<void>;
    /**
     * Gets the sync state for a connection
     */
    getSyncState(connectionId: string): MCPSyncState | undefined;
    /**
     * Checks if a connection is currently syncing
     */
    isSyncing(connectionId: string): boolean;
    /**
     * Gets sync progress message for a connection
     */
    getSyncProgressMessage(connectionId: string): string;
    /**
     * Checks for OAuth completion by looking for query params set by the OAuth callback
     */
    private checkOAuthCompletion;
    /**
     * Shows a success notification (temporary)
     */
    private showSuccessNotification;
    /**
     * Initiates OAuth authorization flow for a connection.
     * Stores the current URL and redirects directly to the OAuth provider.
     * Always uses the frontend callback URL so the OAuth redirect comes back to MJExplorer.
     *
     * @param connectionId - The MCP connection ID requiring OAuth
     */
    initiateOAuthFlow(connectionId: string): Promise<void>;
    /**
     * Calls the InitiateMCPOAuth mutation with frontend callback URL
     */
    private initiateMCPOAuth;
    getStatusClass(status: string): string;
    getTransportIcon(transportType: string): string;
    formatDate(date: Date | string | null): string;
    formatDuration(ms: number | null): string;
    /**
     * Handles click on a sortable column header
     */
    onLogSortColumn(column: typeof this.LogsSortColumn): void;
    /**
     * Sorts the filtered logs based on current sort settings
     */
    private sortFilteredLogs;
    /**
     * Gets the sort indicator class for a column header
     */
    getLogSortClass(column: typeof this.LogsSortColumn): string;
    /**
     * Handles click on a log row to show detail panel
     */
    onLogClick(log: MCPExecutionLogData): Promise<void>;
    /**
     * Closes the log detail panel
     */
    onLogDetailClose(): void;
    /**
     * Handles run again from log detail panel
     */
    onRunAgainFromLog(event: {
        toolId: string;
        connectionId: string;
    }): void;
    /**
     * Toggles server card expansion
     */
    toggleServerExpand(server: MCPServerData): void;
    /**
     * Toggles connection card expansion
     */
    toggleConnectionExpand(conn: MCPConnectionData): void;
    /**
     * Checks if a server card is expanded
     */
    isServerExpanded(server: MCPServerData): boolean;
    /**
     * Checks if a connection card is expanded
     */
    isConnectionExpanded(conn: MCPConnectionData): boolean;
    /**
     * Gets tools for a specific server
     */
    getToolsForServer(serverId: string): MCPToolData[];
    /**
     * Gets tools for a specific connection (via its server)
     */
    getToolsForConnection(connectionId: string): MCPToolData[];
    /**
     * Opens test tool dialog with a specific tool from expanded card
     */
    runToolFromCard(tool: MCPToolData, connection?: MCPConnectionData): void;
    static ɵfac: i0.ɵɵFactoryDeclaration<MCPDashboardComponent, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<MCPDashboardComponent, "mj-mcp-dashboard", never, {}, {}, never, never, false, never>;
}
export {};
//# sourceMappingURL=mcp-dashboard.component.d.ts.map