import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AlertCircle, ChevronDown, ChevronRight, CircleSlash, ExternalLink, } from "lucide-react";
import { SearchInput } from "../../../components/SearchInput";
import { SettingsPanelLayout } from "../SettingsPanelLayout";
import { cn } from "../../../lib/utils";
import { useEditContext } from "../../client/editContext";
import { LoadingState } from "../../ui/LoadingState";
import { getAgentTools, } from "../../services/systemService";
const ALL_IMPLEMENTATION_TYPES = "All";
function getErrorMessage(result) {
    return result.details || result.summary || "Failed to load agent tools.";
}
function getImplementationType(tool) {
    return tool.implementationType || "Unknown";
}
function getRegistrationLocation(tool) {
    return tool.registrationLocation || "Unknown";
}
function getRowKey(tool) {
    return `${getRegistrationLocation(tool)}:${tool.itemId ?? tool.key}:${tool.implementationKey}`;
}
function compareAgentToolsByName(first, second) {
    return (first.key.localeCompare(second.key, undefined, { sensitivity: "base" }) ||
        first.key.localeCompare(second.key) ||
        getImplementationType(first).localeCompare(getImplementationType(second)) ||
        getRegistrationLocation(first).localeCompare(getRegistrationLocation(second)));
}
function matchesQuery(tool, query) {
    if (!query)
        return true;
    const haystack = [
        tool.key,
        tool.implementationKey,
        tool.implementationClassName,
        tool.implementationFullName,
        getImplementationType(tool),
        getRegistrationLocation(tool),
        tool.shortDescription,
        tool.description,
        tool.signature,
        ...(tool.signatureParameters ?? []).flatMap((parameter) => [
            parameter.name,
            parameter.type,
            parameter.description,
            ...(parameter.enumValues ?? []),
        ]),
        tool.defaultFolderName,
        tool.itemPath,
        tool.serverName,
    ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();
    return haystack.includes(query);
}
function splitClassName(fullName) {
    const lastDot = fullName.lastIndexOf(".");
    if (lastDot < 0)
        return { namespace: "", name: fullName };
    return {
        namespace: fullName.slice(0, lastDot + 1),
        name: fullName.slice(lastDot + 1),
    };
}
function splitItemPath(path) {
    const trimmed = path.replace(/\/$/, "");
    const lastSlash = trimmed.lastIndexOf("/");
    if (lastSlash < 0)
        return { parent: "", leaf: trimmed };
    return {
        parent: trimmed.slice(0, lastSlash + 1),
        leaf: trimmed.slice(lastSlash + 1),
    };
}
function SignatureBlock({ tool }) {
    const parameters = tool.signatureParameters ?? [];
    if (parameters.length === 0) {
        return (_jsx("code", { className: "border-border-default text-neutral-grey-100 block rounded-md border bg-white px-3 py-2 font-mono text-xs leading-5 break-words whitespace-pre-wrap", children: tool.signature }));
    }
    return (_jsxs("div", { className: "border-border-default rounded-md border bg-white px-3 py-2 font-mono text-xs leading-5", children: [_jsxs("div", { className: "text-neutral-grey-100 break-all", children: [tool.key, _jsx("span", { className: "text-neutral-grey-50", children: "(" })] }), _jsx("div", { className: "space-y-1.5 py-1", children: parameters.map((parameter, index) => (_jsxs("div", { className: "pl-4", children: [_jsxs("div", { className: "break-all", children: [_jsx("span", { className: "text-neutral-grey-100", children: parameter.name }), !parameter.isRequired ? (_jsx("span", { className: "text-neutral-grey-50", children: "?" })) : null, _jsx("span", { className: "text-neutral-grey-50", children: ": " }), _jsx("span", { className: "text-component-suggestions", children: parameter.type })] }), parameter.description ? (_jsx("div", { className: "text-neutral-grey-50 pl-4 font-sans text-[11px] leading-4 break-words", children: parameter.description })) : null, parameter.enumValues?.length ? (_jsxs("div", { className: "text-neutral-grey-50 pl-4 text-[11px] leading-4 break-words", children: ["enum: ", parameter.enumValues.join(" | ")] })) : null] }, `${parameter.name}:${index}`))) }), _jsx("div", { className: "text-neutral-grey-50", children: ")" })] }));
}
function ToolDetails({ tool, onOpenItem, canOpenItem, }) {
    const implementationClassName = tool.implementationFullName ||
        tool.implementationClassName ||
        "(unresolved)";
    const { namespace, name: shortClassName } = splitClassName(implementationClassName);
    const itemPath = tool.itemPath || tool.itemId || "";
    const { parent: itemParent, leaf: itemLeaf } = splitItemPath(itemPath);
    const description = tool.description || tool.shortDescription;
    return (_jsxs("div", { className: "border-border-default bg-neutral-grey-5/50 space-y-3 border-t px-4 py-3 sm:pl-11", children: [description ? (_jsx("p", { className: "text-neutral-grey-50 text-xs leading-5 break-words", children: description })) : null, _jsx(SignatureBlock, { tool: tool }), tool.signatureError ? (_jsxs("div", { className: "border-feedback-orange bg-feedback-orange-light text-feedback-orange flex items-start gap-1.5 rounded-md border px-3 py-2 text-xs", children: [_jsx(AlertCircle, { className: "mt-0.5 h-3.5 w-3.5 shrink-0", strokeWidth: 1.5 }), _jsx("span", { className: "break-words", children: tool.signatureError })] })) : null, _jsxs("dl", { className: "grid gap-x-6 gap-y-2 text-xs sm:grid-cols-2", children: [tool.implementationKey && tool.implementationKey !== tool.key ? (_jsxs("div", { children: [_jsx("dt", { className: "text-neutral-grey-50 font-medium", children: "Implementation key" }), _jsx("dd", { className: "text-neutral-grey-100 mt-0.5 font-mono text-[11px] break-all", children: tool.implementationKey })] })) : null, _jsxs("div", { children: [_jsx("dt", { className: "text-neutral-grey-50 font-medium", children: "Class" }), _jsxs("dd", { className: "mt-0.5 font-mono text-[11px] break-all", title: implementationClassName, children: [namespace ? (_jsx("span", { className: "text-neutral-grey-50", children: namespace })) : null, _jsx("span", { className: "text-neutral-grey-100", children: shortClassName })] })] }), tool.serverName ? (_jsxs("div", { children: [_jsx("dt", { className: "text-neutral-grey-50 font-medium", children: "Server" }), _jsx("dd", { className: "text-neutral-grey-100 mt-0.5 font-mono text-[11px] break-all", children: tool.serverName })] })) : null, _jsxs("div", { children: [_jsx("dt", { className: "text-neutral-grey-50 font-medium", children: "Item" }), _jsx("dd", { className: "mt-0.5", children: tool.itemId ? (_jsxs("button", { type: "button", onClick: () => onOpenItem(tool), className: "group/link inline-flex min-w-0 items-start gap-1.5 text-left disabled:cursor-not-allowed disabled:opacity-50", disabled: !canOpenItem, title: itemPath, children: [_jsx(ExternalLink, { className: "text-neutral-grey-50 group-hover/link:text-feedback-blue mt-0.5 h-3.5 w-3.5 shrink-0 transition-colors", strokeWidth: 1.5 }), _jsxs("span", { className: "min-w-0 font-mono text-[11px] break-all", children: [itemParent ? (_jsx("span", { className: "text-neutral-grey-50", children: itemParent })) : null, _jsx("span", { className: "text-feedback-blue group-hover/link:underline", children: itemLeaf })] })] })) : (_jsx("span", { className: "text-neutral-grey-50", children: "\u2014" })) })] })] })] }));
}
export function AgentToolsPanel() {
    const editContext = useEditContext();
    const [state, setState] = useState("idle");
    const [tools, setTools] = useState([]);
    const [error, setError] = useState();
    const [query, setQuery] = useState("");
    const [implementationTypeFilter, setImplementationTypeFilter] = useState(ALL_IMPLEMENTATION_TYPES);
    const [expandedRows, setExpandedRows] = useState(new Set());
    const load = useCallback(async () => {
        setState("loading");
        setError(undefined);
        const result = await getAgentTools();
        if (result.type !== "success" || !result.data) {
            setState("error");
            setError(getErrorMessage(result));
            setTools([]);
            return;
        }
        setTools(result.data);
        setState("success");
    }, []);
    useEffect(() => {
        void load();
    }, [load]);
    const toggleRow = useCallback((rowKey) => {
        setExpandedRows((previous) => {
            const next = new Set(previous);
            if (next.has(rowKey)) {
                next.delete(rowKey);
            }
            else {
                next.add(rowKey);
            }
            return next;
        });
    }, []);
    const implementationTypeCounts = useMemo(() => {
        const counts = new Map();
        for (const tool of tools) {
            const implementationType = getImplementationType(tool);
            counts.set(implementationType, (counts.get(implementationType) ?? 0) + 1);
        }
        return counts;
    }, [tools]);
    const implementationTypes = useMemo(() => [
        ALL_IMPLEMENTATION_TYPES,
        ...Array.from(implementationTypeCounts.keys()).sort((a, b) => a.localeCompare(b)),
    ], [implementationTypeCounts]);
    const filteredTools = useMemo(() => {
        const normalizedQuery = query.trim().toLowerCase();
        return tools
            .filter((tool) => (implementationTypeFilter === ALL_IMPLEMENTATION_TYPES ||
            getImplementationType(tool) === implementationTypeFilter) &&
            matchesQuery(tool, normalizedQuery))
            .sort(compareAgentToolsByName);
    }, [implementationTypeFilter, query, tools]);
    const openItem = useCallback(async (tool) => {
        if (!editContext || !tool.itemId)
            return;
        const loaded = await editContext.loadItem(tool.itemId, {
            addToBrowseHistory: false,
        });
        if (loaded) {
            editContext.switchWorkspace("editor");
        }
    }, [editContext]);
    return (_jsx(SettingsPanelLayout, { children: _jsx("div", { className: "rounded-lg bg-white p-4 md:p-6", children: _jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center", children: [_jsx("div", { className: "bg-neutral-grey-5 inline-flex max-w-full shrink-0 overflow-x-auto rounded-lg p-0.5", children: implementationTypes.map((implementationType) => {
                                    const isActive = implementationTypeFilter === implementationType;
                                    const count = implementationType !== ALL_IMPLEMENTATION_TYPES
                                        ? (implementationTypeCounts.get(implementationType) ?? 0)
                                        : null;
                                    return (_jsxs("button", { type: "button", onClick: () => setImplementationTypeFilter(implementationType), className: cn("inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-xs font-medium transition-colors", isActive
                                            ? "text-neutral-grey-100 bg-white shadow-sm"
                                            : "text-neutral-grey-50 hover:text-neutral-grey-100"), children: [_jsx("span", { children: implementationType }), count !== null ? (_jsx("span", { className: "text-neutral-grey-50 text-2xs tabular-nums", children: count })) : null] }, implementationType));
                                }) }), _jsx(SearchInput, { value: query, onChange: setQuery, placeholder: "Filter tools", className: "w-full sm:max-w-64", disabled: state === "loading" })] }), error ? (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded-lg border p-4 text-sm", children: error })) : null, state === "loading" && tools.length === 0 ? (_jsx(LoadingState, { variant: "inline", message: "Loading agent tools...", spinnerSize: "sm" })) : null, state === "success" && filteredTools.length === 0 ? (_jsxs("div", { className: "border-border-default bg-neutral-grey-5 rounded-lg border p-6 text-center", children: [_jsx(CircleSlash, { className: "text-neutral-grey-50 mx-auto mb-3 h-8 w-8", strokeWidth: 1.5 }), _jsx("p", { className: "text-neutral-grey-50 text-sm", children: "No tools match the current filter." })] })) : null, filteredTools.length > 0 ? (_jsx("div", { className: "border-border-default divide-border-default divide-y overflow-hidden rounded-lg border bg-white", children: filteredTools.map((tool) => {
                            const rowKey = getRowKey(tool);
                            const isExpanded = expandedRows.has(rowKey);
                            return (_jsxs("div", { children: [_jsxs("button", { type: "button", onClick: () => toggleRow(rowKey), "aria-expanded": isExpanded, className: "hover:bg-neutral-grey-5 focus-visible:ring-feedback-blue flex w-full items-center gap-3 px-4 py-3 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset", children: [isExpanded ? (_jsx(ChevronDown, { className: "text-neutral-grey-50 h-4 w-4 shrink-0", strokeWidth: 1.5 })) : (_jsx(ChevronRight, { className: "text-neutral-grey-50 h-4 w-4 shrink-0", strokeWidth: 1.5 })), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("span", { className: "text-neutral-grey-100 font-mono text-[13px] break-all", children: tool.key }), _jsx("span", { className: "rounded-badge bg-neutral-grey-5 badge-pad-sm text-2xs text-neutral-grey-50 shrink-0 font-medium", children: getImplementationType(tool) }), tool.signatureError ? (_jsx(AlertCircle, { className: "text-feedback-orange h-3.5 w-3.5 shrink-0", strokeWidth: 1.5, "aria-label": "Signature error" })) : null] }), tool.shortDescription || tool.description ? (_jsx("p", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: tool.shortDescription || tool.description })) : null] })] }), isExpanded ? (_jsx(ToolDetails, { tool: tool, onOpenItem: (target) => void openItem(target), canOpenItem: !!editContext })) : null] }, rowKey));
                        }) })) : null] }) }) }));
}
export default AgentToolsPanel;
//# sourceMappingURL=AgentToolsPanel.js.map