import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { RefreshCw, Bug, Check, Copy } from "lucide-react";
import { toast } from "sonner";
import { Badge } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger, } from "../../components/ui/tooltip";
import { cn } from "../../lib/utils";
import { formatPersistentLogsForCopy } from "../persistentLogCopy";
import { getProjectPersistentLogs, getTaskPersistentLogs, } from "../services/taskService";
import { formatPersistentLogEventType, formatPersistentLogStage, formatPersistentLogStatus, persistentLogAgentIdSnippetTooltip, persistentLogCreatedAtTooltip, persistentLogDurationTooltip, persistentLogEventTypeTooltip, persistentLogSeqTooltip, persistentLogSourceTooltip, persistentLogStageTooltip, persistentLogStatusTooltip, PERSISTENT_LOG_FIELD_HINT_COMPACT, } from "../persistentLogLabels";
function trimPreview(value, maxLength = 700) {
    if (!value)
        return null;
    const normalized = value.trim();
    if (!normalized)
        return null;
    if (normalized.length <= maxLength)
        return normalized;
    return `${normalized.slice(0, maxLength)}...`;
}
function formatDuration(durationMs) {
    if (typeof durationMs !== "number" ||
        !Number.isFinite(durationMs) ||
        durationMs < 0) {
        return null;
    }
    if (durationMs < 1000)
        return `${durationMs}ms`;
    return `${(durationMs / 1000).toFixed(durationMs >= 10000 ? 0 : 1)}s`;
}
function LogMetaLine({ entry }) {
    const duration = formatDuration(entry.durationMs);
    const hasAny = entry.source ||
        typeof entry.seq === "number" ||
        duration ||
        entry.userId ||
        entry.agentId;
    if (!hasAny)
        return null;
    return (_jsxs("div", { className: "text-neutral-grey-50 mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5", children: [entry.source ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "cursor-help", title: persistentLogSourceTooltip(entry.source), children: entry.source }), typeof entry.seq === "number" ||
                        duration ||
                        entry.userId ||
                        entry.agentId ? (_jsx("span", { "aria-hidden": true, className: "text-neutral-grey-50", children: "|" })) : null] })) : null, typeof entry.seq === "number" ? (_jsxs(_Fragment, { children: [_jsxs("span", { className: "cursor-help", title: persistentLogSeqTooltip(entry.seq), children: ["seq ", entry.seq] }), duration || entry.userId || entry.agentId ? (_jsx("span", { "aria-hidden": true, className: "text-neutral-grey-50", children: "|" })) : null] })) : null, duration ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "cursor-help", title: persistentLogDurationTooltip(duration), children: duration }), entry.userId || entry.agentId ? (_jsx("span", { "aria-hidden": true, className: "text-neutral-grey-50", children: "|" })) : null] })) : null, entry.userId ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "max-w-[160px] cursor-help truncate", title: `User or account associated with this log line. ${entry.userId}`, children: entry.userId }), entry.agentId ? (_jsx("span", { "aria-hidden": true, className: "text-neutral-grey-50", children: "|" })) : null] })) : null, entry.agentId ? (_jsxs("span", { className: "cursor-help font-mono", title: persistentLogAgentIdSnippetTooltip(entry.agentId), children: ["agent ", entry.agentId.slice(0, 8)] })) : null] }));
}
function renderPreviewBlock(label, value) {
    const preview = trimPreview(value);
    if (!preview)
        return null;
    return (_jsxs("div", { className: "grid gap-1", children: [_jsx("div", { className: "text-neutral-grey-100 text-[10px] font-medium tracking-wider", children: label }), _jsx("pre", { className: "border-border-default bg-neutral-grey-5 text-neutral-grey-100 overflow-x-auto rounded border p-1.5 text-[11px] leading-tight whitespace-pre-wrap", children: preview })] }));
}
function LogEntryCard({ entry }) {
    const createdAtDisplay = useMemo(() => {
        const createdAt = new Date(entry.createdAt);
        if (Number.isNaN(createdAt.getTime()))
            return entry.createdAt;
        return createdAt.toLocaleString();
    }, [entry.createdAt]);
    const createdAtTitle = useMemo(() => {
        const createdAt = new Date(entry.createdAt);
        if (Number.isNaN(createdAt.getTime()))
            return entry.createdAt;
        return createdAt.toISOString();
    }, [entry.createdAt]);
    const statusTone = entry.success === false || entry.status?.toLowerCase() === "error"
        ? "destructive"
        : entry.success === true
            ? "default"
            : "secondary";
    return (_jsxs("div", { className: "border-border-default text-neutral-grey-100 hover:border-border-default rounded border bg-white p-2 text-[11px] leading-snug shadow-sm transition-colors", children: [_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-1.5", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-1", children: [_jsx(Badge, { variant: "outline", className: "text-2xs border-border-default bg-neutral-grey-5 max-w-[140px] cursor-help leading-none font-normal", title: persistentLogEventTypeTooltip(entry.eventType), children: _jsx("span", { className: "truncate", children: formatPersistentLogEventType(entry.eventType) }) }), entry.stage ? (_jsx(Badge, { variant: "outline", className: "text-2xs border-border-default bg-neutral-grey-5 max-w-[140px] cursor-help leading-none font-normal", title: persistentLogStageTooltip(entry.stage), children: _jsx("span", { className: "truncate", children: formatPersistentLogStage(entry.stage) }) })) : null, entry.status ? (_jsx(Badge, { variant: statusTone, className: "text-2xs max-w-[120px] cursor-help leading-none font-normal", title: persistentLogStatusTooltip(entry.status), children: _jsx("span", { className: "truncate", children: formatPersistentLogStatus(entry.status) }) })) : null] }), _jsx("span", { className: "text-neutral-grey-50 cursor-help font-mono", title: persistentLogCreatedAtTooltip({
                            hasValidDate: !Number.isNaN(new Date(entry.createdAt).getTime()),
                            localDisplay: createdAtDisplay,
                            isoUtc: !Number.isNaN(new Date(entry.createdAt).getTime())
                                ? new Date(entry.createdAt).toISOString()
                                : undefined,
                            raw: entry.createdAt,
                        }), children: createdAtDisplay })] }), entry.summary ? (_jsx("div", { className: "text-neutral-grey-100 mt-1", children: entry.summary })) : null, _jsx(LogMetaLine, { entry: entry }), entry.error ? (_jsx("div", { className: "badge-pad border-feedback-red bg-feedback-red-light/50 text-feedback-red mt-1.5 rounded border text-[11px] leading-snug", children: entry.error })) : null, entry.payloadPreview || entry.resultPreview || entry.metadataJson ? (_jsxs("details", { className: "group mt-2", children: [_jsxs("summary", { className: "text-neutral-grey-100 cursor-pointer list-none transition-colors", children: [_jsx("span", { className: "mr-1 inline-block transition-transform group-open:rotate-90", children: "\u25B6" }), "Details"] }), _jsxs("div", { className: "border-border-default mt-1.5 grid gap-1.5 border-l-2 pl-2", children: [renderPreviewBlock("Payload", entry.payloadPreview), renderPreviewBlock("Result", entry.resultPreview), renderPreviewBlock("Metadata", entry.metadataJson)] })] })) : null] }));
}
export function TaskboardPersistentLogPanel(props) {
    const { scope, projectId = null, taskId = null, title, emptyMessage, limit = 100, refreshKey = null, className, testId, } = props;
    const [logs, setLogs] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [isOpen, setIsOpen] = useState(false);
    const [hasCopied, setHasCopied] = useState(false);
    const triggerTooltip = `Open ${title}`;
    const canLoad = scope === "task"
        ? Boolean(taskId && taskId.trim())
        : Boolean(projectId && projectId.trim());
    const copyText = useMemo(() => formatPersistentLogsForCopy(logs, {
        title,
    }), [logs, title]);
    const loadLogs = useCallback(async () => {
        if (!canLoad) {
            setLogs([]);
            setError(null);
            return;
        }
        setIsLoading(true);
        setError(null);
        const result = scope === "task" && taskId
            ? await getTaskPersistentLogs(taskId, { limit })
            : await getProjectPersistentLogs(projectId, { limit });
        if (result.type === "success") {
            setLogs(result.data?.logs || []);
            setError(null);
        }
        else if (result.type === "unauthorized") {
            setLogs([]);
            setError("You are not authorized to view agent and taskboard logs.");
        }
        else {
            setLogs([]);
            setError(result.summary || "Failed to load agent and taskboard logs.");
        }
        setIsLoading(false);
    }, [canLoad, limit, projectId, scope, taskId]);
    useEffect(() => {
        if (isOpen) {
            void loadLogs();
        }
    }, [loadLogs, refreshKey, isOpen]);
    useEffect(() => {
        if (!hasCopied)
            return;
        const timeoutId = window.setTimeout(() => setHasCopied(false), 1500);
        return () => window.clearTimeout(timeoutId);
    }, [hasCopied]);
    const handleCopy = useCallback(async () => {
        if (!copyText)
            return;
        try {
            await navigator.clipboard.writeText(copyText);
            setHasCopied(true);
        }
        catch (error) {
            console.error("Failed to copy taskboard persistent logs:", error);
            toast.error("Failed to copy agent and taskboard logs.");
        }
    }, [copyText]);
    return (_jsx("div", { className: cn("flex items-center", className), "data-testid": testId, children: _jsxs(Popover, { open: isOpen, onOpenChange: setIsOpen, children: [_jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(PopoverTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "iconSm", className: "text-neutral-grey-50 hover:bg-neutral-grey-5 hover:text-neutral-grey-100", "aria-label": triggerTooltip, children: _jsx(Bug, { className: "h-4 w-4" }) }) }) }), _jsx(TooltipContent, { side: "top", sideOffset: 6, children: triggerTooltip })] }), _jsx(PopoverContent, { align: "end", className: "w-[450px] p-0 shadow-xl", sideOffset: 8, children: _jsxs("div", { className: "flex max-h-[600px] flex-col", children: [_jsxs("div", { className: "border-border-default bg-neutral-grey-5/50 flex items-center justify-between border-b px-3 py-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Bug, { className: "text-neutral-grey-50 h-3.5 w-3.5" }), _jsx("span", { className: "text-neutral-grey-100 text-[11px] font-bold tracking-wider", children: title })] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsxs(Button, { type: "button", variant: "ghost", size: "sm", className: "text-neutral-grey-50 hover:text-neutral-grey-50 h-7 gap-1 px-2 text-[11px]", onClick: (event) => {
                                                    event.stopPropagation();
                                                    void handleCopy();
                                                }, disabled: !copyText, title: "Copy currently loaded agent and taskboard logs", children: [hasCopied ? (_jsx(Check, { className: "h-3.5 w-3.5" })) : (_jsx(Copy, { className: "h-3.5 w-3.5" })), hasCopied ? "Copied" : "Copy"] }), _jsx(Button, { type: "button", variant: "ghost", size: "icon", className: "text-neutral-grey-50 hover:text-neutral-grey-50 h-7 w-7", onClick: (e) => {
                                                    e.stopPropagation();
                                                    void loadLogs();
                                                }, disabled: isLoading || !canLoad, title: "Refresh agent and taskboard logs", children: _jsx(RefreshCw, { className: cn("h-3.5 w-3.5", isLoading ? "animate-spin" : "") }) })] })] }), _jsx("p", { className: "border-border-default text-neutral-grey-50 border-b px-3 py-1.5 text-[10px] leading-snug", children: PERSISTENT_LOG_FIELD_HINT_COMPACT }), _jsx("div", { className: "flex-1 overflow-y-auto p-2", children: isLoading && logs.length === 0 ? (_jsxs("div", { className: "text-neutral-grey-50 py-8 text-center text-sm", children: [_jsx(RefreshCw, { className: "mx-auto mb-2 h-4 w-4 animate-spin opacity-20" }), "Loading logs..."] })) : error ? (_jsx("div", { className: "text-2xs border-feedback-red bg-feedback-red-light text-feedback-red rounded border p-3", children: error })) : logs.length === 0 ? (_jsx("div", { className: "text-neutral-grey-50 py-8 text-center text-sm", children: emptyMessage })) : (_jsx("div", { className: "grid gap-2", children: logs.map((entry) => (_jsx(LogEntryCard, { entry: entry }, entry.logId))) })) })] }) })] }) }));
}
//# sourceMappingURL=TaskboardPersistentLogPanel.js.map