import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AlertCircle, ExternalLink, Wrench } from "lucide-react";
import { FilterInput } from "../../../components/FilterInput";
import { Card } from "../../../components/ui/card";
import { cn } from "../../../lib/utils";
import { useEditContext } from "../../client/editContext";
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 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 SignatureBlock({ tool }) {
    const parameters = tool.signatureParameters ?? [];
    if (parameters.length === 0) {
        return (_jsx("code", { className: "border-border-default/80 from-neutral-grey-5 text-neutral-grey-100 block rounded-md border bg-gradient-to-b to-white px-2.5 py-1.5 text-xs leading-5 break-words whitespace-pre-wrap", children: tool.signature }));
    }
    return (_jsxs("div", { className: "border-border-default/80 overflow-hidden rounded-md border bg-white text-xs", children: [_jsxs("div", { className: "border-border-default/70 bg-neutral-grey-5/70 flex items-baseline border-b px-2.5 py-1.5 font-mono break-all", children: [_jsx("span", { className: "text-neutral-grey-100 font-semibold", children: tool.key }), _jsx("span", { className: "text-neutral-grey-50", children: "(" })] }), _jsx("div", { className: "divide-border-default divide-y", children: parameters.map((parameter, index) => (_jsxs("div", { className: "hover:bg-neutral-grey-5/60 px-2.5 py-1.5 transition-colors", children: [_jsxs("div", { className: "flex flex-wrap items-baseline gap-x-1 gap-y-0.5 font-mono", children: [_jsx("span", { className: "text-neutral-grey-100 font-semibold", 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 }), _jsx("span", { className: cn("ml-1.5 rounded-full px-1.5 py-px font-sans text-[9px] font-semibold tracking-wide", parameter.isRequired
                                        ? "bg-feedback-orange-light/70 text-feedback-orange"
                                        : "bg-neutral-grey-5 text-neutral-grey-50"), children: parameter.isRequired ? "required" : "optional" })] }), parameter.description ? (_jsx("div", { className: "text-neutral-grey-50 mt-1 font-sans text-[11px] leading-4 break-words", children: parameter.description })) : null, parameter.enumValues?.length ? (_jsxs("div", { className: "text-neutral-grey-50 mt-1 font-mono text-[11px] leading-4 break-words", children: [_jsx("span", { className: "text-neutral-grey-50", children: "enum:" }), " ", parameter.enumValues.join(" | ")] })) : null] }, `${parameter.name}:${index}`))) }), _jsx("div", { className: "border-border-default/70 bg-neutral-grey-5/70 text-neutral-grey-50 border-t px-2.5 py-1 font-mono", children: ")" })] }));
}
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),
    };
}
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 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 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));
    }, [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("div", { className: "flex h-full min-h-0 flex-col p-4", children: _jsxs(Card, { icon: _jsx(Wrench, { strokeWidth: 1, className: "h-5 w-5" }), title: _jsxs(_Fragment, { children: ["Agent tools", " ", _jsxs("span", { className: "text-neutral-grey-50 font-normal", children: ["(", filteredTools.length, " of ", tools.length, ")"] })] }), description: "Registered agent tools available to agents, with their implementations.", noPadding: true, className: "flex min-h-0 flex-1 flex-col overflow-hidden", children: [_jsxs("div", { className: "border-border-default shrink-0 border-t px-4 py-3", children: [_jsx("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between", children: _jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center", children: [_jsx("div", { className: "border-border-default inline-flex max-w-full overflow-auto rounded-lg border bg-white 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
                                                    ? "bg-feedback-blue-light text-feedback-blue"
                                                    : "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-100"), children: [_jsx("span", { children: implementationType }), count !== null ? (_jsx("span", { className: cn("rounded-full px-1.5 py-px text-[10px] font-semibold tabular-nums", isActive
                                                            ? "bg-feedback-blue-light text-feedback-blue"
                                                            : "bg-neutral-grey-5 text-neutral-grey-50"), children: count })) : null] }, implementationType));
                                        }) }), _jsx(FilterInput, { value: query, onChange: setQuery, placeholder: "Filter tools", className: "w-full sm:w-64", disabled: state === "loading" })] }) }), error ? (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red mt-3 rounded-md border px-3 py-2 text-sm", children: error })) : null] }), _jsx("div", { className: "min-h-0 flex-1 overflow-auto", children: filteredTools.length === 0 && state === "success" ? (_jsx("div", { className: "text-neutral-grey-50 flex h-full items-center justify-center p-6 text-sm", children: "No tools match the current filter." })) : (_jsxs("table", { className: "min-w-[1240px] table-fixed border-separate border-spacing-0 text-left text-sm", children: [_jsxs("colgroup", { children: [_jsx("col", { className: "w-[15%]" }), _jsx("col", { className: "w-[19%]" }), _jsx("col", { className: "w-[32%]" }), _jsx("col", { className: "w-[17%]" }), _jsx("col", { className: "w-[17%]" })] }), _jsx("thead", { className: "text-neutral-grey-50 sticky top-0 z-10 bg-white text-[11px] font-semibold tracking-wider", children: _jsxs("tr", { children: [_jsx("th", { className: "border-border-default border-b px-4 py-2.5", children: "Key" }), _jsx("th", { className: "border-border-default border-b px-4 py-2.5", children: "Description" }), _jsx("th", { className: "border-border-default border-b px-4 py-2.5", children: "Signature" }), _jsx("th", { className: "border-border-default border-b px-4 py-2.5", children: "Class" }), _jsx("th", { className: "border-border-default border-b px-4 py-2.5", children: "Item" })] }) }), _jsx("tbody", { children: filteredTools.map((tool) => {
                                    const registrationLocation = getRegistrationLocation(tool);
                                    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);
                                    return (_jsxs("tr", { className: "group hover:bg-neutral-grey-5 align-top transition-colors", children: [_jsx("td", { className: "border-border-default border-b px-4 py-3.5", children: _jsxs("div", { className: "flex min-w-0 flex-col gap-1", children: [_jsx("code", { className: "border-feedback-blue/60 bg-feedback-blue-light/60 text-feedback-blue inline-block w-fit max-w-full rounded-md border px-2 py-0.5 text-[12px] font-semibold break-all", children: tool.key }), tool.implementationKey &&
                                                            tool.implementationKey !== tool.key ? (_jsx("span", { className: "text-neutral-grey-50 font-mono text-[11px] break-all", children: tool.implementationKey })) : null] }) }), _jsx("td", { className: "border-border-default border-b px-4 py-3.5", children: _jsx("p", { className: "text-neutral-grey-50 text-[12px] leading-5 break-words", children: tool.shortDescription || tool.description || (_jsx("span", { className: "text-neutral-grey-50", children: "\u2014" })) }) }), _jsx("td", { className: "border-border-default border-b px-4 py-3.5", children: _jsxs("div", { className: "space-y-2", children: [_jsx(SignatureBlock, { tool: tool }), tool.signatureError ? (_jsxs("div", { className: "bg-feedback-orange-light/70 text-feedback-orange flex items-start gap-1.5 rounded-md px-2 py-1 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] }) }), _jsx("td", { className: "border-border-default border-b px-4 py-3.5", children: _jsxs("div", { className: "font-mono text-[11px] leading-5 break-all", title: implementationClassName, children: [namespace ? (_jsx("span", { className: "text-neutral-grey-50", children: namespace })) : null, _jsx("span", { className: "text-neutral-grey-100 font-semibold", children: shortClassName })] }) }), _jsx("td", { className: "border-border-default border-b px-4 py-3.5", children: tool.itemId ? (_jsxs("button", { type: "button", onClick: () => void openItem(tool), className: "group/link inline-flex min-w-0 items-start gap-1.5 text-left disabled:cursor-not-allowed disabled:opacity-50", disabled: !editContext, 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 break-words", children: [itemParent ? (_jsx("span", { className: "text-neutral-grey-50 text-[11px]", children: itemParent })) : null, _jsx("span", { className: "text-feedback-blue group-hover/link:text-feedback-blue text-[12px] font-medium group-hover/link:underline", children: itemLeaf })] })] })) : (_jsx("span", { className: "text-neutral-grey-50 text-xs", children: "\u2014" })) })] }, `${registrationLocation}:${tool.itemId ?? tool.key}:${tool.implementationKey}`));
                                }) })] })) })] }) }));
}
export default AgentToolsPanel;
//# sourceMappingURL=AgentToolsPanel.js.map