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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83c2a9a
 
 
 
6c2d132
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import { FastifyInstance } from 'fastify';
import { prisma } from '../services/prisma';
import { whatsappQueue } from '../services/queue';
import { z } from 'zod';

// ─── Zod Schemas ───────────────────────────────────────────────────────────────
const TrackSchema = z.object({
    title: z.string().min(1),
    description: z.string().optional(),
    duration: z.number().int().positive(),
    language: z.enum(['FR', 'WOLOF']).default('FR'),
    isPremium: z.boolean().default(false),
    priceAmount: z.number().int().optional(),
    stripePriceId: z.string().optional(),
});

const TrackDaySchema = z.object({
    dayNumber: z.number().int().positive(),
    title: z.string().optional(),
    lessonText: z.string().optional(),
    audioUrl: z.string().url().optional().or(z.literal('')),
    exerciseType: z.enum(['TEXT', 'AUDIO', 'BUTTON']).default('TEXT'),
    exercisePrompt: z.string().optional(),
    validationKeyword: z.string().optional(),
    buttonsJson: z.array(z.object({ id: z.string(), title: z.string() })).optional(),
    unlockCondition: z.string().optional(),
});

const OverrideFeedbackSchema = z.object({
    userId: z.string(),
    trackId: z.string(),
    transcription: z.string().min(1),
    overrideAudioUrl: z.string().url(),
    adminId: z.string()
});

export async function adminRoutes(fastify: FastifyInstance) {

    // ── Dashboard Stats ────────────────────────────────────────────────────────
    fastify.get('/stats', async () => {
        const [totalUsers, activeEnrollments, completedEnrollments, totalTracks, totalRevenue] = await Promise.all([
            prisma.user.count(),
            prisma.enrollment.count({ where: { status: 'ACTIVE' } }),
            prisma.enrollment.count({ where: { status: 'COMPLETED' } }),
            prisma.track.count(),
            prisma.payment.aggregate({ where: { status: 'COMPLETED' }, _sum: { amount: true } }),
        ]);
        return { totalUsers, activeEnrollments, completedEnrollments, totalTracks, totalRevenue: totalRevenue._sum.amount || 0 };
    });

    // ── Users ──────────────────────────────────────────────────────────────────
    fastify.get('/users', async (req) => {
        const query = req.query as { page?: string; limit?: string };
        const page = Math.max(1, parseInt(query.page || '1'));
        const limit = Math.min(100, parseInt(query.limit || '50'));

        const [users, total] = await Promise.all([
            prisma.user.findMany({
                orderBy: { createdAt: 'desc' },
                skip: (page - 1) * limit,
                take: limit,
                include: {
                    enrollments: { include: { track: true }, orderBy: { startedAt: 'desc' }, take: 1 },
                    _count: { select: { enrollments: true, responses: true } }
                }
            }),
            prisma.user.count()
        ]);
        return { users, total, page, limit };
    });

    fastify.get('/users/:userId/messages', async (req, reply) => {
        const { userId } = req.params as { userId: string };
        const messages = await prisma.message.findMany({
            where: { userId },
            orderBy: { createdAt: 'asc' },
        });

        const user = await prisma.user.findUnique({
            where: { id: userId },
            select: { id: true, name: true, phone: true }
        });

        if (!user) return reply.status(404).send({ error: 'User not found' });

        return { user, messages };
    });

    // ── Enrollments ────────────────────────────────────────────────────────────
    fastify.get('/enrollments', async () => {
        const enrollments = await prisma.enrollment.findMany({
            include: { user: true, track: true },
            orderBy: { startedAt: 'desc' },
            take: 100,
        });
        return enrollments;
    });

    // ── Human-in-the-Loop / Audio Overdrive ────────────────────────────────────

    // LIVE FEED : Students blocked waiting for manual review
    // LIVE FEED : Students blocked waiting for manual review
    fastify.get('/live-feed', async () => {
        const pendingReviews = await prisma.userProgress.findMany({
            where: {
                exerciseStatus: 'PENDING_REVIEW',
                user: { language: 'WOLOF' } // Currently only focusing on Wolof interceptions
            },
            include: {
                user: { select: { id: true, name: true, phone: true, activity: true, language: true } },
                track: { select: { id: true, title: true } }
            },
            orderBy: { updatedAt: 'asc' }
        });

        // Map the raw payload to find the actual response audio for each pending review
        const liveFeed = await Promise.all(pendingReviews.map(async (progress) => {
            const enrollment = await prisma.enrollment.findFirst({
                where: { userId: progress.userId, trackId: progress.trackId, status: 'ACTIVE' }
            });

            // If no active enrollment found, fallback gracefully
            if (!enrollment) return { ...progress, lastResponse: null };

            // Find the most recent response from this user for this enrollment
            const lastResponse = await prisma.response.findFirst({
                where: { userId: progress.userId, enrollmentId: enrollment.id },
                orderBy: { createdAt: 'desc' }
            });

            return {
                ...progress,
                audioUrl: lastResponse?.mediaUrl || null,
                content: lastResponse?.content || null,
                dayNumber: lastResponse?.dayNumber || Math.floor(enrollment.currentDay)
            };
        }));

        return liveFeed;
    });

    // OVERRIDE ACTION : Admin posts the manual review
    fastify.post('/override-feedback', async (req, reply) => {
        const body = OverrideFeedbackSchema.safeParse(req.body);
        if (!body.success) return reply.code(400).send({ error: body.error.flatten() });

        const { userId, trackId, transcription, overrideAudioUrl, adminId } = body.data;

        // 1. Update UserProgress status & logs
        const progress = await prisma.userProgress.update({
            where: { userId_trackId: { userId, trackId } },
            data: {
                exerciseStatus: 'COMPLETED',
                adminTranscription: transcription,
                overrideAudioUrl: overrideAudioUrl,
                reviewedBy: adminId
            }
        });

        // 2. Update BusinessProfile with human-cleaned transcription
        const enrollment = await prisma.enrollment.findFirst({
            where: { userId, trackId, status: 'ACTIVE' }
        });

        const currentDay = enrollment ? Math.floor(enrollment.currentDay) : 0;

        await prisma.businessProfile.upsert({
            where: { userId },
            update: { lastUpdatedFromDay: currentDay },
            create: { userId, lastUpdatedFromDay: currentDay }
        });

        // 3. Dispatch Background Job (Audio Delivery + Next Day Increment)
        await whatsappQueue.add('send-admin-audio-override', {
            userId,
            trackId,
            overrideAudioUrl,
            adminId
        });

        return reply.code(200).send({ ok: true, progress });
    });

    // ══════════════════════════════════════════════════════════════════════════
    // TRACKS CRUD
    // ══════════════════════════════════════════════════════════════════════════

    // List tracks
    fastify.get('/tracks', async () => {
        return prisma.track.findMany({
            include: { _count: { select: { days: true, enrollments: true } } },
            orderBy: { createdAt: 'desc' }
        });
    });

    // Get single track with all days
    fastify.get<{ Params: { id: string } }>('/tracks/:id', async (req, reply) => {
        const track = await prisma.track.findUnique({
            where: { id: req.params.id },
            include: { days: { orderBy: { dayNumber: 'asc' } } }
        });
        if (!track) return reply.code(404).send({ error: 'Track not found' });
        return track;
    });

    // Create track
    fastify.post('/tracks', async (req, reply) => {
        const body = TrackSchema.safeParse(req.body);
        if (!body.success) return reply.code(400).send({ error: body.error.flatten() });
        const track = await prisma.track.create({ data: body.data });
        return reply.code(201).send(track);
    });

    // Update track
    fastify.put<{ Params: { id: string } }>('/tracks/:id', async (req, reply) => {
        const body = TrackSchema.partial().safeParse(req.body);
        if (!body.success) return reply.code(400).send({ error: body.error.flatten() });
        try {
            const track = await prisma.track.update({ where: { id: req.params.id }, data: body.data });
            return track;
        } catch {
            return reply.code(404).send({ error: 'Track not found' });
        }
    });

    // Delete track
    fastify.delete<{ Params: { id: string } }>('/tracks/:id', async (req, reply) => {
        try {
            await prisma.trackDay.deleteMany({ where: { trackId: req.params.id } });
            await prisma.track.delete({ where: { id: req.params.id } });
            return { ok: true };
        } catch {
            return reply.code(404).send({ error: 'Track not found' });
        }
    });

    // ── STT Quality Calibration Endpoint ───────────────────────────────────────
    fastify.get('/stats/confidence-distribution', async (_req, reply) => {
        const fs = require('fs');
        const path = require('path');
        const statsPath = path.join(__dirname, '../../data/calibration_stats.json');

        try {
            if (fs.existsSync(statsPath)) {
                const data = JSON.parse(fs.readFileSync(statsPath, 'utf8'));
                return data;
            } else {
                return reply.code(404).send({ error: "Calibration not run yet", message: "Le fichier calibration_stats.json est manquant. Lancez runCalibration()." });
            }
        } catch (err: unknown) {
            return reply.code(500).send({ error: (err instanceof Error ? (err instanceof Error ? err.message : String(err)) : String(err)) });
        }
    });

    // ══════════════════════════════════════════════════════════════════════════
    // TRACK DAYS CRUD
    // ══════════════════════════════════════════════════════════════════════════

    // List days for a track
    fastify.get<{ Params: { trackId: string } }>('/tracks/:trackId/days', async (req) => {
        return prisma.trackDay.findMany({
            where: { trackId: req.params.trackId },
            orderBy: { dayNumber: 'asc' }
        });
    });

    // Create day
    fastify.post<{ Params: { trackId: string } }>('/tracks/:trackId/days', async (req, reply) => {
        const body = TrackDaySchema.safeParse(req.body);
        if (!body.success) return reply.code(400).send({ error: body.error.flatten() });
        const day = await prisma.trackDay.create({
            data: {
                ...body.data,
                trackId: req.params.trackId,
                audioUrl: body.data.audioUrl || null,
                buttonsJson: body.data.buttonsJson ? body.data.buttonsJson : undefined
            }
        });
        return reply.code(201).send(day);
    });

    // Update day
    fastify.put<{ Params: { trackId: string; dayId: string } }>('/tracks/:trackId/days/:dayId', async (req, reply) => {
        const body = TrackDaySchema.partial().safeParse(req.body);
        if (!body.success) return reply.code(400).send({ error: body.error.flatten() });
        try {
            const day = await prisma.trackDay.update({
                where: { id: req.params.dayId },
                data: { ...body.data, audioUrl: body.data.audioUrl === '' ? null : body.data.audioUrl }
            });
            return day;
        } catch {
            return reply.code(404).send({ error: 'Day not found' });
        }
    });

    // Delete day
    fastify.delete<{ Params: { trackId: string; dayId: string } }>('/tracks/:trackId/days/:dayId', async (req, reply) => {
        try {
            await prisma.trackDay.delete({ where: { id: req.params.dayId } });
            return { ok: true };
        } catch {
            return reply.code(404).send({ error: 'Day not found' });
        }
    });

    // ── Training Lab Endpoints ───────────────────────────────────────────────

    // Get pending audios for training
    fastify.get('/training/audios', async (_req, reply) => {
        const pending = await prisma.trainingData.findMany({
            where: { status: 'PENDING' },
            orderBy: { createdAt: 'desc' }
        });
        return reply.send(pending);
    });

    // Submit a manual correction
    fastify.post('/training/submit', async (req, reply) => {
        const schema = z.object({
            id: z.string().uuid().optional(),
            audioUrl: z.string(),
            transcription: z.string(),
            manualCorrection: z.string()
        });
        const body = schema.safeParse(req.body);
        if (!body.success) return reply.code(400).send({ error: body.error.flatten() });

        const calculateWER = (reference: string, hypothesis: string): number => {
            const levenshtein = require('fast-levenshtein');
            const refWords = reference.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(/\s+/).filter(w => w);
            const hypWords = hypothesis.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(/\s+/).filter(w => w);
            if (refWords.length === 0) return 0;
            const wordMap = new Map<string, string>();
            let charCode = 0xE000;
            const getChar = (word: string) => {
                if (!wordMap.has(word)) wordMap.set(word, String.fromCharCode(charCode++));
                return wordMap.get(word)!;
            };
            const refChars = refWords.map(getChar).join('');
            const hypChars = hypWords.map(getChar).join('');
            return levenshtein.get(refChars, hypChars) / refWords.length;
        };

        const { normalizeWolof } = require('../scripts/normalizeWolof');
        const normResult = normalizeWolof(body.data.transcription);

        const rawWER = calculateWER(body.data.manualCorrection, body.data.transcription);
        const normalizedWER = calculateWER(body.data.manualCorrection, normResult.normalizedText);

        // Analyze missing words
        const manualWords = body.data.manualCorrection.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(/\s+/).filter(w => w);
        const normWords = normResult.normalizedText.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(/\s+/).filter((w: string) => w);
        // missingWords = elements in manual that are completely absent in normalized
        const missingWords = Array.from(new Set(manualWords.filter((w: string) => !normWords.includes(w))));

        const data = await prisma.trainingData.upsert({
            where: { id: body.data.id || '00000000-0000-0000-0000-000000000000' },
            update: {
                manualCorrection: body.data.manualCorrection,
                rawWER,
                normalizedWER,
                status: 'REVIEWED'
            },
            create: {
                audioUrl: body.data.audioUrl,
                transcription: body.data.transcription,
                manualCorrection: body.data.manualCorrection,
                rawWER,
                normalizedWER,
                status: 'REVIEWED'
            }
        });

        return reply.send({ data, missingWords, rawWER, normalizedWER });
    });

    // Suggest new dictionary rules from TrainingData
    fastify.get('/training/suggestions', async (_req, reply) => {
        const diff = require('diff');
        const trainingData = await prisma.trainingData.findMany({
            where: { status: 'REVIEWED' }
        });

        const substitutionCounts: Record<string, { original: string, replacement: string, count: number }> = {};

        trainingData.forEach(item => {
            if (!item.manualCorrection) return;
            const changes = diff.diffWords(item.transcription, item.manualCorrection);

            // Look for adjacent pairs of [removed] then [added]
            for (let i = 0; i < changes.length - 1; i++) {
                if (changes[i].removed && changes[i + 1].added) {
                    const original = changes[i].value.trim().toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "");
                    const replacement = changes[i + 1].value.trim().toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "");

                    if (original && replacement && original !== replacement && original.split(' ').length === 1 && replacement.split(' ').length === 1) {
                        const key = `${original}->${replacement}`;
                        if (!substitutionCounts[key]) substitutionCounts[key] = { original, replacement, count: 0 };
                        substitutionCounts[key].count++;
                    }
                }
            }
        });

        const suggestions = Object.values(substitutionCounts)
            .sort((a, b) => b.count - a.count)
            .slice(0, 20);

        return reply.send(suggestions);
    });

    // Apply suggestions directly into normalizeWolof.ts files
    fastify.post('/training/apply-suggestions', async (req, reply) => {
        const schema = z.object({
            suggestions: z.array(z.object({
                original: z.string(),
                replacement: z.string()
            }))
        });
        const body = schema.safeParse(req.body);
        if (!body.success) return reply.code(400).send({ error: body.error.flatten() });

        if (body.data.suggestions.length === 0) return reply.send({ ok: true, message: "No suggestions provided" });

        const fs = require('fs');
        const path = require('path');

        const targetFiles = [
            path.join(__dirname, '../scripts/normalizeWolof.ts'),
            path.join(__dirname, '../../../whatsapp-worker/src/normalizeWolof.ts')
        ];

        let rulesToInject = "";
        body.data.suggestions.forEach(s => {
            rulesToInject += `    "${s.original}": "${s.replacement}",\n`;
        });

        for (const file of targetFiles) {
            if (fs.existsSync(file)) {
                let content = fs.readFileSync(file, 'utf8');
                const insertPos = content.indexOf('const NORMALIZATION_RULES: Record<string, string> = {\n');
                if (insertPos !== -1) {
                    const offset = insertPos + 'const NORMALIZATION_RULES: Record<string, string> = {\n'.length;
                    content = content.slice(0, offset) + rulesToInject + content.slice(offset);
                    fs.writeFileSync(file, content, 'utf8');
                }
            }
        }

        // Auto-recalculate WER after injection
        return reply.send({ ok: true, injectedCount: body.data.suggestions.length });
    });

    // Recalculate WER across all reviewed TrainingData with the current dictionary
    fastify.post('/training/recalculate-wer', async (_req, reply) => {
        const trainingData = await prisma.trainingData.findMany({
            where: { status: 'REVIEWED' }
        });

        const calculateWER = (reference: string, hypothesis: string): number => {
            const levenshtein = require('fast-levenshtein');
            const refWords = reference.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(/\s+/).filter(w => w);
            const hypWords = hypothesis.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "").split(/\s+/).filter(w => w);
            if (refWords.length === 0) return 0;
            const wordMap = new Map<string, string>();
            let charCode = 0xE000;
            const getChar = (word: string) => {
                if (!wordMap.has(word)) wordMap.set(word, String.fromCharCode(charCode++));
                return wordMap.get(word)!;
            };
            const refChars = refWords.map(getChar).join('');
            const hypChars = hypWords.map(getChar).join('');
            return levenshtein.get(refChars, hypChars) / refWords.length;
        };

        // We need to bust the require cache to load the newly written normalizeWolof.ts
        const normalizeWolofPath = require.resolve('../scripts/normalizeWolof');
        delete require.cache[normalizeWolofPath];
        const { normalizeWolof } = require('../scripts/normalizeWolof');

        let totalRawWER = 0;
        let totalNormalizedWER = 0;
        let count = 0;

        for (const item of trainingData) {
            if (!item.manualCorrection) continue;

            const rawWER = calculateWER(item.manualCorrection, item.transcription);
            const normResult = normalizeWolof(item.transcription);
            const normalizedWER = calculateWER(item.manualCorrection, normResult.normalizedText);

            await prisma.trainingData.update({
                where: { id: item.id },
                data: { rawWER, normalizedWER }
            });

            totalRawWER += rawWER;
            totalNormalizedWER += normalizedWER;
            count++;
        }

        const avgRaw = count > 0 ? totalRawWER / count : 0;
        const avgNorm = count > 0 ? totalNormalizedWER / count : 0;

        return reply.send({
            processed: count,
            avgRawWER: avgRaw,
            avgNormalizedWER: avgNorm,
            improvementPercent: count > 0 && avgRaw > 0 ? ((avgRaw - avgNorm) / avgRaw) * 100 : 0
        });
    });

    fastify.post('/training/upload', async (_req, reply) => {
        // Just a placeholder until full R2 integration for standalone uploads
        return reply.code(501).send({ error: "Not Implemented Yet" });
    });
}