File size: 6,056 Bytes
f568a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';

export interface PredictedWindow {
  startTime: Date;
  endTime: Date;
  confidence: number;
  expectedCoherence: number;
  expectedLHECount: number;
  reasoning: string;
  dayOfWeek: string;
  hourRange: string;
}

export interface HistoricalPattern {
  dayOfWeek: number;
  hour: number;
  activationRate: number;
  avgCoherence: number;
  avgLHECount: number;
  sampleSize: number;
}

export function usePredictiveWindows(daysAhead = 7) {
  const [predictions, setPredictions] = useState<PredictedWindow[]>([]);
  const [patterns, setPatterns] = useState<HistoricalPattern[]>([]);
  const [isAnalyzing, setIsAnalyzing] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const analyzePredictiveWindows = async () => {
      setIsAnalyzing(true);
      setError(null);

      try {
        // Fetch last 30 days of scheduler history
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

        const { data: history, error: historyError } = await supabase
          .from('scheduler_history')
          .select('*')
          .gte('timestamp', thirtyDaysAgo.toISOString())
          .order('timestamp', { ascending: true });

        if (historyError) throw historyError;

        if (!history || history.length === 0) {
          setPredictions([]);
          setPatterns([]);
          setIsAnalyzing(false);
          return;
        }

        // Analyze patterns by day of week and hour
        const patternMap = new Map<string, {
          activations: number;
          totalSamples: number;
          coherenceSum: number;
          lheSum: number;
        }>();

        history.forEach(record => {
          const date = new Date(record.timestamp);
          const dayOfWeek = date.getDay();
          const hour = date.getHours();
          const key = `${dayOfWeek}-${hour}`;

          const existing = patternMap.get(key) || {
            activations: 0,
            totalSamples: 0,
            coherenceSum: 0,
            lheSum: 0,
          };

          existing.totalSamples++;
          existing.coherenceSum += record.coherence_at_action;
          existing.lheSum += record.lighthouse_events_count;

          if (record.action === 'enable') {
            existing.activations++;
          }

          patternMap.set(key, existing);
        });

        // Convert to patterns array
        const analyzedPatterns: HistoricalPattern[] = [];
        patternMap.forEach((value, key) => {
          const [dayOfWeek, hour] = key.split('-').map(Number);
          analyzedPatterns.push({
            dayOfWeek,
            hour,
            activationRate: value.activations / value.totalSamples,
            avgCoherence: value.coherenceSum / value.totalSamples,
            avgLHECount: value.lheSum / value.totalSamples,
            sampleSize: value.totalSamples,
          });
        });

        setPatterns(analyzedPatterns);

        // Generate predictions for next N days
        const now = new Date();
        const predictedWindows: PredictedWindow[] = [];

        for (let dayOffset = 0; dayOffset < daysAhead; dayOffset++) {
          const targetDate = new Date(now);
          targetDate.setDate(targetDate.getDate() + dayOffset);
          const dayOfWeek = targetDate.getDay();

          // Find patterns for this day of week
          const dayPatterns = analyzedPatterns.filter(p => p.dayOfWeek === dayOfWeek);

          if (dayPatterns.length === 0) continue;

          // Find high-probability windows (activation rate > 0.5 and sufficient samples)
          const strongPatterns = dayPatterns
            .filter(p => p.activationRate > 0.5 && p.sampleSize >= 3)
            .sort((a, b) => b.activationRate - a.activationRate);

          strongPatterns.forEach(pattern => {
            const windowStart = new Date(targetDate);
            windowStart.setHours(pattern.hour, 0, 0, 0);

            const windowEnd = new Date(windowStart);
            windowEnd.setHours(windowStart.getHours() + 1);

            // Skip past windows
            if (windowEnd < now) return;

            const confidence = Math.min(
              pattern.activationRate * (Math.min(pattern.sampleSize, 10) / 10),
              1
            );

            const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            
            predictedWindows.push({
              startTime: windowStart,
              endTime: windowEnd,
              confidence,
              expectedCoherence: pattern.avgCoherence,
              expectedLHECount: pattern.avgLHECount,
              reasoning: `Historical data shows ${(pattern.activationRate * 100).toFixed(0)}% activation rate during this window (${pattern.sampleSize} samples)`,
              dayOfWeek: dayNames[pattern.dayOfWeek],
              hourRange: `${String(pattern.hour).padStart(2, '0')}:00-${String(pattern.hour + 1).padStart(2, '0')}:00`,
            });
          });
        }

        // Sort by start time
        predictedWindows.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());

        setPredictions(predictedWindows);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : 'Analysis failed';
        setError(errorMessage);
        console.error('Predictive windows analysis error:', err);
      } finally {
        setIsAnalyzing(false);
      }
    };

    analyzePredictiveWindows();

    // Refresh every hour
    const interval = setInterval(analyzePredictiveWindows, 60 * 60 * 1000);

    return () => clearInterval(interval);
  }, [daysAhead]);

  return {
    predictions,
    patterns,
    isAnalyzing,
    error,
    nextOptimalWindow: predictions[0],
  };
}