"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComplianceMonitor = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_2 = require("@chakra-ui/react");
const recharts_1 = require("recharts");
const fi_1 = require("react-icons/fi");
const useWebSocket_1 = require("../../hooks/useWebSocket");
const ComplianceMonitor = ({ workflowId, onAlert, autoRefresh = true, refreshInterval = 30000, // 30 seconds
 }) => {
    const [status, setStatus] = (0, react_1.useState)(null);
    const [metrics, setMetrics] = (0, react_1.useState)([]);
    const [alerts, setAlerts] = (0, react_1.useState)([]);
    const [isLoading, setIsLoading] = (0, react_1.useState)(true);
    const [isAutoRefresh, setIsAutoRefresh] = (0, react_1.useState)(autoRefresh);
    const toast = (0, react_2.useToast)();
    const bgColor = (0, react_2.useColorModeValue)('white', 'gray.800');
    const borderColor = (0, react_2.useColorModeValue)('gray.200', 'gray.700');
    const alertBgColor = (0, react_2.useColorModeValue)('red.50', 'red.900');
    // WebSocket connection for real-time updates
    const { lastMessage, sendMessage } = (0, useWebSocket_1.useWebSocket)(`ws://api.bluefly.io/ws/compliance/${workflowId}`);
    // Handle WebSocket messages
    (0, react_1.useEffect)(() => {
        if (lastMessage) {
            const data = JSON.parse(lastMessage.data);
            switch (data.type) {
                case 'status_update':
                    setStatus(data.payload);
                    break;
                case 'metrics_update':
                    setMetrics(prev => [...prev, data.payload].slice(-20)); // Keep last 20 metrics
                    break;
                case 'alert':
                    setAlerts(prev => [data.payload, ...prev].slice(0, 5)); // Keep last 5 alerts
                    if (onAlert) {
                        onAlert(data.payload);
                    }
                    break;
            }
        }
    }, [lastMessage, onAlert]);
    // Auto-refresh logic
    (0, react_1.useEffect)(() => {
        let interval;
        if (isAutoRefresh) {
            interval = setInterval(() => {
                sendMessage({ type: 'refresh' });
            }, refreshInterval);
        }
        return () => {
            if (interval) {
                clearInterval(interval);
            }
        };
    }, [isAutoRefresh, refreshInterval, sendMessage]);
    // Initial data load
    (0, react_1.useEffect)(() => {
        const loadInitialData = async () => {
            try {
                const response = await fetch(`/api/compliance/${workflowId}/status`);
                const data = await response.json();
                setStatus(data.status);
                setMetrics(data.metrics);
                setAlerts(data.alerts);
            }
            catch (error) {
                toast({
                    title: 'Error loading compliance data',
                    description: 'Failed to load initial compliance status',
                    status: 'error',
                    duration: 5000,
                    isClosable: true,
                });
            }
            finally {
                setIsLoading(false);
            }
        };
        loadInitialData();
    }, [workflowId, toast]);
    const handleRefresh = (0, react_1.useCallback)(() => {
        sendMessage({ type: 'refresh' });
    }, [sendMessage]);
    const handleAutoRefreshToggle = (0, react_1.useCallback)(() => {
        setIsAutoRefresh(prev => !prev);
    }, []);
    if (isLoading) {
        return ((0, jsx_runtime_1.jsx)(react_2.Box, { p: 4, textAlign: "center", children: (0, jsx_runtime_1.jsx)(react_2.Text, { children: "Loading compliance data..." }) }));
    }
    return ((0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 6, align: "stretch", p: 4, children: [(0, jsx_runtime_1.jsxs)(react_2.HStack, { justify: "space-between", children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "xl", fontWeight: "bold", children: "Compliance Monitor" }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { children: [(0, jsx_runtime_1.jsx)(react_2.Tooltip, { label: isAutoRefresh ? 'Disable auto-refresh' : 'Enable auto-refresh', children: (0, jsx_runtime_1.jsx)(react_2.IconButton, { icon: (0, jsx_runtime_1.jsx)(fi_1.FiRefreshCw, {}), onClick: handleAutoRefreshToggle, colorScheme: isAutoRefresh ? 'blue' : 'gray', variant: "ghost", "aria-label": "Toggle auto-refresh" }) }), (0, jsx_runtime_1.jsx)(react_2.IconButton, { icon: (0, jsx_runtime_1.jsx)(fi_1.FiRefreshCw, {}), onClick: handleRefresh, variant: "outline", "aria-label": "Refresh now" }), (0, jsx_runtime_1.jsx)(react_2.IconButton, { icon: (0, jsx_runtime_1.jsx)(fi_1.FiSettings, {}), onClick: () => { }, variant: "ghost", "aria-label": "Settings" })] })] }), alerts.length > 0 && ((0, jsx_runtime_1.jsx)(react_2.Box, { children: alerts.map((alert, index) => ((0, jsx_runtime_1.jsxs)(react_2.Alert, { status: alert.severity === 'high' ? 'error' : 'warning', variant: "subtle", bg: alertBgColor, mb: 2, children: [(0, jsx_runtime_1.jsx)(react_2.AlertIcon, {}), (0, jsx_runtime_1.jsxs)(react_2.Box, { flex: "1", children: [(0, jsx_runtime_1.jsx)(react_2.AlertTitle, { children: alert.title }), (0, jsx_runtime_1.jsx)(react_2.AlertDescription, { children: alert.description })] }), (0, jsx_runtime_1.jsx)(react_2.Button, { size: "sm", variant: "outline", onClick: () => { }, children: "View Details" })] }, index))) })), status && ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, bg: bgColor, borderRadius: "md", borderWidth: 1, borderColor: borderColor, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "lg", fontWeight: "semibold", mb: 4, children: "Current Status" }), (0, jsx_runtime_1.jsxs)(react_2.HStack, { spacing: 6, children: [(0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Security" }), (0, jsx_runtime_1.jsx)(react_2.StatNumber, { children: (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: status.security.isCompliant ? 'green' : 'red', fontSize: "md", children: status.security.isCompliant ? 'Compliant' : 'Non-Compliant' }) }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: status.security.trend > 0 ? 'increase' : 'decrease' }), Math.abs(status.security.trend), "% from last check"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "Data" }), (0, jsx_runtime_1.jsx)(react_2.StatNumber, { children: (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: status.data.isCompliant ? 'green' : 'red', fontSize: "md", children: status.data.isCompliant ? 'Compliant' : 'Non-Compliant' }) }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: status.data.trend > 0 ? 'increase' : 'decrease' }), Math.abs(status.data.trend), "% from last check"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Stat, { children: [(0, jsx_runtime_1.jsx)(react_2.StatLabel, { children: "LLM" }), (0, jsx_runtime_1.jsx)(react_2.StatNumber, { children: (0, jsx_runtime_1.jsx)(react_2.Badge, { colorScheme: status.llm.isCompliant ? 'green' : 'red', fontSize: "md", children: status.llm.isCompliant ? 'Compliant' : 'Non-Compliant' }) }), (0, jsx_runtime_1.jsxs)(react_2.StatHelpText, { children: [(0, jsx_runtime_1.jsx)(react_2.StatArrow, { type: status.llm.trend > 0 ? 'increase' : 'decrease' }), Math.abs(status.llm.trend), "% from last check"] })] })] })] })), metrics.length > 0 && ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, bg: bgColor, borderRadius: "md", borderWidth: 1, borderColor: borderColor, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "lg", fontWeight: "semibold", mb: 4, children: "Compliance Trend" }), (0, jsx_runtime_1.jsx)(react_2.Box, { height: "300px", children: (0, jsx_runtime_1.jsx)(recharts_1.ResponsiveContainer, { width: "100%", height: "100%", children: (0, jsx_runtime_1.jsxs)(recharts_1.LineChart, { data: metrics, children: [(0, jsx_runtime_1.jsx)(recharts_1.CartesianGrid, { strokeDasharray: "3 3" }), (0, jsx_runtime_1.jsx)(recharts_1.XAxis, { dataKey: "timestamp", tickFormatter: (value) => new Date(value).toLocaleTimeString() }), (0, jsx_runtime_1.jsx)(recharts_1.YAxis, { domain: [0, 100] }), (0, jsx_runtime_1.jsx)(recharts_1.Tooltip, { labelFormatter: (value) => new Date(value).toLocaleString(), formatter: (value) => [`${value}%`, 'Compliance Score'] }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "score", stroke: "#3182CE", strokeWidth: 2, dot: false }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "securityScore", stroke: "#38A169", strokeWidth: 2, dot: false }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "dataScore", stroke: "#DD6B20", strokeWidth: 2, dot: false }), (0, jsx_runtime_1.jsx)(recharts_1.Line, { type: "monotone", dataKey: "llmScore", stroke: "#805AD5", strokeWidth: 2, dot: false })] }) }) })] })), status?.resourceUsage && ((0, jsx_runtime_1.jsxs)(react_2.Box, { p: 4, bg: bgColor, borderRadius: "md", borderWidth: 1, borderColor: borderColor, children: [(0, jsx_runtime_1.jsx)(react_2.Text, { fontSize: "lg", fontWeight: "semibold", mb: 4, children: "Resource Usage" }), (0, jsx_runtime_1.jsxs)(react_2.VStack, { spacing: 4, align: "stretch", children: [(0, jsx_runtime_1.jsxs)(react_2.Box, { children: [(0, jsx_runtime_1.jsx)(react_2.Text, { mb: 2, children: "API Calls (Last Hour)" }), (0, jsx_runtime_1.jsx)(react_2.Progress, { value: status.resourceUsage.apiCallsPercentage, colorScheme: status.resourceUsage.apiCallsPercentage > 80 ? 'red' : 'blue', size: "sm" }), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "sm", mt: 1, children: [status.resourceUsage.apiCalls, " / ", status.resourceUsage.apiCallsLimit, " calls"] })] }), (0, jsx_runtime_1.jsxs)(react_2.Box, { children: [(0, jsx_runtime_1.jsx)(react_2.Text, { mb: 2, children: "Token Usage" }), (0, jsx_runtime_1.jsx)(react_2.Progress, { value: status.resourceUsage.tokenUsagePercentage, colorScheme: status.resourceUsage.tokenUsagePercentage > 80 ? 'red' : 'blue', size: "sm" }), (0, jsx_runtime_1.jsxs)(react_2.Text, { fontSize: "sm", mt: 1, children: [status.resourceUsage.tokenUsage, " / ", status.resourceUsage.tokenLimit, " tokens"] })] })] })] }))] }));
};
exports.ComplianceMonitor = ComplianceMonitor;
//# sourceMappingURL=ComplianceMonitor.js.map