"use strict";
/**
 * @file useUsageLearning.ts
 * Hook for learning from component usage patterns
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.useUsageLearning = useUsageLearning;
const react_1 = require("react");
/**
 * Hook for learning from component usage patterns
 */
function useUsageLearning(config) {
    const { componentId, enabled = true, storageKey } = config;
    const key = storageKey || `llm-usage-${componentId}`;
    const [usageData, setUsageData] = (0, react_1.useState)(() => {
        if (typeof window === 'undefined' || !enabled) {
            return createEmptyUsageData();
        }
        try {
            const stored = localStorage.getItem(key);
            return stored ? JSON.parse(stored) : createEmptyUsageData();
        }
        catch (e) {
            return createEmptyUsageData();
        }
    });
    // Record usage
    const recordUsage = (0, react_1.useCallback)((action) => {
        if (!enabled)
            return;
        const now = Date.now();
        const date = new Date(now);
        const hour = date.getHours();
        const day = date.getDay();
        setUsageData(prev => {
            const updated = {
                ...prev,
                count: prev.count + 1,
                lastUsed: now,
                patterns: {
                    ...prev.patterns,
                    timeOfDay: {
                        ...prev.patterns.timeOfDay,
                        [hour]: (prev.patterns.timeOfDay[hour] || 0) + 1,
                    },
                    dayOfWeek: {
                        ...prev.patterns.dayOfWeek,
                        [day]: (prev.patterns.dayOfWeek[day] || 0) + 1,
                    },
                    sequence: [...prev.patterns.sequence.slice(-9), action || 'use'].slice(-10),
                },
                predictions: calculatePredictions(prev),
            };
            // Persist to storage
            if (typeof window !== 'undefined') {
                try {
                    localStorage.setItem(key, JSON.stringify(updated));
                }
                catch (e) {
                    console.warn('Failed to save usage data:', e);
                }
            }
            return updated;
        });
    }, [enabled, key]);
    // Calculate predictions based on usage patterns
    const calculatePredictions = (data) => {
        const predictions = {
            confidence: 0,
        };
        // Need minimum data for predictions
        if (data.count < 5) {
            return predictions;
        }
        // Predict next use time based on patterns
        const currentHour = new Date().getHours();
        const hourCounts = data.patterns.timeOfDay;
        // Find most common usage hours
        const sortedHours = Object.entries(hourCounts)
            .sort(([, a], [, b]) => b - a)
            .map(([hour]) => parseInt(hour));
        if (sortedHours.length > 0) {
            // Find next likely hour
            const nextHour = sortedHours.find(h => h > currentHour) || sortedHours[0];
            const today = new Date();
            today.setHours(nextHour, 0, 0, 0);
            if (nextHour <= currentHour) {
                today.setDate(today.getDate() + 1);
            }
            predictions.nextUseTime = today.getTime();
            predictions.confidence = Math.min(0.9, data.count / 50); // Max 90% confidence
        }
        // Predict next action based on sequence patterns
        if (data.patterns.sequence.length >= 3) {
            const sequences = findPatterns(data.patterns.sequence);
            if (sequences.length > 0) {
                predictions.nextAction = sequences[0].next;
                predictions.confidence = Math.max(predictions.confidence, sequences[0].confidence);
            }
        }
        return predictions;
    };
    // Find patterns in action sequences
    const findPatterns = (sequence) => {
        const patterns = {};
        // Build pattern map
        for (let i = 0; i < sequence.length - 1; i++) {
            const current = sequence[i];
            const next = sequence[i + 1];
            if (!patterns[current]) {
                patterns[current] = {};
            }
            patterns[current][next] = (patterns[current][next] || 0) + 1;
        }
        // Find predictions for last action
        const lastAction = sequence[sequence.length - 1];
        const predictions = patterns[lastAction];
        if (!predictions)
            return [];
        // Convert to sorted array
        return Object.entries(predictions)
            .map(([action, count]) => ({
            next: action,
            confidence: count / sequence.length,
        }))
            .sort((a, b) => b.confidence - a.confidence);
    };
    // Get usage insights
    const getInsights = (0, react_1.useCallback)(() => {
        const insights = [];
        if (usageData.count === 0)
            return insights;
        // Most active time
        const topHour = Object.entries(usageData.patterns.timeOfDay)
            .sort(([, a], [, b]) => b - a)[0];
        if (topHour) {
            insights.push(`Most active at ${topHour[0]}:00`);
        }
        // Usage frequency
        if (usageData.count > 10) {
            const daysSinceFirst = (Date.now() - usageData.lastUsed) / (1000 * 60 * 60 * 24);
            const usagePerDay = usageData.count / Math.max(1, daysSinceFirst);
            if (usagePerDay > 5) {
                insights.push('High frequency user');
            }
            else if (usagePerDay > 1) {
                insights.push('Regular user');
            }
            else {
                insights.push('Occasional user');
            }
        }
        // Predictions
        if (usageData.predictions.nextUseTime && usageData.predictions.confidence > 0.5) {
            const nextUse = new Date(usageData.predictions.nextUseTime);
            insights.push(`Likely to use again at ${nextUse.getHours()}:00`);
        }
        return insights;
    }, [usageData]);
    // Reset usage data
    const resetUsage = (0, react_1.useCallback)(() => {
        const empty = createEmptyUsageData();
        setUsageData(empty);
        if (typeof window !== 'undefined') {
            localStorage.removeItem(key);
        }
    }, [key]);
    // Sync with global AI service
    (0, react_1.useEffect)(() => {
        if (enabled && window.Drupal?.llmAI && usageData.count > 0) {
            window.Drupal.llmAI.recordInteraction({
                component: componentId,
                usage: {
                    count: usageData.count,
                    lastUsed: usageData.lastUsed,
                    predictions: usageData.predictions,
                },
            });
        }
    }, [enabled, componentId, usageData.count, usageData.lastUsed, usageData.predictions]);
    return {
        usageCount: usageData.count,
        lastUsed: usageData.lastUsed,
        predictions: usageData.predictions,
        insights: getInsights(),
        recordUsage,
        resetUsage,
    };
}
// Create empty usage data
function createEmptyUsageData() {
    return {
        count: 0,
        lastUsed: 0,
        patterns: {
            timeOfDay: {},
            dayOfWeek: {},
            sequence: [],
        },
        predictions: {
            confidence: 0,
        },
    };
}
//# sourceMappingURL=useUsageLearning.js.map