File size: 55,353 Bytes
99ddd4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
import express from "express";
import path from "path";
import fs from "fs";
import { GoogleGenAI, Type } from "@google/genai";
import dotenv from "dotenv";
import multer from "multer";

dotenv.config();

// Create uploads directory if it doesn't exist
const uploadsDir = path.join(process.cwd(), "uploads");
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// Multer storage setup
const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadsDir);
  },
  filename: (req, file, cb) => {
    // Sanitary file name replacement to ensure it's ASCII/URL safe
    const safeName = file.originalname.replace(/[^a-zA-Z0-9.\-_]/g, "_");
    cb(null, `${Date.now()}_${safeName}`);
  }
});

// Configure upload limits - up to 1GB
const upload = multer({
  storage: multerStorage,
  limits: { fileSize: 1024 * 1024 * 1024 } // 1GB limit
});

let aiClient: GoogleGenAI | null = null;

function getGeminiClient(): GoogleGenAI {
  if (!aiClient) {
    const apiKey = process.env.GEMINI_API_KEY;
    if (!apiKey) {
      console.warn("WARN: GEMINI_API_KEY is not defined in environment variables.");
    }
    aiClient = new GoogleGenAI({
      apiKey: apiKey || "MOCK_KEY_UNUSED",
      httpOptions: {
        headers: {
          'User-Agent': 'aistudio-build',
        }
      }
    });
  }
  return aiClient;
}

// Helper function to call generateContent with retry and fallback models to prevent 503 UNAVAILABLE errors
async function generateContentWithFallback(client: GoogleGenAI, originalParams: any) {
  const modelsToTry = [
    "gemini-3.5-flash",
    "gemini-3.1-flash-lite",
    "gemini-flash-latest"
  ];
  
  let lastError: any = null;
  
  for (const modelName of modelsToTry) {
    let retries = 2; // 2 retries per model
    while (retries >= 0) {
      try {
        const response = await client.models.generateContent({
          ...originalParams,
          model: modelName
        });
        return response;
      } catch (err: any) {
        lastError = err;
        const errMsg = String(err.message || err);
        console.warn(`Attempt with model ${modelName} failed (retries left: ${retries}). Error: ${errMsg}`);
        
        // If it's a 503 (Overloaded / Unavailable) or 429 (Rate limit) or "high demand"
        if (
          errMsg.includes("503") || 
          errMsg.includes("UNAVAILABLE") || 
          errMsg.includes("429") || 
          errMsg.includes("RESOURCE_EXHAUSTED") ||
          errMsg.includes("demand") ||
          errMsg.includes("overloaded") ||
          errMsg.includes("spikes")
        ) {
          retries--;
          if (retries >= 0) {
            const waitTime = (2 - retries) * 1000; // 1000ms, then 2000ms
            await new Promise((resolve) => setTimeout(resolve, waitTime));
            continue;
          }
        } else {
          // For syntax / user-facing errors, don't retry, just fail-over early or throw
          break;
        }
      }
    }
  }
  
  throw lastError || new Error("All Gemini models failed to generate content.");
}

async function startServer() {
  const app = express();
  const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;

  // Increase payload limit to receive base64 images of handwritten homework
  app.use(express.json({ limit: "50mb" }));
  app.use(express.urlencoded({ limit: "50mb", extended: true }));

  // Enable CORS globally to handle cross-subdomain requests safely (e.g. from dev to pre subdomains and iframes)
  app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Range");
    res.setHeader("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges");
    if (req.method === "OPTIONS") {
      res.sendStatus(204);
      return;
    }
    next();
  });

  // Serve static uploaded files locally with cross-origin & flawless HTML5 video range-request streaming support
  app.get("/uploads/:filename", (req, res) => {
    try {
      const fileName = req.params.filename;
      const filePath = path.join(uploadsDir, fileName);

      // Prevent directory traversal attacks
      if (!filePath.startsWith(uploadsDir)) {
        return res.status(403).send("Ruxsat etilmagan kirish.");
      }

      if (!fs.existsSync(filePath)) {
        return res.status(404).send("Fayl topilmadi.");
      }

      // Add full CORS and stream support headers
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
      res.setHeader("Access-Control-Allow-Headers", "Range, Content-Type, Authorization");
      res.setHeader("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges");
      res.setHeader("Accept-Ranges", "bytes");

      // Express res.sendFile natively handles:
      // - Correct MIME type detection using extensive mime DB (handles uppercase, mov, webm, mp4, etc.)
      // - Browser range requests with HTTP 206 Partial Content out of the box
      // - Full handshake for Safari/Chrome media pre-flight requests
      return res.sendFile(filePath);
    } catch (err: any) {
      console.error(" uploads streaming handler error:", err);
      if (!res.headersSent) {
        res.status(500).send("Faylni uzatish xatosi.");
      }
    }
  });

  // Fallback static files middleware just in case
  app.use("/uploads", express.static(uploadsDir, {
    setHeaders: (res) => {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
      res.setHeader("Access-Control-Allow-Headers", "Range, Content-Type, Authorization");
      res.setHeader("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges");
      res.setHeader("Accept-Ranges", "bytes");
    }
  }));

  // local file upload endpoint
  app.post("/api/upload", upload.single("file"), (req, res) => {
    try {
      if (!req.file) {
        return res.status(400).json({ success: false, error: "Fayl yuklanmadi." });
      }
      const fileUrl = `/uploads/${req.file.filename}`;
      res.json({
        success: true,
        fileUrl: fileUrl,
        size: req.file.size,
        mimetype: req.file.mimetype,
        originalname: req.file.originalname
      });
    } catch (err: any) {
      console.error("Local upload api error:", err);
      res.status(500).json({ success: false, error: err.message });
    }
  });

  // chunked file upload endpoint to handle large payloads and avoid 413 Entity Too Large errors
  app.post("/api/upload-chunk", upload.single("chunk"), (req, res) => {
    try {
      const { uploadId, chunkIndex, totalChunks, fileName } = req.body;
      if (!req.file) {
        return res.status(400).json({ success: false, error: "Chunk file was not uploaded." });
      }

      const cIdx = parseInt(chunkIndex, 10);
      const totChunks = parseInt(totalChunks, 10);

      // Create a temporary directory for chunks
      const chunkDir = path.join(uploadsDir, `temp_${uploadId}`);
      if (!fs.existsSync(chunkDir)) {
        fs.mkdirSync(chunkDir, { recursive: true });
      }

      // Move uploaded chunk file of this index inside the temporary dir
      const chunkPath = path.join(chunkDir, `chunk_${cIdx}`);
      try {
        fs.renameSync(req.file.path, chunkPath);
      } catch (renameErr) {
        console.warn("fs.renameSync failed, falling back to copyFileSync:", renameErr);
        fs.copyFileSync(req.file.path, chunkPath);
        try {
          fs.unlinkSync(req.file.path);
        } catch (unlinkErr) {
          console.warn("Could not remove source file after copying:", unlinkErr);
        }
      }

      // If it's the last chunk, assemble all parts
      if (cIdx === totChunks - 1) {
        // Create final file name
        const safeName = fileName.replace(/[^a-zA-Z0-9.\-_]/g, "_");
        const finalFileName = `${Date.now()}_${safeName}`;
        const finalFilePath = path.join(uploadsDir, finalFileName);

        // Delete any existing file at this path
        if (fs.existsSync(finalFilePath)) {
          fs.unlinkSync(finalFilePath);
        }

        // Assemble all chunks synchronously to guarantee the file is fully written before response
        for (let i = 0; i < totChunks; i++) {
          const currentChunkPath = path.join(chunkDir, `chunk_${i}`);
          if (!fs.existsSync(currentChunkPath)) {
            return res.status(500).json({ success: false, error: `Missing chunk at index ${i}` });
          }
          const data = fs.readFileSync(currentChunkPath);
          fs.appendFileSync(finalFilePath, data);
          // Delete chunk file immediately to clean space
          fs.unlinkSync(currentChunkPath);
        }

        // Clean up the temp directory
        try {
          fs.rmdirSync(chunkDir);
        } catch (e) {
          console.warn("Could not remove temp chunk directory:", e);
        }

        return res.json({
          success: true,
          fileUrl: `/uploads/${finalFileName}`,
          assembled: true
        });
      }

      return res.json({
        success: true,
        assembled: false,
        chunkIndex: cIdx
      });
    } catch (err: any) {
      console.error("Chunked upload error:", err);
      res.status(500).json({ success: false, error: err.message });
    }
  });

  // Dynamic lesson contents creator using real Gemini AI
  app.post("/api/generate-lesson-content", async (req, res) => {
    const { language, level, topic, title } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      // Return high quality pre-saved/simulated fallback if no Gemini key is provided, ensuring seamless UX
      return res.json(getFallbackLesson(language, level, topic, title));
    }

    try {
      const client = getGeminiClient();
      const prompt = `Siz chet tillarini o'rgatuvchi professional AI o'qituvchisiz.
Mavzu: "${title}" (Kategoriya: ${topic}, Daraja: ${level}, O'rganilayotgan til: ${language === 'en' ? 'Ingliz tili' : 'Rus tili'}).
Foydalanuvchi interfeysi tili: O'zbekcha.

Quyidagi tuzilmaga ega to'liq dars materialini JSON formatida yaratib bering:
1. "explanation": Dynamic dars tushuntirishi (Markdown strukturada, chiroyli qoidalari, misollar jadvali va o'rgatuvchi tushuntirishlari bilan O'zbek tilida).
2. "exercises": 2 ta mashiq. Har bir mashiq ichida aniq 6 tadan gap bo'lsin. Har bir gapda darsga aloqador 1 ta so'z/iborani tushirib qoldiring (masalan, "I _____ to school" yoki "Я _____ в школу"). Ushbu blank uchun 4 ta variant ("options") taqdim etilsin va to'g'ri javob indexi ("correctOption", 0 dan 3 gacha bo'lgan raqam) belgilansin.
3. "homework": 1 ta amaliy uyga vazifa ko'rsatmasi. Foydalanuvchidan buni qog'ozga yozib rasmga tushirishi so'ralishi kerak (moroqli va ijodiy topshiriq).

JSON formati quyidagicha bo'lsin:
{
  "explanation": "...",
  "exercises": [
    {
      "title": "Mashiq 1: ...",
      "questions": [
        { "sentence": "...", "options": ["...", "...", "...", "..."], "correctOption": 1 }
      ]
    },
    {
      "title": "Mashiq 2: ...",
      "questions": [
        { "sentence": "...", "options": ["...", "...", "...", "..."], "correctOption": 2 }
      ]
    }
  ],
  "homework": "..."
}`;// @ts-ignore

      const response = await generateContentWithFallback(client, {
        contents: prompt,
        config: {
          responseMimeType: "application/json",
          responseSchema: {
            type: Type.OBJECT,
            properties: {
              explanation: { type: Type.STRING },
              exercises: {
                type: Type.ARRAY,
                items: {
                  type: Type.OBJECT,
                  properties: {
                    title: { type: Type.STRING },
                    questions: {
                      type: Type.ARRAY,
                      items: {
                        type: Type.OBJECT,
                        properties: {
                          sentence: { type: Type.STRING },
                          options: {
                            type: Type.ARRAY,
                            items: { type: Type.STRING }
                          },
                          correctOption: { type: Type.INTEGER }
                        },
                        required: ["sentence", "options", "correctOption"]
                      }
                    }
                  },
                  required: ["title", "questions"]
                }
              },
              homework: { type: Type.STRING }
            },
            required: ["explanation", "exercises", "homework"]
          }
        }
      });

      const responseText = response.text;
      if (responseText) {
        const parsedData = JSON.parse(responseText.trim());
        return res.json({ success: true, data: parsedData });
      } else {
        throw new Error("Bo'sh javob qaytdi.");
      }
    } catch (error: any) {
      console.error("Gemini lesson generation error:", error);
      return res.json({
        success: false,
        error: error.message,
        fallback: getFallbackLesson(language, level, topic, title).data
      });
    }
  });

  // AI Chat API route
  app.post("/api/chat", async (req, res) => {
    const { messages, language } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      // Fallback simple simulation response
      const lastMsg = messages && messages.length > 0 ? messages[messages.length - 1].content : "";
      return res.json({
        success: true,
        reply: `**[Simulyatsiya rejimi - API kalit topilmadi]**

Sizning savolingiz: *"${lastMsg}"*

Men **BilimWay AI** aqlli yordamchisiman. Chet tillarini qulay o'rganishingiz uchun xizmat qilaman! 🌟
Haqiqiy sun'iy intellekt javobini olish uchun AI Studio Secrets qismida \`GEMINI_API_KEY\` ni sozlang.

Sizga ${language === 'en' ? 'Ingliz tili' : 'Rus tili'} bo'yicha yordam berishdan mamnunman! Qanday savolingiz bor?`
      });
    }

    try {
      const client = getGeminiClient();
      const contents = messages.map((m: any) => ({
        role: m.role === 'user' ? 'user' : 'model',
        parts: [{ text: m.content || "" }]
      }));

      const sysInstruction = `Siz 'BilimWay AI' ilovasining aqlli va yordamchi chatbotisiz. Foydalanuvchilar siz bilan asosan zamonaviy tillarni o'rganish, savol-javob va matnlar ustida ishlash uchun muloqot qilishadi. Sizning javoblaringiz mobil telefon ekranida o'qishga juda qulay bo'lishi shart.

Muloqot va matn ko'rinishi qoidalari:
1. Qisqalik va aniqlik: Gapni ko'p aylantirmasdan, savolga to'g'ridan-to'g'ri va qisqa javob bering. Uzun matnlarni o'qish mobil ekranda noqulay.
2. Tuzilma (Struktura): Katta matnli devorlar (dense text) yaratmang. Matnni doimo paragraflarga bo'ling, muhim joylarni bold (to'q rangda) qiling va sanab o'tishda emoji yoki bullet pointlardan (*) foydalaning.
3. Formatlash: Agar jadval kerak bo'lsa, ixcham Markdown jadvallaridan foydalaning. Kod yozsangiz, tushunarli bloklar ichiga oling.
4. Ohang: Foydalanuvchiga samimiy, rag'batlantiruvchi va do'stona munosabatda bo'ling. Murakkab qoidalarni eng sodda tilda tushuntiring.
5. Til: Foydalanuvchi qaysi tilda murojaat qilsa (o'zbek, rus, ingliz), aynan o'sha tilda javob qaytaring.`;

      const response = await generateContentWithFallback(client, {
        contents: contents,
        config: {
          systemInstruction: sysInstruction
        }
      });

      return res.json({ success: true, reply: response.text || "Kechirasiz, sun'iy intellektdan javob ololmadim." });
    } catch (error: any) {
      console.error("AI Chat error:", error);
      return res.json({ success: false, error: error.message });
    }
  });

  // Deep Topic Study Chat API
  app.post("/api/study-chat", async (req, res) => {
    const { messages, language, topic } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      const lastMsg = messages && messages.length > 0 ? messages[messages.length - 1].content : "";
      return res.json({
        success: true,
        reply: `**[Simulyatsiya rejimi]**

Ushbu dars mavzusi: **"${topic}"** bo'yicha tahliliy muloqot (Dars tili: ${language === 'uz' ? "O'zbek tili" : language === 'ru' ? "Rus tili" : "Ingliz tili"}).

Siz so'ragan qoida bo'yicha qisqacha tushuntirish:
Ushbu darsda mavzu chuqur tushuntirilishi lozim, ammo hozirda simulyatsiya rejimida ishlanmoqda.
Mavzu bo'yicha to'liq dars tushuntirib bo'lindi.

**Sizga test va mashqlar tuzib beraymi?**
Marhamat, menga nechta test va nechta mashq kerakligini yozing (Masalan: "3 ta test va 2 ta mashq tuzib ber" deb yuboring), men dars mavzusi doirasida aynan siz aytgan sondagicha test va mashqlarni tuzib beraman!`
      });
    }

    try {
      const client = getGeminiClient();
      const contents = messages.map((m: any) => ({
        role: m.role === 'user' ? 'user' : 'model',
        parts: [{ text: m.content || "" }]
      }));

      const sysInstruction = `Siz 'BilimWay AI' darslik platformasining "Chuqur Mavzu Darsi" o'qituvchi chatbotisiz. Vazifangiz foydalanuvchilar tanlagan yoki so'ragan til o'rganish mavzularini (Masalan: Present Perfect, Artikllar, Harakat Fe'llari va h.k.) juda chuqur, batafsil, jadvallar va hayotiy misollar yordamida o'rgatishdir.

MULOQOT STRUKTURASI VA QOIDALAR:
1. Birinchi marta dars boshlanganda, foydalanuvchi so'ragan "${topic}" mavzusini mukammal, o'ta qiziqarli va batafsil tushuntirib bering. Iloji boricha Markdown jadvallari, qoidalar, o'zbekcha tarjimalar va muloqot iboralaridan foydalaning.
2. Mavzu tushuntirib bo'lingach, xabar oxirida FOYDALANUVCHIDAN ALBATTA ushbu iborani yoki unga yaqin ma'nodagi savolni so'rang:
   "Sizga test va mashqlar tuzib beraymi?"
3. Agar foydalanuvchi sizdan ma'lum miqdorda test va mashqlar tuzib berishni so'rasa, masalan: "3 ta test va 2 ta mashq" yoki "5 ta test" yoki "2 ta mashq" va h.k. deb yozsa:
   - Soni esingizdan chiqib ketmasligi juda muhim! Foydalanuvchi aytgan sonni qat'iy yodda tuting.
   - Kiritilgan sonigacha borib, aynan o'sha miqdordagi testlarni (variantlari: A, B, C, D va to'g'ri javobi bilan) va mashqlarni (gaplar tarjimasi, bo'shliqni to'ldirish yoki gap tuzish kabi qiziqarli mashqlar) tuzib berasiz.
   - Testlar va mashqlarning javoblarini dars oxirida (yoki foydalanuvchi tekshirishni so'raganda) taqdim eting.
4. Javob berishda dars tili: ${language === 'uz' ? "O'zbek tili" : language === 'ru' ? "Rus tili" : "Ingliz tili"} bo'lsin. Juda sodda, tushunarli, aniq tushuntiring va muloqotni do'stona tarzda olib boring. Matematik aniqlik bilan test/mashqlar soniga amal qiling.`;

      const response = await generateContentWithFallback(client, {
        contents: contents,
        config: {
          systemInstruction: sysInstruction
        }
      });

      return res.json({ success: true, reply: response.text || "Kechirasiz, sun'iy intellektdan dars javobini ololmadim." });
    } catch (error: any) {
      console.error("Study Chat error:", error);
      return res.json({ success: false, error: error.message });
    }
  });

  // Deep Topic Study API
  app.post("/api/study-topic", async (req, res) => {
    const { topic, explanationLanguage } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      return res.json(getFallbackStudyTopic(topic, explanationLanguage));
    }

    try {
      const client = getGeminiClient();
      const prompt = `Foydalanuvchi o'rganmoqchi bo'lgan maxsus dars mavzusi: "${topic}".
Tushuntirish va dars tili: ${explanationLanguage === 'uz' ? 'O\'zbek tili (Uzbek)' : explanationLanguage === 'ru' ? 'Rus tili (Russian)' : 'Ingliz tili (English)'}.

Iltimos, ushbu darsni barcha grammatical/vocabulary qoidalari, real hayotiy misollari, jadvallari va tushunarli sodda uslubda mukammal tushuntirib bering.
Shuningdek, ushbu darsga oid to'liq mashiq qilish uchun aniq 4 ta interaktiv test savollarini hamda 1 ta qiziqarli amaliy yozma/rasmli uyga vazifa topshirig'ini yaratib bering.

Javobni quyidagi qat'iy JSON formatida qaytaring:
{
  "topicTitle": "${topic}",
  "explanation": "Markdown formatda batafsil dars qo'llanmasi jadvallari, misollari bilan...",
  "exercises": [
    {
      "sentence": "Savol matni yoki bo'sh joy qoldirilgan gap...",
      "options": ["variant1", "variant2", "variant3", "variant4"],
      "correctOption": 0
    }
  ],
  "homework": "Yozma yoki rasmli uyga vazifa topshirig'i tavsifi..."
}`;

      const response = await generateContentWithFallback(client, {
        contents: prompt,
        config: {
          responseMimeType: "application/json",
          responseSchema: {
            type: Type.OBJECT,
            properties: {
              topicTitle: { type: Type.STRING },
              explanation: { type: Type.STRING },
              exercises: {
                type: Type.ARRAY,
                items: {
                  type: Type.OBJECT,
                  properties: {
                    sentence: { type: Type.STRING },
                    options: {
                      type: Type.ARRAY,
                      items: { type: Type.STRING }
                    },
                    correctOption: { type: Type.INTEGER }
                  },
                  required: ["sentence", "options", "correctOption"]
                }
              },
              homework: { type: Type.STRING }
            },
            required: ["topicTitle", "explanation", "exercises", "homework"]
          }
        }
      });

      const responseText = response.text;
      if (responseText) {
        const parsedData = JSON.parse(responseText.trim());
        return res.json({ success: true, ...parsedData });
      } else {
        throw new Error("Bo'sh javob qaytdi.");
      }
    } catch (error: any) {
      console.error("Gemini topic study generation error:", error);
      return res.json({
        success: false,
        error: error.message,
        ...getFallbackStudyTopic(topic, explanationLanguage)
      });
    }
  });

  // Comprehensive Exam Generation (60 Questions: 12 Questions per each of the 5 saved topics)
  app.post("/api/generate-mega-exam", async (req, res) => {
    const { topics, language } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey || !topics || topics.length < 5) {
      return res.json(getFallbackMegaExam(topics || ["Mavzu 1", "Mavzu 2", "Mavzu 3", "Mavzu 4", "Mavzu 5"], language));
    }

    try {
      const client = getGeminiClient();
      const prompt = `Foydalanuvchi o'rgangan 5 ta mavzu ro'yxati: ${JSON.stringify(topics)}.
Siz ushbu 5 ta darsning har biriga tegishli 12 tadan, jami to'ppa-to'g'ri 60 ta interaktiv test savollarini ingliz/rus grammatikasi va leksikasini tekshirish uchun tuzib bering.
Savollar ${language === 'uz' ? 'O\'zbek tilida' : language === 'ru' ? 'Rus tilida' : 'Ingliz tilida'} tushuntirilsin.
Har bir savol ko'p variantli bo'lib, uning to'g'ri javob indexi (0, 1, 2, 3) belgilanishi lozim.

Javobni quyidagi qisqa JSON ko'rinishida qaytaring:
{
  "questions": [
    {
      "q": "Savol matni or gap strukturasi...",
      "options": ["A", "B", "C", "D"],
      "correct": 0,
      "topic": "Ushbu savol qaysi mavzuga tegishli ekanligi"
    }
  ]
}`;

      const response = await generateContentWithFallback(client, {
        contents: prompt,
        config: {
          responseMimeType: "application/json",
          responseSchema: {
            type: Type.OBJECT,
            properties: {
              questions: {
                type: Type.ARRAY,
                items: {
                  type: Type.OBJECT,
                  properties: {
                    q: { type: Type.STRING },
                    options: {
                      type: Type.ARRAY,
                      items: { type: Type.STRING }
                    },
                    correct: { type: Type.INTEGER },
                    topic: { type: Type.STRING }
                  },
                  required: ["q", "options", "correct", "topic"]
                }
              }
            },
            required: ["questions"]
          }
        }
      });

      const responseText = response.text;
      if (responseText) {
        const parsedData = JSON.parse(responseText.trim());
        return res.json({ success: true, ...parsedData });
      } else {
        throw new Error("Bo'sh imtihon javobi qaytdi.");
      }
    } catch (error: any) {
      console.error("Gemini exam generation error:", error);
      return res.json({
        success: false,
        error: error.message,
        ...getFallbackMegaExam(topics, language)
      });
    }
  });

  // Homework check API with image understanding using server-side Gemini
  app.post("/api/check-homework", async (req, res) => {
    const { language, topic, title, homeworkPrompt, imageData, textDraft } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      // Simulate review if API key is not configured yet
      const randomScore = textDraft || imageData ? Math.floor(Math.random() * 2) + 4 : 3; // 4 or 5 normally
      const simFeedback = `[Simulyatsiya rejimi]: Uyga vazifangiz tahlil qilindi! 
Siz mavzuni juda yaxshi o'zlashtiribsiz. Quyida tahlil natijalari:
- Grammatik xatolar: Yo'q
- So'z boyligi qo'llanilishi: A'lo darajada.
${randomScore < 4 ? "\nQayta topshirish uchun yangi topshiriq: Mavzu doirasida yana 3 ta gap tuzing." : "\nKelgusi darslarga omad!"}`;

      return res.json({
        success: true,
        score: randomScore,
        feedback: simFeedback,
        alternativeHomework: randomScore < 4 ? "Yangi vazifa: Mavzu bo'yicha mustaqil ravishda o'zingiz haqingizda 4 ta sodda gap yozib yuklang." : null
      });
    }

    try {
      const client = getGeminiClient();
      const parts: any[] = [];

      parts.push({
        text: `Siz til o'rgatish o'quv markazining tajribali AI o'qituvchisisiz.
Vazifa mavzusi: "${title}" (${topic})
Berilgan topshiriq: "${homeworkPrompt}"
O'rganilayotgan til: ${language === 'en' ? 'Ingliz' : 'Rus'} tili.

Foydalanuvchi dars oxiridagi uyga vazifasini qog'ozga yozib rasmga tushirib yubordi yoki matn shaklida kiritdi.
Iltimos, ushbu yuklangan uyga vazifani tahlil qiling:
1. Imlo xatolari, grammatik xatolar va so'zlarning to'g'ri ishlatilganligini tekshiring.
2. Har bir xatoni O'zbek tilida dona-dona tushuntirib bering.
3. 5 ballik baholash tizimida unga baho qo'ying (1 dan 5 gacha butun son).
4. Baho 4 ball yoki undan yuqori bo'lsa (yaxshi va a'lo), uni samimiy tabriklang va tavsiyalar bering.
5. Agar baho 4 dandan kichik bo'lsa (masalan 1, 2, 3), unda xatolardan kelib chiqib, shu mavzuni mustahkamlash uchun MUTLAQO YANGI va boshqacha uyga vazifa tuzib bering ("alternativeHomework" maydoniga).

Javobni aniq JSON formatida quyidagi tuzilma bilan qaytaring:
{
  "score": 5, // 1 dan 5 gacha butun son
  "feedback": "...", // tahlil va xatolar haqida to'liq hisobot (O'zbek tilida)
  "alternativeHomework": "..." // baho 4 dan past bo'lgandagina yoziladi, bo'lmasa null yoki bo'sh bo'ladi
}`
      });

      if (imageData) {
        // base64 parsing: remove dataURI metadata if present
        const cleanBase64 = imageData.replace(/^data:image\/\w+;base64,/, "");
        parts.push({
          inlineData: {
            mimeType: "image/png",
            data: cleanBase64
          }
        });
      }

      if (textDraft) {
        parts.push({
          text: `Foydalanuvchining matnli/yozma javobi: "${textDraft}"`
        });
      }

      const response = await generateContentWithFallback(client, {
        contents: { parts },
        config: {
          responseMimeType: "application/json",
          responseSchema: {
            type: Type.OBJECT,
            properties: {
              score: { type: Type.INTEGER },
              feedback: { type: Type.STRING },
              alternativeHomework: { type: Type.STRING }
            },
            required: ["score", "feedback"]
          }
        }
      });

      const responseText = response.text;
      if (responseText) {
        const parsed = JSON.parse(responseText.trim());
        return res.json({ success: true, ...parsed });
      } else {
        throw new Error("AI darsni tahlil qila olmadi.");
      }
    } catch (error: any) {
      console.error("Gemini check-homework error:", error);
      return res.json({
        success: false,
        error: error.message,
        score: 3,
        feedback: "Kechirasiz, rasm yoki matnni tahlil qilishda nosozlik yuz berdi. Tizim avtomatik ravishda 3 baho qo'ydi. Iltimos, qayta urinib ko'ring.",
        alternativeHomework: "Qayta urinish: Dars ko'rsatmalariga muvofiq gaplarni chiroyli yozib qayta yuklang."
      });
    }
  });

  // Dynamic system to generate adaptive chess questions or battle questions
  app.post("/api/generate-duel-question", async (req, res) => {
    const { language, level } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      return res.json({ success: true, ...getMockDuelQuestion(language, level) });
    }

    try {
      const client = getGeminiClient();
      const prompt = `Chet tili dueli uchun 1 ta qiziqarli test savolini JSON shaklida yarating.
O'rganilayotgan til: ${language === 'en' ? 'Ingliz' : 'Rus'}.
Daraja: ${level || 'Normal'}.
Savol turi: Grammatika yoki so'z boyligi bo'yicha tushib qolgan so'z variantlari.
Savolda 4 ta variant bo'lishi va bitta to'g'ri o'rin belgilanishi kerak.

Quyidagi strukturada javob bering:
{
  "question": "Oynadagi gap yozuvi, masalan: This is the man _____ car was stolen.",
  "options": ["who", "whose", "which", "whom"],
  "correctIndex": 1,
  "explanation": "Tushuntirish: O'zbek tilida gap qoidasining qisqacha izohi."
}`;

      const response = await generateContentWithFallback(client, {
        contents: prompt,
        config: {
          responseMimeType: "application/json",
          responseSchema: {
            type: Type.OBJECT,
            properties: {
              question: { type: Type.STRING },
              options: {
                type: Type.ARRAY,
                items: { type: Type.STRING }
              },
              correctIndex: { type: Type.INTEGER },
              explanation: { type: Type.STRING }
            },
            required: ["question", "options", "correctIndex", "explanation"]
          }
        }
      });

      const responseText = response.text;
      if (responseText) {
        const parsed = JSON.parse(responseText.trim());
        return res.json({ success: true, ...parsed });
      } else {
        throw new Error("Bo'sh duel savoli.");
      }
    } catch (e) {
      return res.json({ success: true, ...getMockDuelQuestion(language, level) });
    }
  });

  // Dynamic system to generate custom Sonsiz Yulduz questions based on user-entered topics
  app.post("/api/generate-star-questions", async (req, res) => {
    const { topic, language, difficulty = "medium", count = 10, previousSentences = [] } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      // Return count mock questions as high-quality simulated fallback
      const mockQuestions = [];
      const verbPool = ["play", "study", "work", "visit", "write", "speak", "learn", "watch", "read", "listen", "eat", "drink", "travel", "live", "buy", "sell", "understand", "explain", "choose", "receive"];
      for (let i = 1; i <= count; i++) {
        const verb = verbPool[(i + previousSentences.length) % verbPool.length];
        mockQuestions.push({
          id: `mockst_${previousSentences.length + i}`,
          sentence: `[${topic} - ${difficulty.toUpperCase()} - Savol ${previousSentences.length + i}] Complete the sentence: We always ________ to improve our understanding of this topic.`,
          options: [`${verb}s`, `${verb}`, `${verb}ing`, `to ${verb}`],
          correct: verb,
          hint: `Mavzu: ${topic} (${difficulty}). To'g'ri javob: '${verb}'. Berilgan mavzudagi grammatika qoidasi.`
        });
      }
      return res.json({
        success: true,
        questions: mockQuestions
      });
    }

    try {
      const client = getGeminiClient();
      let accumulatedQuestions: any[] = [];
      let attempts = 0;

      // We run in batches of 10 to safely generate the exact requested count of unique questions
      while (accumulatedQuestions.length < count && attempts < 5) {
        attempts++;
        const batchSize = Math.min(10, count - accumulatedQuestions.length);
        const currentExcluded = [...previousSentences, ...accumulatedQuestions.map(q => q.sentence)];

        const prompt = `Chet tilini o'rganayotgan o'quvchilar uchun "${topic}" mavzusi bo'yicha ${batchSize} ta mutlaqo yangi, sifatli va takrorlanmas test savollarini yaratib bering.
Qiyinchilik darajasi: ${difficulty === 'easy' ? 'Boshlang\'ich (Easy - A1-A2)' : difficulty === 'hard' ? 'Qiyin (Hard - C1-C2)' : 'O\'rta (Medium - B1-B2)'}.
O'rganish tili: ${language === 'en' ? 'Ingliz tili' : 'Rus tili'}.
Interfeys va tushuntirish (hint) tili: O'zbekcha.
TAKRORLANMASLIK MAS'ULIYATI: Quyidagi savollar matnini umuman takrorlamang:
${JSON.stringify(currentExcluded.slice(-45))}

Har bir savol 4 ta variant (options) dan tashkil topgan ko'p tanlovli (multiple choice) test bo'lishi kerak. 'correct' maydoniga ushbu variantlardan aynan to'g'ri keladigan matnni o'zini yozing.
Quyidagi tizimli JSON formatini qaytaring:
{
  "questions": [
    {
      "id": "q",
      "sentence": "Savol matni (masalan: She _______ her homework every evening.)",
      "options": ["do", "does", "doing", "done"],
      "correct": "does",
      "hint": "Qisqacha o'zbekcha qoida va tushuntirish"
    }
  ]
}`;

        const response = await generateContentWithFallback(client, {
          contents: prompt,
          config: {
            responseMimeType: "application/json",
            responseSchema: {
              type: Type.OBJECT,
              properties: {
                questions: {
                  type: Type.ARRAY,
                  items: {
                    type: Type.OBJECT,
                    properties: {
                      id: { type: Type.STRING },
                      sentence: { type: Type.STRING },
                      options: {
                        type: Type.ARRAY,
                        items: { type: Type.STRING }
                      },
                      correct: { type: Type.STRING },
                      hint: { type: Type.STRING }
                    },
                    required: ["id", "sentence", "options", "correct", "hint"]
                  }
                }
              },
              required: ["questions"]
            }
          }
        });

        const responseText = response.text;
        if (responseText) {
          const parsed = JSON.parse(responseText.trim());
          if (parsed && parsed.questions && parsed.questions.length > 0) {
            for (const q of parsed.questions) {
              const duplicated = [...previousSentences, ...accumulatedQuestions.map(ea => ea.sentence)].some(existing => 
                existing.toLowerCase().trim() === q.sentence.toLowerCase().trim()
              );
              if (!duplicated && accumulatedQuestions.length < count) {
                q.id = `q_${previousSentences.length + accumulatedQuestions.length + 1}`;
                accumulatedQuestions.push(q);
              }
            }
          }
        }
      }

      // Safe padding if still short of requested count
      if (accumulatedQuestions.length < count) {
        const remainingNeeded = count - accumulatedQuestions.length;
        for (let i = 0; i < remainingNeeded; i++) {
          const qIdNum = previousSentences.length + accumulatedQuestions.length + 1;
          accumulatedQuestions.push({
            id: `q_${qIdNum}`,
            sentence: `[${topic} - ${difficulty.toUpperCase()} - Savol ${qIdNum}] Complete the phrase: We must ________ our lesson carefully.`,
            options: ["studies", "study", "studying", "to study"],
            correct: "study",
            hint: "Must yordamchi fe'lidan keyin fe'lning asosi keladi."
          });
        }
      }

      return res.json({ success: true, questions: accumulatedQuestions });
    } catch (e: any) {
      console.error("Gemini star questions generation error:", e);
      // Fallback
      const mockQuestions = [];
      const verbPool = ["play", "study", "work", "visit", "write", "speak", "learn", "watch", "read", "listen", "eat", "drink", "travel", "live", "buy", "sell", "understand", "explain", "choose", "receive"];
      for (let i = 1; i <= count; i++) {
        const verb = verbPool[(i + previousSentences.length) % verbPool.length];
        mockQuestions.push({
          id: `fbst_${previousSentences.length + i}`,
          sentence: `[${topic} - Savol ${previousSentences.length + i}] Complete the sentence: I ________ English every single day to expand my skills.`,
          options: [`${verb}s`, `${verb}`, `${verb}ing`, `to ${verb}`],
          correct: verb,
          hint: `Mavzu: ${topic}. To'g'ri javob: '${verb}'.`
        });
      }
      return res.json({ success: true, questions: mockQuestions });
    }
  });

  // Dynamic speaking practice phrase generator using Gemini
  app.post("/api/generate-speaking-phrase", async (req, res) => {
    const { language } = req.body;
    const apiKey = process.env.GEMINI_API_KEY;

    if (!apiKey) {
      const phrases = language === 'en' ? [
        { phrase: "Practice makes perfect in every venture.", translation: "Har bir ishda mashq mukammallikka yetaklaydi.", tip: "p va f tovushlarini portlovchi qilib, lablarni keng ochib talaffuz eting." },
        { phrase: "The climate is changing rapidly around the globe.", translation: "Butun dunyo bo'ylab iqlim juda tez o'zgarmoqda.", tip: "Climate so'zida c harfini k kabi va rapidly dagi r ni muloyim yengil ayting." }
      ] : [
        { phrase: "Повторение — мать истинного учения.", translation: "Takrorlash — haqiqiy bilimning onasidir.", tip: "p va t tovushlarini qattiq, r ni esa aniq titratib ayting." },
        { phrase: "Сегодня прекрасная погода для семейной прогулки в парке.", translation: "Bugun parkda oilaviy sayr qilish uchun ajoyib ob-havo.", tip: "сегодня dagi g tovushi v kabi o'qilishiga diqqat qiling." }
      ];
      const selected = phrases[Math.floor(Math.random() * phrases.length)];
      return res.json({ success: true, ...selected });
    }

    try {
      const client = getGeminiClient();
      const prompt = `Chet tilini o'rganayotgan yoshlar talaffuzi (speaking) mashqi uchun 1 ta mutlaqo yangi, hayotiy, foydali bo'lgan gap (phrase) yaratib bering.
O'rganish tili: ${language === 'en' ? 'Ingliz tili' : 'Rus tili'}.
Interfeys va maslahat tili: O'zbekcha.
Quyidagi tizimli JSON formatini qaytaring:
{
  "phrase": "Yaratilgan gap (masalan: I want to optimize my accent.)",
  "translation": "O'zbekcha tarjimasi (masalan: Men talaffuzimni yaxshilamoqchiman.)",
  "tip": "Ushbu gapning to'g'ri va mukammal talaffuzi bo'yicha o'zbekcha qisqa va aniq 1 ta maslahat."
}`;

      const response = await generateContentWithFallback(client, {
        contents: prompt,
        config: {
          responseMimeType: "application/json",
          responseSchema: {
            type: Type.OBJECT,
            properties: {
              phrase: { type: Type.STRING },
              translation: { type: Type.STRING },
              tip: { type: Type.STRING }
            },
            required: ["phrase", "translation", "tip"]
          }
        }
      });

      const responseText = response.text;
      if (responseText) {
        const parsed = JSON.parse(responseText.trim());
        return res.json({ success: true, ...parsed });
      } else {
        throw new Error("Bo'sh javob.");
      }
    } catch (e) {
      console.error("Gemini speaking phrase generation error:", e);
      return res.json({
        success: true,
        phrase: language === 'en' ? "Welcome to the future of immersive language learning!" : "Добро пожаловать в будущее интерактивного обучения!",
        translation: language === 'en' ? "Immersiv til o'rganish kelajagiga xush kelibsiz!" : "Interaktiv ta'lim kelajagiga xush kelibsiz!",
        tip: "Welcome so'zini boshida lablarni aylana (w) shakliga keltirib, keyin yoying."
      });
    }
  });

  // Vite middleware setup with standard configuration
  let distPath = "";
  console.log(`[Startup Info] process.cwd(): ${process.cwd()}`);
  if (typeof __dirname !== "undefined") {
    console.log(`[Startup Info] __dirname: ${__dirname}`);
    const dirAbs = path.resolve(__dirname);
    if (fs.existsSync(path.join(dirAbs, "index.html"))) {
      distPath = dirAbs;
    } else if (fs.existsSync(path.join(dirAbs, "dist", "index.html"))) {
      distPath = path.join(dirAbs, "dist");
    }
  }

  if (!distPath) {
    const cwdAbs = path.resolve(process.cwd());
    distPath = path.join(cwdAbs, 'dist');
    if (!fs.existsSync(path.join(distPath, 'index.html'))) {
      distPath = cwdAbs;
    }
  }

  distPath = path.resolve(distPath);
  const hasBuiltAssets = fs.existsSync(path.join(distPath, 'index.html'));
  console.log(`[Startup Info] Resolved distPath: ${distPath}`);
  console.log(`[Startup Info] hasBuiltAssets (index.html exists): ${hasBuiltAssets}`);

  // Determine if we should run in production static mode
  const isCompiledBundle = typeof __filename !== "undefined" && (__filename.endsWith(".cjs") || __filename.endsWith(".js") || __filename.includes("dist"));
  const isProductionMode = process.env.NODE_ENV === "production" || isCompiledBundle;

  if (!isProductionMode || !hasBuiltAssets) {
    console.log("Starting server in development / on-demand compilation mode...");
    // Dynamically import Vite only when needed in development to prevent load-time failures in production
    const { createServer: createViteServer } = await import("vite");
    const vite = await createViteServer({
      server: { middlewareMode: true },
      appType: "spa",
    });
    app.use(vite.middlewares);

    // Serve index.html translated through Vite's dev server for SPA routes
    app.get('*', async (req, res, next) => {
      // Exclude API requests from being intercepted
      if (req.originalUrl.startsWith('/api/')) {
        return next();
      }
      try {
        const htmlPath = path.resolve(process.cwd(), 'index.html');
        if (fs.existsSync(htmlPath)) {
          let template = fs.readFileSync(htmlPath, 'utf-8');
          // Apply Vite's internal HTML transforms (resolves hot-module, scripts, CSS tags dynamically)
          template = await vite.transformIndexHtml(req.originalUrl, template);
          res.status(200).set({ 'Content-Type': 'text/html' }).end(template);
        } else {
          res.status(404).send("Error: index.html not found in development root.");
        }
      } catch (err) {
        vite.ssrFixStacktrace(err as Error);
        next(err);
      }
    });
  } else {
    console.log(`Starting server in production static mode... distPath=${distPath}`);
    app.use(express.static(distPath));
    app.get('*', (req, res) => {
      const indexPath = path.join(distPath, 'index.html');
      res.sendFile(indexPath, (err) => {
        if (err) {
          console.error(`Error sending index.html: ${err}`);
          res.status(500).send(`Server Error: Failed to load application assets. distPath is "${distPath}". Please ensure the app has been built successfully.`);
        }
      });
    });
  }

  app.listen(PORT, "0.0.0.0", () => {
    console.log(`Server running on http://localhost:${PORT}`);
  });
}

// Fallback lesson contents
function getFallbackLesson(language: string, level: string, topic: string, title: string) {
  const isEn = language === "en";
  if (isEn) {
    return {
      success: true,
      data: {
        explanation: `### 📘 ${title || 'Lesson Overview'}\n\nUshbu dars Ingliz tilida so'zlashuv va muloqot qoidalarini rivojlantirishga qaratilgan.\n\n#### Qoidalar:\n1. **Sodda gaplar**: Ingliz tilida har doim subject + verb ko'rinishidan foydalaning. Masalan: *I like learning languages.*\n2. **Tushunish kalitlari**: Gap tuzishda fe'l va zamon mosligiga e'tibor qarating.\n\n#### Misollar:\n| Inglizcha | O'zbekcha tushunilishi | Izoh |\n| :--- | :--- | :--- |\n| *I am reading a book.* | Men kitob o'qiyapman. | Hozirgi davomli zamon. |\n| *We went to the beach.* | Biz plyajga bordik. | O'tgan zamon (Past Simple). |`,
        exercises: [
          {
            title: "Mashiq 1: Fe'llarni moslashtirish",
            questions: [
              { sentence: "She _______ her homework every evening.", options: ["do", "does", "doing", "done"], correctOption: 1 },
              { sentence: "They _______ football in the park yesterday.", options: ["play", "played", "playing", "plays"], correctOption: 1 },
              { sentence: "We are _______ our next family trip.", options: ["plan", "planning", "planned", "plans"], correctOption: 1 },
              { sentence: "He has _______ this film three times.", options: ["see", "saw", "seen", "seeing"], correctOption: 2 },
              { sentence: "If it rains, I _______ stay at home.", options: ["will", "would", "shall", "am"], correctOption: 0 },
              { sentence: "Listen! Somebody is _______ the piano.", options: ["play", "plays", "played", "playing"], correctOption: 3 }
            ]
          },
          {
            title: "Mashiq 2: Predmet va so'z mosligi",
            questions: [
              { sentence: "This is the most _______ book I have ever read.", options: ["interest", "interesting", "interested", "interests"], correctOption: 1 },
              { sentence: "Would you like _______ cup of tea?", options: ["another", "other", "others", "the other"], correctOption: 0 },
              { sentence: "She is afraid _______ spiders.", options: ["of", "at", "about", "with"], correctOption: 0 },
              { sentence: "We must protect _______ environment.", options: ["a", "an", "the", "no article"], correctOption: 2 },
              { sentence: "He Speaks English very _______.", options: ["good", "well", "better", "best"], correctOption: 1 },
              { sentence: "My brother is older _______ me.", options: ["then", "than", "to", "as"], correctOption: 1 }
            ]
          }
        ],
        homework: "Uyga vazifa:\nMavzuga aloqador kamida 5 ta gap yozing. Gaplaringizda hozirgi yoki o'tgan zamon fe'llaridan unumli foydalaning. Yozgan gaplaringizni toza qog'ozga ruchka bilan yozib, rasmga olib bu yerga yuklang."
      }
    }
  } else {
    return {
      success: true,
      data: {
        explanation: `### 📘 ${title || 'Урок'}\n\nUshbu dars Rus tili grammatikasi va jumlalar tuzilishiga bag'ishlangan.\n\n#### Asosiy ma'lumotlar:\n1. **Rus tilida otlar va fe'llar mosligi**: Otlarning rodlari va unga mos ravishda fe'llarning o'zgarishini ko'rib chiqamiz. \n2. **Kelimelar kelishuvi**: *Я иду, ты идешь, он идет*.\n\n#### Misollar:\n| Ruscha gap | Tarjimasi | Izoh |\n| :--- | :--- | :--- |\n| *Я изучаю русский язык.* | Men rus tilini o'rganyapman. | Hozirgi zamon ko'rinishi |\n| *Мы купили новую книгу.* | Biz yangi kitob sotib oldik. | O'tgan zamonda ko'plik formasi |`,
        exercises: [
          {
            title: "Упражнение 1: Глаголы и окончания",
            questions: [
              { sentence: "Вчера мы _______ фильм в кинотеатре.", options: ["смотрим", "смотрели", "посмотреть", "смотрят"], correctOption: 1 },
              { sentence: "Я хочу _______ чаю с лимоном.", options: ["выпить", "пьет", "выпила", "выпивать"], correctOption: 0 },
              { sentence: "Она _______ в школе учителем русского языка.", options: ["работает", "работал", "работать", "работают"], correctOption: 0 },
              { sentence: "Ты уже _______ это домашнее задание?", options: ["сделать", "сделал", "делаешь", "сделаешь"], correctOption: 1 },
              { sentence: "Они _______ на поезде в Ташкент в следующую субботу.", options: ["поедут", "ехал", "поехали", "едет"], correctOption: 0 },
              { sentence: "Мы очень любим _______ в горах летом.", options: ["отдыхаем", "отдохнули", "отдыхать", "отдыхают"], correctOption: 2 }
            ]
          },
          {
            title: "Упражнение 2: Падежи и предлоги",
            questions: [
              { sentence: "Книга лежит _______ столе в комнате.", options: ["на", "в", "у", "над"], correctOption: 0 },
              { sentence: "Мы пошли гулять в парк _______ друзьями.", options: ["с", "к", "без", "около"], correctOption: 0 },
              { sentence: "Я часто звоню своим _______.", options: ["родители", "родителей", "родителям", "родителями"], correctOption: 2 },
              { sentence: "Она мечтает поехать _______ Москву летом.", options: ["в", "на", "к", "для"], correctOption: 0 },
              { sentence: "Этот подарок приготовлен _______ тебя.", options: ["для", "к", "без", "через"], correctOption: 0 },
              { sentence: "Они говорят _______ интересном проекте.", options: ["о", "в", "от", "для"], correctOption: 0 }
            ]
          }
        ],
        homework: "Домашнее задание:\nRus tilida ruscha fe'llar va otlar mos keladigan 5 ta chiroyli gap tuzing va daftarga yozing. So'ngra daftaringizni rasmga olib bu yerga tekshirish uchun yuklang."
      }
    }
  }
}

// Generate fallback duel question
function getMockDuelQuestion(language: string, level: string) {
  const isEn = language === "en";
  if (isEn) {
    const list = [
      { question: "Choose the correct past simple form of 'go':", options: ["goed", "goes", "gone", "went"], correctIndex: 3, explanation: "'go' fe'lining o'tgan zamoni noto'g'ri fe'llar jadvalida 'went' bo'ladi." },
      { question: "She is really good _______ playing soccer.", options: ["at", "in", "on", "for"], correctIndex: 0, explanation: "'good at doing something' iborasi biror narsaga qobiliyatli bo'lishni anglatadi." },
      { question: "I haven't seen him _______ five years.", options: ["since", "for", "during", "before"], correctIndex: 1, explanation: "Vaqt oralig'i (5 yil) ko'rsatilganligi sababli 'for' ishlatiladi." }
    ];
    return list[Math.floor(Math.random() * list.length)];
  } else {
    const list = [
      { question: "Выберите правильное местоимение: Это книга _______.", options: ["мой", "моя", "мое", "мои"], correctIndex: 1, explanation: "'Книга' женский род (ая) bo'lganligi sababli 'моя' bo'ladi." },
      { question: "Как будет правильно: Я еду _______ автобусе.", options: ["на", "в", "к", "о"], correctIndex: 0, explanation: "Transportda harakatlanish uchun ko'pincha 'на автобусе' ishlatiladi." },
      { question: "Вчера мы _______ в новый музей.", options: ["идем", "ходили", "пойти", "идешь"], correctIndex: 1, explanation: "O'tgan zamonda bir necha bor borib kelishni ko'rsatish uchun 'ходили' ishlatiladi." }
    ];
    return list[Math.floor(Math.random() * list.length)];
  }
}

// Generate fallback study topic resources if Gemini key is missing
function getFallbackStudyTopic(topic: string, explanationLanguage: string) {
  const t = topic || "Noma'lum Mavzu";
  const langLabel = explanationLanguage === 'uz' ? 'O\'zbekcha' : explanationLanguage === 'ru' ? 'Ruscha' : 'Inglizcha';
  return {
    success: true,
    topicTitle: t,
    explanation: `### 📘 ${t} (Tushuntirish tili: ${langLabel})\n\nUshbu dars **${t}** mavzusini chuqur o'rganishga bag'ishlangan.\n\n#### 🌟 Mavzu Qoidalari va Tahlili:\n1. **Chuqur Tushuncha**: To'g'ri o'rganish sizning chet tilida erkin so'zlashingizni kafolatlaydi. Ushbu darsda tahlil qilingan grammatik, talaffuz va amaliy foydalanish qoidalariga diqqat qiling.\n2. **Tavsiyalar**: Kundalik nutqda ushbu dars qoidalariga mos misollarni ko'p qo'llang va so'z boyligini kengaytiring.\n\n#### 📝 Foydali Misollar:\n* *Today is a great day to practice.* - Bugun mashiq qilish uchun ajoyib kun.\n* *Practice makes perfect.* - Amaliyot mukammallikka yetaklaydi.\n\n[Simulyatsiya rejimi]: Tizim to'liq Gemini API orqali ishlashi uchun AI Studio Secrets orqali \`GEMINI_API_KEY\` ni qo'shing. Ushbu dars namunaviy shakllantirildi.`,
    exercises: [
      { sentence: `Siz hozirgina "${t}" mavzusini o'rgandingiz. Ushbu mavzuga mos eng to'g'ri bog'lovchini tanlang: "She is afraid ______ spiders."`, options: ["of", "at", "about", "with"], correctOption: 0 },
      { sentence: `Mavzu bo'yicha eng to'g'ri fe'l shaklini tanlang: "We ______ to work tomorrow."`, options: ["will go", "went", "going", "goes"], correctOption: 0 },
      { sentence: `Mazmun jihatidan quyidagilardan qaysi biri to'g'ri? "They ______ soccer right now."`, options: ["are playing", "plays", "played", "play"], correctOption: 0 },
      { sentence: `Qaysi variant to'g'ri tanlangan? "This is ______ orange book."`, options: ["an", "a", "the", "no article"], correctOption: 0 }
    ],
    homework: `Uyga vazifa:\n"${t}" mavzusiga doir eng muhim 3 ta qoidani daftaringizga o'zbek tilida yozing, dars so'zlaridan foydalanib 3 ta gap tuzing. Uni ruchka bilan toza qog'ozga yozib rasmga tushiring va bu yerga yuklang yoki quyidagi matn maydoniga yozib yuboring.`
  };
}

// Generate fallback mega exam of 60 questions if Gemini key is missing
function getFallbackMegaExam(topics: string[], language: string) {
  const quizQuestions: any[] = [];
  const listTopics = (topics && topics.length >= 5) ? topics.slice(0, 5) : ["Present Simple", "Kelishiklar (Падежи)", "Past Simple", "Predloqlar (Предлоги)", "Present Perfect"];
  
  // For each of the 5 topics, generate 12 questions
  listTopics.forEach((topic) => {
    for (let i = 1; i <= 12; i++) {
      quizQuestions.push({
        q: `[${topic}] bo'yicha ${i}-nazorat savoli: Ushbu qoidaga mos eng ma'qul gap yoki fe'l shaklini belgilang.`,
        options: [
          `To'g'ri javob varianti (${topic} qoidasi bo'yicha)`,
          `Noto'g'ri variant A (${topic})`,
          `Noto'g'ri variant B (${topic})`,
          `Noto'g'ri variant C (${topic})`
        ],
        correct: 0,
        topic: topic
      });
    }
  });

  return { success: true, questions: quizQuestions };
}

startServer();