File size: 12,155 Bytes
86d71bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
 * Interview Storage Service
 * 
 * Provides persistent storage for interview completion data.
 * Uses backend API as primary source, localStorage as fallback.
 * 
 * CRITICAL: Ensures interview data persists after refresh and
 * dashboard counts/history are always accurate.
 */

const STORAGE_KEY = 'ai_interviewer_completed_sessions';
const HISTORY_KEY = 'ai_interviewer_interview_history';
const ANALYTICS_KEY = 'ai_interviewer_analytics_cache';

// ===========================================
// INTERVIEW DATA STRUCTURE
// ===========================================

/**
 * Creates a standardized interview record
 * @param {Object} data - Interview completion data
 * @returns {Object} Standardized interview record
 */
export function createInterviewRecord(data) {
    return {
        interviewId: data.interviewId || data.session_id || data.id,
        date: data.date || data.completed_at || new Date().toISOString(),
        score: data.score || data.readiness?.score || 0,
        grade: data.grade || data.readiness?.grade || 'C',
        targetRole: data.targetRole || data.target_role || 'Interview',
        status: 'completed',
        strengths: data.strengths || [],
        weaknesses: data.weaknesses || [],
        improvementTips: data.improvementTips || data.improvements?.areas || [],
        pdfUrl: data.pdfUrl || null,
        summary: data.summary || data.executive_summary || '',
        statistics: data.statistics || {
            total_questions: data.total_questions || 0,
            answered: data.answered || 0,
            skipped: data.skipped || 0,
            duration_minutes: data.duration_minutes || 0,
        },
        skills: data.skills || {},
        createdAt: new Date().toISOString(),
    };
}

// ===========================================
// LOCAL STORAGE OPERATIONS
// ===========================================

/**
 * Get all stored interview records from localStorage
 * @returns {Array} Array of interview records
 */
export function getStoredInterviews() {
    try {
        const stored = localStorage.getItem(HISTORY_KEY);
        return stored ? JSON.parse(stored) : [];
    } catch (e) {
        console.warn('[InterviewStorage] Failed to read from localStorage:', e);
        return [];
    }
}

/**
 * Save interview record to localStorage
 * @param {Object} record - Interview record to save
 * @returns {boolean} Success status
 */
export function saveInterviewToStorage(record) {
    try {
        const interviews = getStoredInterviews();

        // Check if interview already exists (update) or is new (add)
        const existingIndex = interviews.findIndex(
            i => i.interviewId === record.interviewId
        );

        if (existingIndex >= 0) {
            // Update existing record
            interviews[existingIndex] = {
                ...interviews[existingIndex],
                ...record,
                updatedAt: new Date().toISOString(),
            };
        } else {
            // Add new record at beginning
            interviews.unshift(record);
        }

        // Keep only last 100 interviews
        const trimmedInterviews = interviews.slice(0, 100);
        localStorage.setItem(HISTORY_KEY, JSON.stringify(trimmedInterviews));

        // Update analytics cache
        updateAnalyticsCache(trimmedInterviews);

        console.log('[InterviewStorage] Saved interview:', record.interviewId);
        return true;
    } catch (e) {
        console.error('[InterviewStorage] Failed to save:', e);
        return false;
    }
}

/**
 * Get a specific interview by ID
 * @param {string} interviewId - Interview ID
 * @returns {Object|null} Interview record or null
 */
export function getInterviewById(interviewId) {
    const interviews = getStoredInterviews();
    return interviews.find(i => i.interviewId === interviewId) || null;
}

/**
 * Delete an interview from storage
 * @param {string} interviewId - Interview ID
 * @returns {boolean} Success status
 */
export function deleteInterviewFromStorage(interviewId) {
    try {
        const interviews = getStoredInterviews();
        const filtered = interviews.filter(i => i.interviewId !== interviewId);
        localStorage.setItem(HISTORY_KEY, JSON.stringify(filtered));
        updateAnalyticsCache(filtered);
        return true;
    } catch (e) {
        console.error('[InterviewStorage] Failed to delete:', e);
        return false;
    }
}

// ===========================================
// ANALYTICS CACHE
// ===========================================

/**
 * Update local analytics cache based on stored interviews
 * @param {Array} interviews - Array of interview records
 */
function updateAnalyticsCache(interviews) {
    try {
        const completed = interviews.filter(i => i.status === 'completed');
        const scores = completed.filter(i => i.score > 0).map(i => i.score);

        const analytics = {
            total_interviews: interviews.length,
            completed_interviews: completed.length,
            average_score: scores.length > 0
                ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
                : null,
            best_score: scores.length > 0 ? Math.max(...scores) : null,
            last_interview_at: interviews.length > 0 ? interviews[0].date : null,
            updatedAt: new Date().toISOString(),
        };

        localStorage.setItem(ANALYTICS_KEY, JSON.stringify(analytics));
    } catch (e) {
        console.warn('[InterviewStorage] Failed to update analytics cache:', e);
    }
}

/**
 * Get cached analytics
 * @returns {Object} Analytics data
 */
export function getCachedAnalytics() {
    try {
        const cached = localStorage.getItem(ANALYTICS_KEY);
        if (cached) {
            return JSON.parse(cached);
        }
    } catch (e) {
        console.warn('[InterviewStorage] Failed to read analytics cache:', e);
    }

    // Calculate from stored interviews if cache missing
    const interviews = getStoredInterviews();
    const completed = interviews.filter(i => i.status === 'completed');
    const scores = completed.filter(i => i.score > 0).map(i => i.score);

    return {
        total_interviews: interviews.length,
        completed_interviews: completed.length,
        average_score: scores.length > 0
            ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
            : null,
        best_score: scores.length > 0 ? Math.max(...scores) : null,
        last_interview_at: interviews.length > 0 ? interviews[0].date : null,
    };
}

// ===========================================
// INTERVIEW COMPLETION HANDLER
// ===========================================

/**
 * Handle interview completion - stores data and updates counts
 * Call this when an interview finishes (from LiveInterview or InterviewReport)
 * 
 * @param {string} sessionId - Session/Interview ID
 * @param {Object} reportData - Report data from backend or local evaluation
 * @returns {Object} Saved interview record
 */
export function handleInterviewCompletion(sessionId, reportData) {
    console.log('[InterviewStorage] Handling interview completion:', sessionId);

    const record = createInterviewRecord({
        interviewId: sessionId,
        ...reportData,
    });

    saveInterviewToStorage(record);

    return record;
}

/**
 * Mark session as completed (without full report data)
 * Use when navigating to report page before report is generated
 * 
 * @param {string} sessionId - Session ID
 * @param {Object} basicData - Basic interview data (targetRole, date, etc.)
 */
export function markSessionCompleted(sessionId, basicData = {}) {
    const existing = getInterviewById(sessionId);

    if (!existing) {
        // Create a placeholder record that will be updated with full report later
        const record = createInterviewRecord({
            interviewId: sessionId,
            status: 'pending_report',
            targetRole: basicData.targetRole || 'Interview',
            date: basicData.date || new Date().toISOString(),
            score: 0, // Will be updated when report is generated
        });

        saveInterviewToStorage(record);
    }
}

/**
 * Update existing interview record with report data
 * Call this from InterviewReport after report is generated/loaded
 * 
 * @param {string} sessionId - Session ID
 * @param {Object} report - Full report data
 * @returns {Object} Updated interview record
 */
export function updateWithReportData(sessionId, report) {
    console.log('[InterviewStorage] Updating with report data:', sessionId);

    const record = createInterviewRecord({
        interviewId: sessionId,
        score: report.readiness?.score || report.score,
        grade: report.readiness?.grade || report.grade,
        targetRole: report.target_role || report.targetRole,
        date: report.generated_at || report.date || new Date().toISOString(),
        strengths: report.strengths || [],
        weaknesses: report.weaknesses || [],
        improvementTips: report.improvements?.areas || [],
        summary: report.executive_summary || '',
        statistics: report.statistics || {},
        skills: report.skills || {},
        status: 'completed',
    });

    saveInterviewToStorage(record);

    return record;
}

// ===========================================
// HISTORY & DISPLAY HELPERS
// ===========================================

/**
 * Get interview history for dashboard display
 * @param {number} limit - Max number of interviews to return
 * @returns {Array} Array of interview history items
 */
export function getInterviewHistory(limit = 10) {
    const interviews = getStoredInterviews();
    return interviews.slice(0, limit).map(i => ({
        id: i.interviewId,
        job_role: i.targetRole,
        score: i.score,
        status: i.status,
        created_at: i.date,
        grade: i.grade,
    }));
}

/**
 * Get statistics for dashboard
 * @returns {Object} Dashboard statistics
 */
export function getDashboardStats() {
    return getCachedAnalytics();
}

// ===========================================
// SYNC WITH BACKEND (Hybrid approach)
// ===========================================

/**
 * Merge backend data with local storage
 * Call this when backend data is loaded to ensure consistency
 * 
 * @param {Array} backendInterviews - Interviews from backend API
 */
export function syncWithBackend(backendInterviews) {
    if (!backendInterviews || !Array.isArray(backendInterviews)) return;

    const localInterviews = getStoredInterviews();
    const mergedMap = new Map();

    // Add local interviews first
    localInterviews.forEach(i => {
        mergedMap.set(i.interviewId, i);
    });

    // Overlay backend data (takes precedence)
    backendInterviews.forEach(i => {
        const id = i.id || i.session_id || i.interviewId;
        const existing = mergedMap.get(id);

        const record = createInterviewRecord({
            interviewId: id,
            score: i.score || existing?.score,
            grade: i.grade || existing?.grade,
            targetRole: i.job_role || i.target_role || existing?.targetRole,
            date: i.created_at || i.completed_at || existing?.date,
            status: i.status || 'completed',
        });

        mergedMap.set(id, { ...existing, ...record });
    });

    // Save merged data
    const mergedArray = Array.from(mergedMap.values())
        .sort((a, b) => new Date(b.date) - new Date(a.date));

    localStorage.setItem(HISTORY_KEY, JSON.stringify(mergedArray.slice(0, 100)));
    updateAnalyticsCache(mergedArray);
}

/**
 * Clear all interview storage (for logout)
 */
export function clearInterviewStorage() {
    localStorage.removeItem(HISTORY_KEY);
    localStorage.removeItem(ANALYTICS_KEY);
    localStorage.removeItem(STORAGE_KEY);
}

export default {
    createInterviewRecord,
    getStoredInterviews,
    saveInterviewToStorage,
    getInterviewById,
    deleteInterviewFromStorage,
    getCachedAnalytics,
    handleInterviewCompletion,
    markSessionCompleted,
    updateWithReportData,
    getInterviewHistory,
    getDashboardStats,
    syncWithBackend,
    clearInterviewStorage,
};