File size: 146,416 Bytes
dbc3b43
 
 
 
 
b1ecb81
 
 
 
dbc3b43
e077614
 
 
 
 
 
 
dbc3b43
 
 
 
 
 
 
 
 
b1ecb81
a70bc0e
 
 
 
b1ecb81
7f53a72
 
 
 
 
a70bc0e
 
7f53a72
dbc3b43
 
 
 
e077614
 
 
2e80070
df175c7
 
caca638
 
 
df175c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dde204
 
 
df175c7
 
 
 
 
 
 
 
 
993afc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21f1460
e077614
 
 
 
 
21f1460
e077614
 
 
 
 
21f1460
e077614
 
 
 
 
 
 
21f1460
e077614
 
 
 
 
21f1460
e077614
 
 
 
 
21f1460
e077614
 
 
 
 
 
 
 
21f1460
 
 
 
e077614
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
 
eff1161
 
 
 
dbc3b43
 
 
d17b8bd
 
 
 
 
eff1161
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
 
d17b8bd
 
dbc3b43
 
 
 
 
d17b8bd
dbc3b43
 
 
 
 
 
eff1161
dbc3b43
eff1161
7fa1896
eff1161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
 
d17b8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fa1896
 
 
 
 
 
 
 
dbc3b43
 
 
 
 
eff1161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
7fa1896
d17b8bd
7fa1896
dbc3b43
d17b8bd
 
 
 
 
7fa1896
 
 
 
 
 
 
 
 
d17b8bd
 
 
 
 
 
 
7fa1896
 
 
 
d17b8bd
 
7fa1896
 
d17b8bd
 
 
 
 
dbc3b43
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
dabe59b
 
 
dbc3b43
dabe59b
 
 
 
 
dbc3b43
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
dabe59b
 
 
dbc3b43
dabe59b
 
 
 
 
dbc3b43
7fa1896
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
dabe59b
 
 
dbc3b43
dabe59b
 
 
 
 
dbc3b43
 
 
 
7fa1896
 
 
dbc3b43
7fa1896
 
 
dbc3b43
7fa1896
dbc3b43
 
 
 
 
d17b8bd
dbc3b43
7fa1896
 
dbc3b43
d17b8bd
dbc3b43
d17b8bd
 
 
 
 
 
 
 
 
dbc3b43
 
 
d17b8bd
dbc3b43
 
7fa1896
d17b8bd
dbc3b43
d17b8bd
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
7fa1896
dbc3b43
 
7fa1896
 
dbc3b43
d17b8bd
 
 
 
 
 
 
 
dbc3b43
 
 
7fa1896
dbc3b43
 
7fa1896
d17b8bd
dbc3b43
d17b8bd
 
 
 
 
 
 
 
dbc3b43
 
 
 
 
 
 
 
 
dabe59b
dbc3b43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10042a9
dbc3b43
 
 
 
 
 
 
 
 
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6c9393
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10042a9
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6c9393
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dff233a
e077614
825c650
 
eff1161
e077614
825c650
eff1161
 
e077614
825c650
eff1161
 
e077614
825c650
 
eff1161
e077614
825c650
eff1161
 
 
 
 
 
e077614
dff233a
e077614
825c650
 
 
e077614
1256b30
 
 
 
 
 
e077614
825c650
e077614
825c650
e077614
825c650
e077614
825c650
eff1161
 
 
 
 
825c650
 
eff1161
 
e077614
825c650
e077614
825c650
e077614
 
 
dbc3b43
 
 
 
 
 
 
 
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46e172a
e077614
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
 
 
 
 
 
 
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
e077614
dbc3b43
 
 
a70bc0e
 
 
 
10042a9
a70bc0e
 
dbc3b43
 
 
 
 
 
 
 
 
 
 
e077614
 
 
 
 
 
 
 
 
dbc3b43
e077614
 
 
 
 
 
 
 
 
dbc3b43
a70bc0e
 
 
 
 
 
eff1161
10042a9
 
 
dff233a
10042a9
 
 
dff233a
10042a9
 
 
 
 
 
 
dff233a
10042a9
 
 
 
 
 
 
dff233a
a70bc0e
 
 
 
 
 
10042a9
a70bc0e
10042a9
9282b0c
a70bc0e
 
 
7f53a72
 
 
 
 
 
 
10042a9
7f53a72
 
 
 
 
10042a9
7f53a72
a70bc0e
7f53a72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a70bc0e
dbc3b43
 
 
8fde5d2
 
 
e077614
 
 
 
 
 
 
 
 
 
d6c9393
e077614
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
e077614
dbc3b43
 
 
 
 
 
 
 
 
e077614
dbc3b43
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
46e172a
e077614
 
 
 
 
 
 
 
 
 
 
d6c9393
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fde5d2
 
 
e077614
dbc3b43
 
 
 
e077614
 
 
 
 
 
 
 
 
 
 
 
 
10042a9
e077614
 
 
dbc3b43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e077614
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df175c7
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6c9393
e077614
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
 
 
 
 
e077614
 
 
 
dbc3b43
 
 
 
 
 
 
 
e077614
 
 
 
 
 
 
 
 
 
 
 
 
dbc3b43
 
 
10042a9
dbc3b43
 
 
e077614
 
 
 
 
dbc3b43
 
 
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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
from flask import Flask, request, jsonify
from flask_cors import CORS
from groq import Groq
import os
import logging
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()
from datetime import datetime
import sqlite3
import uuid
import json
import time
from functools import wraps
from collections import defaultdict, deque
import threading

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)

# Initialize Groq client - will use HF Spaces secrets
GROQ_API_KEY = os.getenv("GROQ_API_KEY")

# Initialize Groq client with error handling
client = None
try:
    if GROQ_API_KEY:
        client = Groq(api_key=GROQ_API_KEY)
        logger.info("Groq client initialized successfully")
    else:
        logger.warning("No valid GROQ_API_KEY provided. Running in fallback mode.")
        logger.info("To enable AI responses, set GROQ_API_KEY environment variable with a valid Groq API key")
except Exception as e:
    logger.error(f"Failed to initialize Groq client: {e}")
    logger.info("Running in fallback mode with pre-written responses")

# Store conversation context
conversation_context = []

# Database setup
def init_db():
    """Initialize SQLite database for visitor tracking"""
    global DB_PATH
    try:
        # Try to create database in a writable location for HF Spaces
        # Use a Windows-compatible path for local development
        default_db_path = 'visitors.db' if os.name == 'nt' else '/tmp/visitors.db'
        db_path = os.environ.get('SQLITE_DB_PATH', default_db_path)
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Create visitors table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS visitors (
                id TEXT PRIMARY KEY,
                session_id TEXT,
                timestamp TEXT,
                user_type TEXT,
                question TEXT,
                answer TEXT,
                user_info TEXT,
                ip_address TEXT
            )
        ''')
        
        # Create user_profiles table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_profiles (
                session_id TEXT PRIMARY KEY,
                primary_type TEXT,
                sophistication_level TEXT,
                conversation_count INTEGER,
                first_interaction TEXT,
                last_interaction TEXT,
                topics_of_interest TEXT,
                profile_data TEXT
            )
        ''')
        
        conn.commit()
        conn.close()
        logger.info(f"Database initialized successfully at {db_path}")
        
        # Store the database path globally for other functions to use
        DB_PATH = db_path
        
        # Run database migrations
        migrate_database()
        
    except Exception as e:
        logger.error(f"Database initialization failed: {e}")
        # Set a fallback - use in-memory database
        DB_PATH = ':memory:'
        logger.warning("Using in-memory database as fallback")

# Global database path
DB_PATH = None

def migrate_database():
    """Apply database migrations for schema updates"""
    try:
        db_path = DB_PATH if DB_PATH else '/tmp/visitors.db'
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Check if user_profiles table has the new columns
        cursor.execute("PRAGMA table_info(user_profiles)")
        columns = [column[1] for column in cursor.fetchall()]
        
        # Add missing columns if they don't exist
        if 'first_seen' not in columns:
            cursor.execute('ALTER TABLE user_profiles ADD COLUMN first_seen TEXT')
            logger.info("Added first_seen column to user_profiles table")
        
        if 'last_seen' not in columns:
            cursor.execute('ALTER TABLE user_profiles ADD COLUMN last_seen TEXT')
            logger.info("Added last_seen column to user_profiles table")
            
        if 'profile_data' not in columns:
            cursor.execute('ALTER TABLE user_profiles ADD COLUMN profile_data TEXT')
            logger.info("Added profile_data column to user_profiles table")
        
        conn.commit()
        conn.close()
        logger.info("Database migration completed successfully")
        
    except Exception as e:
        logger.error(f"Database migration failed: {e}")

def get_db_connection():
    """Get database connection with fallback"""
    global DB_PATH
    if DB_PATH is None:
        logger.warning("Database not initialized, using in-memory database")
        conn = sqlite3.connect(':memory:')
        # Create tables in memory if needed
        create_tables_in_connection(conn)
        return conn
    return sqlite3.connect(DB_PATH)

def create_tables_in_connection(conn):
    """Create necessary tables in the given connection"""
    try:
        cursor = conn.cursor()
        
        # Create visitors table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS visitors (
                id TEXT PRIMARY KEY,
                session_id TEXT,
                timestamp TEXT,
                user_type TEXT,
                question TEXT,
                answer TEXT,
                user_info TEXT,
                ip_address TEXT
            )
        ''')
        
        # Create user_profiles table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_profiles (
                session_id TEXT PRIMARY KEY,
                primary_type TEXT,
                sophistication_level TEXT,
                conversation_count INTEGER,
                first_interaction TEXT,
                last_interaction TEXT,
                topics_of_interest TEXT,
                profile_data TEXT
            )
        ''')
        
        # Create daily_analytics table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS daily_analytics (
                date TEXT PRIMARY KEY,
                total_conversations INTEGER,
                unique_sessions INTEGER,
                user_type_breakdown TEXT,
                avg_conversation_length INTEGER,
                top_questions TEXT,
                updated_at TIMESTAMP
            )
        ''')
        
        conn.commit()
    except Exception as e:
        logger.error(f"Error creating tables: {e}")

# Initialize database on startup
init_db()

# Rate limiting storage
class RateLimiter:
    def __init__(self):
        self.requests = defaultdict(deque)  # IP -> deque of timestamps
        self.sessions = defaultdict(deque)  # session_id -> deque of timestamps
        
    def is_rate_limited(self, identifier, limit=60, window=3600):
        """Check if identifier (IP or session) is rate limited"""
        now = time.time()
        requests = self.requests[identifier]
        
        # Remove old requests outside the time window
        while requests and now - requests[0] > window:
            requests.popleft()
        
        # Check if within limit
        if len(requests) >= limit:
            return True, requests[0] + window  # Return reset time
        
        # Add current request
        requests.append(now)
        return False, None
    
    def get_remaining_requests(self, identifier, limit=60, window=3600):
        """Get remaining requests for identifier"""
        now = time.time()
        requests = self.requests[identifier]
        
        # Remove old requests
        while requests and now - requests[0] > window:
            requests.popleft()
        
        return max(0, limit - len(requests))
    
    def get_reset_time(self, identifier, window=3600):
        """Get time when rate limit resets"""
        requests = self.requests[identifier]
        if not requests:
            return time.time()
        return requests[0] + window

# Session management
class SessionManager:
    def __init__(self):
        self.active_sessions = {}  # session_id -> session_info
        self.session_cleanup_interval = 3600  # 1 hour
        self.last_cleanup = time.time()
    
    def create_session(self, session_id):
        """Create or update session info"""
        self.active_sessions[session_id] = {
            'created_at': time.time(),
            'last_activity': time.time(),
            'request_count': 0,
            'status': 'active'
        }
        self._cleanup_old_sessions()
        return self.active_sessions[session_id]
    
    def update_session_activity(self, session_id):
        """Update session last activity"""
        if session_id in self.active_sessions:
            self.active_sessions[session_id]['last_activity'] = time.time()
            self.active_sessions[session_id]['request_count'] += 1
        else:
            self.create_session(session_id)
    
    def get_session_info(self, session_id):
        """Get session information"""
        return self.active_sessions.get(session_id)
    
    def _cleanup_old_sessions(self):
        """Remove old inactive sessions"""
        now = time.time()
        if now - self.last_cleanup < self.session_cleanup_interval:
            return
        
        expired_sessions = []
        for session_id, info in self.active_sessions.items():
            # Remove sessions inactive for more than 24 hours
            if now - info['last_activity'] > 86400:
                expired_sessions.append(session_id)
        
        for session_id in expired_sessions:
            del self.active_sessions[session_id]
        
        self.last_cleanup = now
        logger.info(f"Cleaned up {len(expired_sessions)} expired sessions")

# Initialize rate limiter and session manager
rate_limiter = RateLimiter()
session_manager = SessionManager()

def rate_limit_decorator(limit=60, window=3600, per_session_limit=20):
    """Rate limiting decorator for API endpoints"""
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            # Get IP address
            ip_address = request.remote_addr or request.environ.get('HTTP_X_FORWARDED_FOR', 'unknown')
            
            # Get session ID if available
            session_id = None
            if request.method == 'POST' and request.get_json():
                session_id = request.get_json().get('session_id')
            
            # Check IP-based rate limit
            is_limited, reset_time = rate_limiter.is_rate_limited(f"ip:{ip_address}", limit, window)
            if is_limited:
                return jsonify({
                    "success": False,
                    "error": {
                        "type": "rate_limit_exceeded",
                        "message": "Too many requests. Please slow down.",
                        "code": "RATE_LIMITED",
                        "details": f"IP limit: {limit} requests per {window//60} minutes"
                    },
                    "rate_limit": {
                        "limit": limit,
                        "remaining": 0,
                        "reset_time": reset_time,
                        "window_seconds": window
                    },
                    "timestamp": datetime.now().isoformat()
                }), 429
            
            # Check session-based rate limit if session exists
            if session_id:
                session_is_limited, session_reset_time = rate_limiter.is_rate_limited(
                    f"session:{session_id}", per_session_limit, window
                )
                if session_is_limited:
                    return jsonify({
                        "success": False,
                        "error": {
                            "type": "session_rate_limit_exceeded", 
                            "message": "Too many requests for this session. Please wait.",
                            "code": "SESSION_RATE_LIMITED",
                            "details": f"Session limit: {per_session_limit} requests per {window//60} minutes"
                        },
                        "rate_limit": {
                            "session_limit": per_session_limit,
                            "remaining": rate_limiter.get_remaining_requests(f"session:{session_id}", per_session_limit, window),
                            "reset_time": session_reset_time,
                            "window_seconds": window
                        },
                        "timestamp": datetime.now().isoformat()
                    }), 429
            
            # Update session if exists
            if session_id:
                session_manager.update_session_activity(session_id)
            
            # Call the original function
            response = f(*args, **kwargs)
            
            # Add rate limit headers to successful responses
            if hasattr(response, 'headers'):
                response.headers['X-RateLimit-Limit'] = str(limit)
                response.headers['X-RateLimit-Remaining'] = str(rate_limiter.get_remaining_requests(f"ip:{ip_address}", limit, window))
                response.headers['X-RateLimit-Reset'] = str(int(rate_limiter.get_reset_time(f"ip:{ip_address}", window)))
                
                if session_id:
                    response.headers['X-Session-RateLimit-Limit'] = str(per_session_limit)
                    response.headers['X-Session-RateLimit-Remaining'] = str(rate_limiter.get_remaining_requests(f"session:{session_id}", per_session_limit, window))
            
            return response
        return decorated_function
    return decorator

def save_conversation(session_id, question, answer, user_type=None, user_info=None, ip_address=None):
    """Save conversation to database"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        conversation_id = str(uuid.uuid4())
        timestamp = datetime.now().isoformat()
        
        cursor.execute('''
            INSERT INTO visitors (id, session_id, timestamp, user_type, question, answer, user_info, ip_address)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ''', (conversation_id, session_id, timestamp, user_type, question, answer, json.dumps(user_info), ip_address))
        
        conn.commit()
        conn.close()
        logger.info(f"Conversation saved for session: {session_id}")
        
        # Update daily analytics in background (non-blocking)
        try:
            update_daily_analytics()
        except Exception as analytics_error:
            logger.error(f"Analytics update failed: {analytics_error}")
            
    except Exception as e:
        logger.error(f"Error saving conversation: {e}")

def get_conversation_memory(session_id, limit=5):
    """Get recent conversation history for context building"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT user_type, question, answer, timestamp, user_info
            FROM visitors 
            WHERE session_id = ?
            ORDER BY timestamp DESC
            LIMIT ?
        ''', (session_id, limit))
        
        conversations = cursor.fetchall()
        conn.close()
        
        if not conversations:
            return None
            
        # Build conversation memory (most recent first, then reverse for chronological order)
        memory = {
            "session_id": session_id,
            "total_exchanges": len(conversations),
            "conversation_history": [],
            "conversation_themes": [],
            "mentioned_topics": set(),
            "progression_pattern": []
        }
        
        # Reverse to get chronological order (oldest first)
        for i, (user_type, question, answer, timestamp, user_info_str) in enumerate(reversed(conversations)):
            exchange = {
                "exchange_number": len(conversations) - i,
                "question": question,
                "answer": answer[:200] + "..." if len(answer) > 200 else answer,  # Truncate long answers
                "user_type": user_type,
                "timestamp": timestamp,
                "topics_discussed": []
            }
            
            # Extract topics from this exchange
            question_lower = question.lower()
            answer_lower = answer.lower()
            
            # Technical topics
            if any(term in question_lower or term in answer_lower for term in ['project', 'docutalk', 'finance advisor', 'customer churn']):
                exchange["topics_discussed"].append("projects")
                memory["mentioned_topics"].add("projects")
            
            if any(term in question_lower or term in answer_lower for term in ['ai', 'ml', 'machine learning', 'artificial intelligence']):
                exchange["topics_discussed"].append("ai_ml")
                memory["mentioned_topics"].add("ai_ml")
            
            if any(term in question_lower or term in answer_lower for term in ['python', 'flask', 'coding', 'programming', 'technical']):
                exchange["topics_discussed"].append("technical_skills")
                memory["mentioned_topics"].add("technical_skills")
            
            if any(term in question_lower or term in answer_lower for term in ['experience', 'work', 'role', 'position', 'career']):
                exchange["topics_discussed"].append("experience")
                memory["mentioned_topics"].add("experience")
            
            if any(term in question_lower or term in answer_lower for term in ['education', 'college', 'degree', 'cgpa']):
                exchange["topics_discussed"].append("education")
                memory["mentioned_topics"].add("education")
                
            memory["conversation_history"].append(exchange)
            memory["progression_pattern"].append(user_type)
        
        # Identify conversation themes
        topic_counts = {}
        for topic in memory["mentioned_topics"]:
            topic_counts[topic] = sum(1 for ex in memory["conversation_history"] if topic in ex["topics_discussed"])
        
        # Most discussed topics become themes
        memory["conversation_themes"] = [topic for topic, count in sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)][:3]
        memory["mentioned_topics"] = list(memory["mentioned_topics"])
        
        return memory
        
    except Exception as e:
        logger.error(f"Error getting conversation memory: {e}")
        return None

def get_user_profile(session_id):
    """Get existing user profile from database"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT user_type, user_info, question, answer, timestamp
            FROM visitors 
            WHERE session_id = ?
            ORDER BY timestamp ASC
        ''', (session_id,))
        
        conversations = cursor.fetchall()
        conn.close()
        
        if not conversations:
            return None
            
        # Build user profile from conversation history
        profile = {
            "session_id": session_id,
            "conversation_count": len(conversations),
            "user_types_detected": [],
            "interests": [],
            "questions_asked": [],
            "first_interaction": conversations[0][4],
            "last_interaction": conversations[-1][4]
        }
        
        for conv in conversations:
            user_type, user_info_str, question, answer, timestamp = conv
            
            if user_type:
                profile["user_types_detected"].append(user_type)
            
            profile["questions_asked"].append({
                "question": question,
                "timestamp": timestamp,
                "type": user_type
            })
            
            # Extract interests from questions
            if any(keyword in question.lower() for keyword in ['ai', 'machine learning', 'ml']):
                profile["interests"].append("AI/ML")
            if any(keyword in question.lower() for keyword in ['python', 'coding', 'development']):
                profile["interests"].append("Development")
            if any(keyword in question.lower() for keyword in ['project', 'work', 'experience']):
                profile["interests"].append("Projects")
        
        # Determine primary user type
        if profile["user_types_detected"]:
            profile["primary_type"] = max(set(profile["user_types_detected"]), 
                                        key=profile["user_types_detected"].count)
        else:
            profile["primary_type"] = "unknown"
            
        # Remove duplicates from interests
        profile["interests"] = list(set(profile["interests"]))
        
        return profile
        
    except Exception as e:
        logger.error(f"Error getting user profile: {e}")
        return None

def create_conversation_context_summary(conversation_memory):
    """Create a concise summary of conversation history for AI context"""
    if not conversation_memory or not conversation_memory["conversation_history"]:
        return "This is the first conversation with this user."
    
    history = conversation_memory["conversation_history"]
    themes = conversation_memory["conversation_themes"]
    total_exchanges = conversation_memory["total_exchanges"]
    
    # Create context summary
    summary = f"CONVERSATION HISTORY ({total_exchanges} previous exchanges):\n"
    
    # Add main themes
    if themes:
        summary += f"Main topics discussed: {', '.join(themes)}\n"
    
    # Add recent exchanges (last 3)
    summary += "\nRecent conversation flow:\n"
    for exchange in history[-3:]:  # Last 3 exchanges
        summary += f"Q{exchange['exchange_number']}: {exchange['question'][:100]}{'...' if len(exchange['question']) > 100 else ''}\n"
        summary += f"A{exchange['exchange_number']}: {exchange['answer'][:150]}{'...' if len(exchange['answer']) > 150 else ''}\n\n"
    
    # Add progression insights
    user_types = conversation_memory["progression_pattern"]
    if len(set(user_types)) > 1:
        summary += f"User type evolution: {' β†’ '.join(user_types[-3:])}\n"
    
    return summary

def analyze_user_sophistication(question, profile=None):
    """Analyze how technical/sophisticated the user's question is"""
    question_lower = question.lower()
    
    # Technical sophistication indicators
    advanced_terms = ['architecture', 'implementation', 'algorithm', 'optimization', 'scalability', 
                     'deployment', 'microservices', 'api design', 'database design', 'performance']
    
    intermediate_terms = ['python', 'machine learning', 'ai', 'framework', 'library', 'code', 
                         'development', 'programming', 'technical']
    
    basic_terms = ['what is', 'how to', 'beginner', 'learn', 'tutorial', 'simple', 'basic']
    
    if any(term in question_lower for term in advanced_terms):
        return 'advanced'
    elif any(term in question_lower for term in intermediate_terms):
        return 'intermediate' 
    elif any(term in question_lower for term in basic_terms):
        return 'beginner'
    else:
        return 'intermediate'  # default

def get_visitor_analytics():
    """Get comprehensive analytics about all visitors and conversations"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        analytics = {
            "overview": {},
            "user_types": {},
            "sophistication_levels": {},
            "popular_topics": {},
            "conversation_patterns": {},
            "engagement_metrics": {},
            "temporal_analysis": {}
        }
        
        # Overview metrics
        cursor.execute('SELECT COUNT(*) FROM visitors')
        analytics["overview"]["total_conversations"] = cursor.fetchone()[0]
        
        cursor.execute('SELECT COUNT(DISTINCT session_id) FROM visitors')
        analytics["overview"]["unique_visitors"] = cursor.fetchone()[0]
        
        cursor.execute('SELECT AVG(LENGTH(question)) FROM visitors')
        avg_question_length = cursor.fetchone()[0] or 0
        analytics["overview"]["avg_question_length"] = round(avg_question_length, 2)
        
        cursor.execute('SELECT AVG(LENGTH(answer)) FROM visitors')
        avg_answer_length = cursor.fetchone()[0] or 0
        analytics["overview"]["avg_answer_length"] = round(avg_answer_length, 2)
        
        # User type distribution
        cursor.execute('SELECT user_type, COUNT(*) FROM visitors GROUP BY user_type')
        for user_type, count in cursor.fetchall():
            analytics["user_types"][user_type or 'unknown'] = count
        
        # Popular topics analysis
        cursor.execute('SELECT question, COUNT(*) as frequency FROM visitors GROUP BY LOWER(question) HAVING frequency > 1 ORDER BY frequency DESC LIMIT 10')
        popular_questions = cursor.fetchall()
        analytics["popular_topics"]["repeated_questions"] = [
            {"question": q, "frequency": f} for q, f in popular_questions
        ]
        
        # Engagement patterns - conversations per session
        cursor.execute('''
            SELECT session_id, COUNT(*) as conversation_count, 
                   MIN(timestamp) as first_interaction, 
                   MAX(timestamp) as last_interaction
            FROM visitors 
            GROUP BY session_id
            ORDER BY conversation_count DESC
        ''')
        
        session_data = cursor.fetchall()
        total_sessions = len(session_data)
        
        if total_sessions > 0:
            conversation_counts = [row[1] for row in session_data]
            analytics["engagement_metrics"] = {
                "avg_conversations_per_session": round(sum(conversation_counts) / total_sessions, 2),
                "max_conversations_in_session": max(conversation_counts),
                "single_question_sessions": len([c for c in conversation_counts if c == 1]),
                "multi_turn_sessions": len([c for c in conversation_counts if c > 1]),
                "highly_engaged_sessions": len([c for c in conversation_counts if c >= 5])
            }
        
        # Top engaged sessions
        analytics["conversation_patterns"]["top_engaged_sessions"] = []
        for session_id, count, first, last in session_data[:5]:
            analytics["conversation_patterns"]["top_engaged_sessions"].append({
                "session_id": session_id[:8] + "...",  # Truncate for privacy
                "conversation_count": count,
                "first_interaction": first,
                "last_interaction": last,
                "duration_hours": round((datetime.fromisoformat(last) - datetime.fromisoformat(first)).total_seconds() / 3600, 2) if count > 1 else 0
            })
        
        # Temporal analysis - conversations by hour of day
        cursor.execute('''
            SELECT strftime('%H', timestamp) as hour, COUNT(*) as count
            FROM visitors 
            GROUP BY hour
            ORDER BY hour
        ''')
        hourly_data = cursor.fetchall()
        analytics["temporal_analysis"]["hourly_distribution"] = {
            hour: count for hour, count in hourly_data
        }
        
        # Recent activity (last 7 days)
        cursor.execute('''
            SELECT DATE(timestamp) as date, COUNT(*) as count
            FROM visitors 
            WHERE timestamp >= datetime('now', '-7 days')
            GROUP BY date
            ORDER BY date DESC
        ''')
        recent_activity = cursor.fetchall()
        analytics["temporal_analysis"]["recent_activity"] = [
            {"date": date, "conversations": count} for date, count in recent_activity
        ]
        
        conn.close()
        return analytics
        
    except Exception as e:
        logger.error(f"Error getting analytics: {e}")
        return {"error": "Could not retrieve analytics"}

def get_session_insights(session_id):
    """Get detailed insights for a specific session"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT timestamp, user_type, question, answer, user_info
            FROM visitors 
            WHERE session_id = ?
            ORDER BY timestamp ASC
        ''', (session_id,))
        
        conversations = cursor.fetchall()
        conn.close()
        
        if not conversations:
            return {"error": "Session not found"}
        
        insights = {
            "session_id": session_id,
            "conversation_count": len(conversations),
            "first_interaction": conversations[0][0],
            "last_interaction": conversations[-1][0],
            "user_journey": [],
            "detected_user_types": set(),
            "topics_explored": set(),
            "sophistication_progression": []
        }
        
        for i, (timestamp, user_type, question, answer, user_info_str) in enumerate(conversations):
            user_info = json.loads(user_info_str) if user_info_str else {}
            
            insights["user_journey"].append({
                "turn": i + 1,
                "timestamp": timestamp,
                "question": question,
                "question_length": len(question),
                "answer_length": len(answer),
                "detected_type": user_type,
                "sophistication": user_info.get('sophistication_level', 'unknown')
            })
            
            if user_type:
                insights["detected_user_types"].add(user_type)
                
            # Extract topics mentioned in question
            question_lower = question.lower()
            for project in YASH_PROFILE['flagship_projects']:
                if project['name'].lower() in question_lower:
                    insights["topics_explored"].add(project['name'])
        
        # Convert sets to lists for JSON serialization
        insights["detected_user_types"] = list(insights["detected_user_types"])
        insights["topics_explored"] = list(insights["topics_explored"])
        
        return insights
        
    except Exception as e:
        logger.error(f"Error getting session insights: {e}")
        return {"error": "Could not retrieve session insights"}

def update_daily_analytics():
    """Update daily analytics summary for performance tracking"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # Create analytics table if it doesn't exist
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS daily_analytics (
                date TEXT PRIMARY KEY,
                total_conversations INTEGER,
                unique_sessions INTEGER,
                user_type_breakdown TEXT,
                avg_conversation_length INTEGER,
                top_questions TEXT,
                updated_at TIMESTAMP
            )
        ''')
        
        today = datetime.now().strftime('%Y-%m-%d')
        
        # Get today's stats
        cursor.execute('''
            SELECT COUNT(*) as total_conversations,
                   COUNT(DISTINCT session_id) as unique_sessions,
                   AVG(LENGTH(question || ' ' || answer)) as avg_length
            FROM visitors 
            WHERE DATE(timestamp) = ?
        ''', (today,))
        
        stats = cursor.fetchone()
        total_conversations, unique_sessions, avg_length = stats or (0, 0, 0)
        
        # Get user type breakdown for today
        cursor.execute('''
            SELECT user_type, COUNT(*) 
            FROM visitors 
            WHERE DATE(timestamp) = ?
            GROUP BY user_type
        ''', (today,))
        
        user_types = dict(cursor.fetchall())
        
        # Get top questions for today
        cursor.execute('''
            SELECT question, COUNT(*) as freq
            FROM visitors 
            WHERE DATE(timestamp) = ?
            GROUP BY LOWER(question)
            HAVING freq > 1
            ORDER BY freq DESC
            LIMIT 5
        ''', (today,))
        
        top_questions = [{"question": q, "frequency": f} for q, f in cursor.fetchall()]
        
        # Insert or update today's analytics
        cursor.execute('''
            INSERT OR REPLACE INTO daily_analytics 
            (date, total_conversations, unique_sessions, user_type_breakdown, avg_conversation_length, top_questions, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ''', (
            today,
            total_conversations,
            unique_sessions,
            json.dumps(user_types),
            int(avg_length) if avg_length else 0,
            json.dumps(top_questions),
            datetime.now().isoformat()
        ))
        
        conn.commit()
        conn.close()
        logger.info(f"Daily analytics updated for {today}")
        
    except Exception as e:
        logger.error(f"Error updating daily analytics: {e}")

def get_response_template(user_type, sophistication_level):
    """Get response template with examples based on user type and sophistication"""
    templates = {
        'recruiter': {
            'advanced': {
                'greeting': "Sure! Let me tell you about Yash's technical background.",
                'focus': "system architecture, scalability, team leadership",
                'metrics': "complex technical achievements and innovation impact",
                'closing': "What specific technical challenges is your team facing?"
            },
            'intermediate': {
                'greeting': "Yash has some solid experience that might interest you.",
                'focus': "proven results, technical skills, business impact",
                'metrics': "94% accuracy rates, 90% efficiency improvements",
                'closing': "What role are you considering him for?"
            },
            'beginner': {
                'greeting': "Happy to share Yash's background with you.",
                'focus': "educational background, internship success, eagerness to learn",
                'metrics': "8.12 CGPA, successful project deliveries",
                'closing': "What kind of responsibilities would the position involve?"
            }
        },
        'technical': {
            'advanced': {
                'greeting': "What technical aspects would you like to know about?",
                'focus': "architecture patterns, optimization strategies, system design",
                'metrics': "performance benchmarks, scalability solutions",
                'closing': "What specific technical challenges interest you?"
            },
            'intermediate': {
                'greeting': "Sure, I can walk you through his technical work.",
                'focus': "specific technologies, practical solutions, measurable results",
                'metrics': "tech stack choices, implementation strategies",
                'closing': "Are you working on anything similar?"
            },
            'beginner': {
                'greeting': "I can explain his technical projects in simple terms.",
                'focus': "clear explanations, practical applications, learning resources",
                'metrics': "real-world examples, educational context",
                'closing': "Would you like me to explain any specific concepts?"
            }
        }
    }
    
    return templates.get(user_type, {}).get(sophistication_level, {
        'greeting': "Hey! What would you like to know about Yash?",
        'focus': "his skills and experience",
        'metrics': "his achievements and projects",
        'closing': "Anything specific you're curious about?"
    })

def update_user_profile(session_id, question, user_type, sophistication_level):
    """Update user profile with new insights"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # Create or update user profile table
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_profiles (
                session_id TEXT PRIMARY KEY,
                primary_type TEXT,
                sophistication_level TEXT,
                interests TEXT,
                conversation_count INTEGER,
                first_seen TEXT,
                last_seen TEXT,
                profile_data TEXT
            )
        ''')
        
        # Check if profile exists
        cursor.execute('SELECT * FROM user_profiles WHERE session_id = ?', (session_id,))
        existing = cursor.fetchone()
        
        timestamp = datetime.now().isoformat()
        
        if existing:
            # Update existing profile
            cursor.execute('''
                UPDATE user_profiles 
                SET primary_type = ?, sophistication_level = ?, last_seen = ?,
                    conversation_count = conversation_count + 1
                WHERE session_id = ?
            ''', (user_type, sophistication_level, timestamp, session_id))
        else:
            # Create new profile
            cursor.execute('''
                INSERT INTO user_profiles 
                (session_id, primary_type, sophistication_level, conversation_count, first_seen, last_seen)
                VALUES (?, ?, ?, 1, ?, ?)
            ''', (session_id, user_type, sophistication_level, timestamp, timestamp))
        
        conn.commit()
        conn.close()
        logger.info(f"User profile updated for session: {session_id}")
        
    except Exception as e:
        logger.error(f"Error updating user profile: {e}")

# Yash Gori's comprehensive profile data
YASH_PROFILE = {
    "personal_info": {
        "name": "Yash Gori",
        "title": "AI Product IC (Individual Contributor with product leadership exposure)",
        "core_identity": "AI Engineer Γ— Product Manager β€” bridges technical depth with product thinking",
        "work_style": "Builder-first, curious, hands-on β€” learns by making things, not reading about them",
        "sweet_spot": "Early-stage AI-driven startups where can own problems end-to-end (0β†’1)",
        "location": "Mumbai, Maharashtra, India",
        "email": "[email protected]",
        "phone": "7718081766",
        "linkedin": "https://linkedin.com/in/yashgori20",
        "github": "https://github.com/yashgori20",
        "hugging_face": "https://huggingface.co/yashgori20",
        "instagram": "https://www.instagram.com/yashgori20",
        "twitter": "https://twitter.com/yashgori20",
        "about": "AI Product IC with hybrid AI Engineer Γ— Product Manager skills. Bridges technical depth with product thinking. Led AI products from 0β†’1, secured Microsoft AI Hub funding, and converted pilots to paid B2B deployments. Specializes in early-stage GenAI startups.",
        "what_i_bring": "I transform AI concepts into market-ready products by understanding user problems, building solutions, shipping products, gathering feedback, and iterating. Not isolated engineering or pure theory β€” I own problems end-to-end with technical depth and product thinking combined.",
        "philosophy": "If I don't know how something works, I'll learn it until I do.",
        "what_excites_me": "Understanding user problems β†’ building solutions β†’ shipping products β†’ gathering feedback β†’ iterating",
        "languages": ["English (Fluent)", "Hindi (Native)", "Gujarati (Native)", "Marathi (Conversational)"],
        "personality_traits": {
            "work_personality": "Collaborative (not a lone wolf), thrive with cross-functional teams. Curious and experimental, enjoy exploring and revising. Product-first thinking, care about 'why we're building' as much as 'how'. Long-term oriented in relationships, projects, and career growth.",
            "learning_style": "Experiment-first, documentation-second. Learn through curiosity about problems, not academic exercises. Build something real, break it, fix it, improve it. Just-in-time learning (learn what you need when you need it).",
            "risk_appetite": "Progress beats perfection. Once pitched and demoed SwiftCheck (unfinished AI product) to investors and enterprise clients. The system was still rough but believed in moving forward. Secured Microsoft AI Hub funding.",
            "values": "Power over money (not flashy, but the kind that lets you shape ideas and decisions). Giving up is the only real failure; bad outcomes are just data.",
            "personal_interests": ["Beach > Mountains", "MMA & Swimming (currently learning)", "Sad Bollywood music", "Series: Rom-coms to mind-bending (Dark, Patriot, Attack on Titan)", "Cooking (light hobbyist)"]
        }
    },
    
    "education": {
        "current": {
            "degree": "B.Tech in Information Technology",
            "institution": "K.J. SOMAIYA COLLEGE OF ENGINEERING",
            "duration": "2021 – 2025",
            "cgpa": "8.12/10"
        },
        "previous": {
            "qualification": "12th (HSC)",
            "institution": "LAKSHYA JUNIOR COLLEGE",
            "year": "2021",
            "percentage": "84.17%"
        }
    },
    
    "current_position": {
        "role": "AI Product Lead (IC)",
        "company": "Webotix IT Consultancy",
        "company_context": "Early-stage AI SaaS startup focusing on GenAI QA",
        "location": "Mumbai, Maharashtra (Remote)",
        "duration": "February 2025 – Present",
        "role_type": "Hybrid role across AI Engineering, Product Strategy, and Execution",
        "key_responsibilities": {
            "ai_development": [
                "Build and maintain AI features including backend logic, APIs, and service integrations",
                "Work on Azure-based systems for AI deployment, storage, and API management",
                "Design and test GenAI workflows (RAG pipelines, embedding models, prompt engineering)",
                "Set up and maintain backend infrastructure for smooth AI–app integration",
                "Manage AI model versions, logs, and performance tracking in production",
                "Review AI system accuracy, latency, and performance for optimization",
                "Troubleshoot issues in deployed AI systems and ensure smooth operation"
            ],
            "product_strategy": [
                "Work directly with Giash Sir (CEO) to define product vision, AI features, and roadmap",
                "Collaborate on prioritization, trade-offs, and go/no-go decisions",
                "Write PRDs and technical documentation for AI-related product updates",
                "Participate in product strategy discussions with leadership",
                "Research new AI tools, APIs, and frameworks suitable for product use",
                "Test new features post-integration to ensure reliability and alignment with product goals"
            ],
            "cross_functional": [
                "Coordinate with Ashish (App Developer) for app-side implementation and technical dependencies",
                "Work with design teams on system architecture and Figma flows",
                "Bridge communication between product, tech, and business functions",
                "Review technical feasibility of proposed designs",
                "Define system architecture for AI and app components, ensuring scalability and performance",
                "Collaborate on Figma design flows to align UX with backend AI functionalities",
                "Document system design diagrams and architecture flow for team understanding",
                "Coordinate project timelines and deliverables with team members"
            ],
            "client_demos": [
                "Support internal and client demos by explaining AI features and outcomes",
                "Gather and analyze user feedback for feature improvements",
                "Prepare presentations and status updates for leadership and investor discussions",
                "Assist in meetings by providing AI-related insights and recommendations"
            ]
        },
        "key_achievements": [
            "Built and deployed GenAI-powered features (RAG pipelines, embedding systems, Azure APIs) from concept to production",
            "Secured Microsoft AI Hub funding by leading the product's technical and strategic pitch",
            "Achieved 80%+ model accuracy, supporting 25+ compliance parameters with sub-second response latency",
            "Converted pilot to production deployment, boosting user adoption by 30%",
            "Reduced document generation time by 90% through optimized AI workflows",
            "Continuously learning and experimenting with new AI and cloud technologies to improve system performance"
        ]
    },
    
    "technical_skills": {
        "ai_ml_core": [
            "Retrieval-Augmented Generation (RAG) Systems",
            "Prompt Engineering", 
            "Vector Databases (FAISS, Pinecone)",
            "LLM Integration (GPT, Mixtral, LLaMA, Gemini)",
            "OCR Processing",
            "Scikit-learn",
            "Natural Language Processing"
        ],
        "technical_delivery": [
            "Python",
            "LangChain",
            "Streamlit", 
            "API Development (REST, FASTAPI, Flask)",
            "Azure (OpenAI, Cosmos DB, Container Apps)",
            "Docker",
            "GitHub Actions"
        ],
        "product_collaboration": [
            "Product Strategy",
            "Agile/Scrum",
            "Roadmap Planning", 
            "Cross-functional Team Leadership",
            "Stakeholder Communication",
            "Client Relations",
            "Data-Driven Decision Making"
        ],
        "programming": ["Python", "SQL", "JavaScript", "TypeScript"],
        "ai_ml": ["LangChain", "RAG Systems", "FAISS", "Pinecone", "Azure AI Search", "GPT-4", "Mixtral", "Gemini", "Prompt Engineering"],
        "llm_platforms": ["Azure OpenAI", "GPT-4", "Mixtral", "Gemini", "GROQ Cloud", "Together AI"],
        "frameworks": ["Flask", "Streamlit", "FastAPI", "React", "Flutter"],
        "cloud": ["Azure OpenAI", "Azure Cosmos DB", "Azure Container Apps", "Docker", "GitHub Actions"],
        "databases": ["PostgreSQL", "Azure Cosmos DB", "Redis", "Firebase", "Vector Databases"],
        "data": ["Pandas", "NumPy", "Power BI", "Random Forest", "Decision Trees", "Seaborn", "Matplotlib"],
        "tools": ["Git", "GitHub", "PowerBI", "Docker", "Azure", "Figma"]
    },
    
    "soft_skills": ["Detail Oriented", "Adaptability", "Critical Thinking", "Creative Problem Solving"],
    
    "flagship_projects": [
        {
            "name": "ChargeOrFill β€” EV Charging Aggregator App",
            "role": "Founder / Product Lead",
            "status": "Concept & Research Validation",
            "description": "Conceived and led a 0β†’1 product to unify EV charging networks across Mumbai after observing rising adoption but fragmented user experience (each brand had its own app). Conducted extensive research and made go/no-go decision based on product-market fit validation.",
            "technologies": ["Product Strategy", "Market Research", "User Research", "Figma", "Competitive Analysis", "Go-to-Market Strategy"],
            "key_features": [
                "Conducted extensive research using on-ground interviews, online surveys, competitive benchmarking, and root-cause analysis frameworks",
                "Designed complete Figma prototype for EV charging aggregator UI",
                "Planned stakeholder outreach for station owners and modeled revenue through commissions",
                "Validated learning on product-market fit and go/no-go decision-making"
            ],
            "problem": "Rising EV adoption in 2021 Mumbai, but users faced friction discovering and managing multiple charging apps (Ather, Statiq, Tata Power). No unified interface existed.",
            "research_approach": [
                "On-ground interviews with EV owners, showroom managers, station vendors",
                "Online surveys + EV forums (Reddit, Facebook groups)",
                "Competitive benchmarking (Ather Grid, Statiq, Tata Power EZ, Chargeup)",
                "Root-cause analysis: Why do EV owners struggle?"
            ],
            "key_insight": "~80% of EV users charged at home or in private facilities β†’ validated lack of B2C product-market fit, prompting pivot toward B2B fleet solutions",
            "impact": "Demonstrated strong product thinking, market research frameworks, and ownership mindset to make data-driven go/no-go decisions",
            "learning": "Proved ability to conduct comprehensive market research, validate assumptions, and exercise product ownership through evidence-based decision-making"
        },
        {
            "name": "Swift Check AI: Enterprise QC Platform",
            "description": "Led product architecture and implementation: Azure OpenAI RAG templates, OCR ingestion, multi-tenant design; converted pilots into paid deployments.",
            "technologies": ["Product Strategy", "AI/ML", "B2B SaaS", "Azure OpenAI", "Flask", "Cosmos DB", "Redis", "Docker"],
            "key_features": [
                "Framed value for buyers: 90% time reduction on document workflows and clear compliance accuracy KPIs",
                "Live demo link + short video: show template generation (before vs after) and config UI for 25+ parameters",
                "Diagram: pipeline (OCR β†’ embeddings β†’ RAG β†’ template renderer); annotate latency and compliance checks",
                "Include pilot case study: client name (anonymized if needed), pilot-to-paid conversion rate, and ROI table",
                "Multi-tenant SaaS architecture for enterprise clients with Microsoft AI Hub funding secured"
            ],
            "impact": "Revolutionary AI product with 90% operational time reduction and enterprise B2B deployment",
            "github_repo": "https://github.com/yashgori20/swift-check-ai",
            "demo_link": "https://swift-check-ai.azurewebsites.net"
        },
        {
            "name": "Interactive AI Portfolio",
            "description": "Chat-based portfolio using custom AI model to answer questions about skills and experience.",
            "technologies": ["React", "TypeScript", "Tailwind CSS", "Vite", "TanStack Query", "Shadcn UI"],
            "key_features": [
                "AI-powered chatbot with conversation memory",
                "Multi-modal interface with smooth animations",
                "Responsive design with mobile gesture support",
                "Real-time chat with smart suggestions",
                "Professional portfolio showcase with interactive elements"
            ],
            "github_repo": "https://github.com/yashgori20/yashgori20",
            "demo_link": "https://yashgori20.vercel.app/"
        },
        {
            "name": "DocuTalk: AI Document Intelligence Platform",
            "description": "Scoped conversational UI from user interviews; delivered FAISS-backed retrieval and Flutter client for multi-platform reach.",
            "technologies": ["User Research", "API Design", "Cross-platform", "Python", "FAISS", "LangChain", "Gemini Embeddings", "Flask", "Flutter"],
            "key_features": [
                "Outcome: major time-savings on document review and measurable adoption lift",
                "Embed interactive demo (upload a doc + ask Q) and short screencast of Flutter UX",
                "Show FAISS + embedding architecture graphic and call out 40% adoption improvement",
                "Link to code and a sample dataset (redacted) so reviewers can validate retrieval accuracy",
                "Cross-platform deployment with conversational AI interface for document queries"
            ],
            "impact": "Revolutionary document understanding system for enhanced user productivity",
            "rich_content": {
                "technical_details": {
                    "architecture": "Microservices architecture with Flutter frontend, Flask API backend, and FAISS vector database",
                    "data_flow": "Document upload β†’ Text extraction β†’ Embedding generation β†’ FAISS indexing β†’ Query processing β†’ Semantic search β†’ Response generation",
                    "performance": "95% accuracy on 100+ page documents, sub-second query response times",
                    "scalability": "Handles documents up to 500 pages, supports concurrent users"
                },
                "implementation_highlights": [
                    "Custom document preprocessing pipeline for optimal text extraction",
                    "Optimized FAISS index configuration for semantic search performance",
                    "Flutter integration with real-time chat interface",
                    "Gemini LLM fine-tuning for domain-specific responses"
                ],
                "challenges_solved": [
                    "Complex document structure parsing (tables, images, multi-column layouts)",
                    "Memory optimization for large document processing",
                    "Real-time streaming responses for better UX",
                    "Cross-platform deployment consistency"
                ],
                "github_repo": "https://github.com/yashgori/docutalk",
                "demo_link": "https://docutalk-demo.streamlit.app",
                "tech_stack_details": {
                    "frontend": "Flutter (Dart) - Cross-platform mobile and web application",
                    "backend": "Flask (Python) - RESTful API with WebSocket support",
                    "ai_engine": "Gemini LLM for natural language understanding and generation",
                    "vector_db": "FAISS for high-performance semantic search and similarity matching",
                    "orchestration": "LangChain for AI workflow management and prompt engineering"
                }
            }
        },
        {
            "name": "Inhance & Interactive Portfolio",
            "description": "Built the product flow (evaluation β†’ recommendation β†’ resume generation) and integrated LLM agents for conversational help.",
            "technologies": ["Streamlit", "GROQ Cloud", "Mixtral LLM", "Multi-Agent System", "LinkedIn API", "ATS Analysis", "LaTeX", "PDF Processing"],
            "key_features": [
                "Result: tangible recruiter-facing demos, ATS scoring, and exportable resumes",
                "Add an interactive widget on portfolio: 'Score my LinkedIn' demo with live ATS output",
                "Provide before/after LinkedIn profile examples and downloadable LaTeX resume templates",
                "Multi-agent AI system for profile evaluation with optimization suggestions",
                "Multi-format support (PDF, DOCX, TXT) with professional LaTeX formatting"
            ],
            "impact": "Helps professionals optimize their LinkedIn presence for better job opportunities",
            "rich_content": {
                "technical_details": {
                    "architecture": "Multi-agent AI system with Streamlit web interface and GROQ Cloud integration",
                    "ai_workflow": "Profile analysis β†’ Multi-agent evaluation β†’ Personalized recommendations β†’ Interactive guidance",
                    "performance": "Processes LinkedIn profiles in under 30 seconds with actionable insights",
                    "user_experience": "Interactive web interface with real-time feedback and suggestions"
                },
                "implementation_highlights": [
                    "Multi-agent AI system for comprehensive profile analysis",
                    "Role-specific optimization strategies using Mixtral LLM",
                    "Real-time interactive chatbot for guided improvements",
                    "Cloud deployment for global accessibility"
                ],
                "challenges_solved": [
                    "Balancing generic advice with role-specific recommendations",
                    "Creating engaging user experience for profile optimization",
                    "Integrating multiple AI agents for cohesive analysis",
                    "Handling diverse profile formats and industries"
                ],
                "demo_link": "https://inhance-linkedin.streamlit.app",
                "tech_stack_details": {
                    "frontend": "Streamlit - Interactive web application with real-time updates",
                    "ai_platform": "GROQ Cloud - High-performance AI inference platform",
                    "llm_model": "Mixtral LLM - Advanced language model for content analysis",
                    "architecture": "Multi-agent system for specialized evaluation tasks"
                }
            }
        },
        {
            "name": "FinLLM-RAG: RBI Compliance Automation",
            "description": "Combined regulatory research with RAG model engineering; validated β‚Ή10% cost-savings case and improved model accuracy to ~80%.",
            "technologies": ["Regulatory Tech", "Market Analysis", "Python", "Mixtral LLM", "GROQ Cloud", "FAISS", "Custom Model Training"],
            "key_features": [
                "Packaged outputs into investor-ready demos and compliance dashboards",
                "Publish a short compliance playbook showing sample rule β†’ model output β†’ human review loop",
                "Include accuracy/confusion matrix screenshot and cost-savings calculation that led to the β‚Ή10% claim",
                "Custom RAG system for regulatory document processing with Mixtral LLM integration",
                "Iterative AI product refinement methodology for compliance automation"
            ],
            "impact": "Revolutionary AI compliance tool with 90% verification time reduction and 80% regulatory accuracy",
            "rich_content": {
                "technical_details": {
                    "architecture": "Multi-agent financial advisory system with RBI compliance engine and vector database integration",
                    "compliance_engine": "Real-time RBI regulation processing with 80% accuracy in loan compliance predictions",
                    "performance": "90% reduction in compliance verification time, 80% regulatory accuracy",
                    "data_processing": "MPBF/DP computations with real-time regulatory updates via FAISS vector search"
                },
                "implementation_highlights": [
                    "Custom RBI regulatory document training with high accuracy",
                    "Multi-agent architecture for MPBF/DP computations",
                    "Real-time compliance checking with vector database lookups",
                    "Industry classification system with semantic matching"
                ],
                "challenges_solved": [
                    "Complex RBI regulation interpretation and automation",
                    "Real-time financial calculation accuracy and speed",
                    "Integrating multiple data sources for compliance verification",
                    "Maintaining regulatory updates and accuracy over time"
                ],
                "demo_link": "https://finance-advisor-agent.streamlit.app",
                "tech_stack_details": {
                    "frontend": "Streamlit - Interactive financial advisory interface",
                    "ai_platform": "GROQ Cloud with Gemma 9B - Specialized financial AI processing",
                    "vector_db": "FAISS - Fast regulatory document search and compliance matching",
                    "compliance_engine": "Custom RBI regulation processing with machine learning"
                }
            }
        },
        {
            "name": "Additional Tools: Churn Predictor & Utilities",
            "description": "Produced robust analytics (churn 94% accuracy) and multimodal utilities that showcase end-to-end AI product thinking β€” from data collection to deployment and UX.",
            "technologies": ["Python", "Random Forest", "Decision trees", "Power BI", "Numpy", "Pandas", "Seaborn", "Matplotlib"],
            "key_features": [
                "Attach Power BI embed or screenshots highlighting feature importance and actionable insights",
                "Provide code link + README showing evaluation pipeline and data preprocessing steps",
                "94% accuracy in customer churn prediction with Random Forest and Decision Tree algorithms",
                "Interactive Power BI dashboard for comprehensive business insights",
                "Visual analytics pipeline with Seaborn and Matplotlib for data storytelling"
            ],
            "impact": "Provides seamless cryptocurrency information access across language barriers"
        },
        {
            "name": "LinkedIn Profile Optimization Platform",
            "description": "AI product management - identified market gap in professional profile optimization and designed solution targeting job seekers.",
            "technologies": ["Growth Hacking", "User Engagement", "Streamlit", "GROQ Cloud", "Mixtral LLM", "Multi-Agent System"],
            "key_features": [
                "I identified market gap in professional profile optimization; designed AI solution targeting job seekers and professionals",
                "I created feature prioritization matrix based on user interviews and competitive analysis",
                "I designed multi-agent evaluation system providing role-specific profile optimization with conversational AI guidance"
            ],
            "impact": "AI-powered professional optimization platform with multi-agent evaluation system"
        }
    ],
    
    "work_experience": [
        {
            "role": "AI Product Lead",
            "company": "Webotix IT Consultancy",
            "location": "Mumbai, Maharashtra (Remote)",
            "duration": "December 2024 – June 2025",
            "type": "Current Position",
            "technologies": ["Azure OpenAI GPT-4o", "Azure Cosmos DB", "Azure Document Intelligence OCR", "Product Strategy", "B2B SaaS"],
            "achievements": [
                "I led technical architecture and product strategy for enterprise QC automation platform serving food industry clients.",
                "I scoped and delivered MVP using Azure OpenAI GPT-4o, Azure Cosmos DB, and Azure Document Intelligence OCR.",
                "I coordinated with C-suite on positioning, securing $5k Microsoft AI Hub funding."
            ],
            "additional_achievements": [
                "Translated compliance requirements into 25+ parameterized templates, achieving 80% accuracy and sub-second performance.",
                "First B2B SaaS product from Webotix to receive Microsoft AI Hub funding.",
                "Independently handled architecture and deployment for production-ready enterprise solution.",
                "Designed compliance-first AI pipeline for regulated industries."
            ]
        },
        {
            "role": "Business Analyst",
            "company": "N.K. Engineering",
            "location": "Mumbai, Maharashtra",
            "duration": "June 2024 – November 2024",
            "technologies": ["Predictive Analytics", "Business Intelligence", "HTML/CSS/JS", "Market Research", "Financial Modeling"],
            "achievements": [
                "I used predictive analytics and BI to identify β‚Ή5Cr+ market potential and packaged insights into investor-ready decks.",
                "I spearheaded responsive e-commerce launch from wireframes to deployment while aligning scope to market demand.",
                "I balanced product delivery with investor relations: closed 5 new funding deals while hitting digital product launch timelines."
            ],
            "additional_achievements": [
                "Rolled out automated competitor tracking tools, enabling faster pivots in market strategy.",
                "Developed fully responsive e-commerce site in HTML, CSS, JS integrated with BI dashboards for sales tracking.",
                "Automated competitor monitoring to refresh market intelligence weekly, cutting manual research by 80%.",
                "Built predictive models for demand forecasting; results informed product roadmap and stock planning.",
                "Authored concise investor one-pagers with key metrics and opportunities; reduced funding pitch cycles by 30%."
            ]
        },
        {
            "role": "Product Design Lead",
            "company": "MetaRizz",
            "location": "Mumbai, Maharashtra",
            "duration": "December 2023 – May 2024",
            "technologies": ["Product Management", "Figma", "UI/UX Design", "Flutter", "Stakeholder Management"],
            "achievements": [
                "I owned end-to-end product for two projects including GuestInMe (1,000+ users) with AI-assisted content and UX updates.",
                "I shipped monetization features (table booking, club passes) and aligned them with stakeholder goals achieving 40% engagement increase.",
                "I ran roadmap, prioritization, and stakeholder communications while mediating clients ↔ devs to keep releases on schedule."
            ],
            "additional_achievements": [
                "Defined PRD-level specs from stakeholder asks and converted to developer-ready tickets with clear acceptance criteria.",
                "Mapped UX via Figma and coordinated handoff to Flutter devs, reducing back-and-forth during implementation.",
                "Introduced lightweight post-release reviews to decide what iterates, what ships, and what gets cut."
            ]
        },
        {
            "role": "Business Development Manager",
            "company": "Watermelon Gang",
            "location": "Mumbai, Maharashtra",
            "duration": "August 2022 – November 2023",
            "technologies": ["AI Content Workflows", "Market Analysis", "Client Lifecycle Management", "Data Analytics"],
            "achievements": [
                "I directed AI-powered content workflows, managing a 2-person creative team to deliver for 5 enterprise clients.",
                "I combined market analysis with AI content optimization to boost engagement metrics by 35%.",
                "I owned client relationship lifecycle, from outreach to delivery, across fintech and cryptocurrency sectors."
            ],
            "additional_achievements": [
                "Built a modular AI-assisted content system that reduced production time by 40%.",
                "Introduced data-backed A/B testing for social media creatives, influencing future campaign strategies.",
                "Integrated sentiment analysis into reporting to better gauge audience reception."
            ]
        }
    ],
    
    "volunteering": [
        {
            "organization": "Vacha NGO",
            "role": "English & Computer Instructor",
            "duration": "July 2024",
            "description": "I designed innovative AI-enhanced learning modules for underprivileged students with improved digital literacy engagement.",
            "activities": [
                "Coached English and computer skills to students",
                "Crafted innovative learning aids to improve engagement"
            ]
        }
    ],
    
    "unique_strengths": [
        "Full-stack AI development from concept to deployment",
        "Expertise in RAG systems and vector databases",
        "Multi-LLM platform experience (Gemini, GROQ, Mixtral, Gemma, Llama)",
        "Cross-platform development (Flutter + Flask)",
        "Financial domain AI applications",
        "Real-world business impact with measurable results",
        "Strong academic performance (8.12 CGPA)",
        "Diverse industry experience (FinTech, HealthTech, Crypto)",
        "Leadership in AI product development and documentation"
    ]
}

def create_intelligent_prompt(question, profile):
    """Create context-rich prompt for AI assistant"""
    return f"""You are representing Yash Gori, an exceptional AI Engineer and Machine Learning Developer. 
You must answer recruiter questions in a way that showcases his remarkable skills, achievements, and potential.

=== YASH GORI'S PROFILE ===

PERSONAL INFO:
- Name: {profile['personal_info']['name']}
- Title: {profile['personal_info']['title']}
- Location: {profile['personal_info']['location']}
- Email: {profile['personal_info']['email']}
- Current Role: {profile['current_position']['role']} at {profile['current_position']['company']}

EDUCATION:
- {profile['education']['current']['degree']} - CGPA: {profile['education']['current']['cgpa']}
- {profile['education']['current']['institution']}

CURRENT POSITION:
Role: {profile['current_position']['role']} at {profile['current_position']['company']}
Key Work:
{chr(10).join('β€’ ' + resp for resp in profile['current_position']['responsibilities'])}

TECHNICAL EXPERTISE:
- AI/ML: {', '.join(profile['technical_skills']['ai_ml'])}
- LLM Platforms: {', '.join(profile['technical_skills']['llm_platforms'])}
- Programming: {', '.join(profile['technical_skills']['programming'])}
- Frameworks: {', '.join(profile['technical_skills']['frameworks'])}

FLAGSHIP PROJECTS:
"""
    
    for project in profile['flagship_projects']:
        prompt += f"""
πŸš€ {project['name']}:
   Technologies: {', '.join(project['technologies'])}
   Impact: {project['impact']}
"""
    
    prompt += f"""

WORK EXPERIENCE HIGHLIGHTS:
"""
    for exp in profile['work_experience']:
        prompt += f"""
β€’ {exp['role']} at {exp['company']} ({exp['duration']})
  Achievements: {', '.join(exp['achievements'][:2])}
"""
    
    prompt += f"""

UNIQUE STRENGTHS:
{chr(10).join('✨ ' + strength for strength in profile['unique_strengths'])}

=== INSTRUCTIONS ===
1. Answer as Yash's AI representative with enthusiasm and confidence
2. Highlight specific technical achievements and real-world impact
3. Mention concrete technologies, accuracies, and business results
4. Show passion for AI development and innovation
5. Be specific about his multi-LLM expertise and RAG systems
6. If asked about availability, mention he's actively seeking new opportunities and available for immediate start
7. Always maintain professional, confident, and engaging tone
8. Showcase his unique combination of technical depth and business impact

RECRUITER QUESTION: {question}

Provide a comprehensive response that makes Yash irresistible to hire:"""
    
    return prompt

def detect_question_clarity(question):
    """Detect if question is unclear and needs clarification"""
    question_lower = question.lower().strip()
    
    # Very short/vague questions
    if len(question_lower.split()) <= 2:
        return {
            'is_unclear': True,
            'reason': 'too_short',
            'clarity_score': 0.2,
            'suggestions': ['Could you provide more details about what you\'d like to know?', 
                          'What specific aspect interests you most?']
        }
    
    # Ambiguous pronouns without context
    ambiguous_patterns = ['tell me about him', 'what does he do', 'his work', 'about yash', 'yash gori']
    if any(pattern in question_lower for pattern in ambiguous_patterns) and len(question_lower.split()) <= 4:
        return {
            'is_unclear': True,
            'reason': 'ambiguous_scope',
            'clarity_score': 0.4,
            'suggestions': ['Are you interested in his technical projects, work experience, or something specific?',
                          'What brings you here - are you a recruiter, developer, or looking to collaborate?']
        }
    
    # Very general questions
    general_patterns = ['tell me about', 'what about', 'how about', 'anything about']
    if any(pattern in question_lower for pattern in general_patterns) and 'specific' not in question_lower:
        return {
            'is_unclear': True,
            'reason': 'too_general',
            'clarity_score': 0.6,
            'suggestions': ['What specific area would you like to focus on?',
                          'Are you more interested in his projects, skills, or experience?']
        }
    
    # Question seems clear
    return {
        'is_unclear': False,
        'reason': 'clear',
        'clarity_score': 0.9,
        'suggestions': []
    }

def detect_user_intent(question):
    """Detect what type of user is asking and their intent"""
    question_lower = question.lower()
    
    # Recruiter indicators
    recruiter_keywords = ['hire', 'position', 'role', 'salary', 'available', 'interview', 'candidate', 'resume', 'cv']
    
    # Technical indicators  
    tech_keywords = ['code', 'implementation', 'architecture', 'algorithm', 'technical', 'how did', 'explain']
    
    # Collaboration indicators
    collab_keywords = ['collaborate', 'project', 'work together', 'partnership', 'team up']
    
    # Student/learning indicators
    student_keywords = ['learn', 'tutorial', 'how to', 'beginner', 'guide', 'study']
    
    if any(word in question_lower for word in recruiter_keywords):
        return 'recruiter'
    elif any(word in question_lower for word in tech_keywords):
        return 'technical'
    elif any(word in question_lower for word in collab_keywords):
        return 'collaborator'
    elif any(word in question_lower for word in student_keywords):
        return 'student'
    else:
        return 'general'

def generate_clarifying_questions(question, user_intent, clarity_analysis, user_profile=None):
    """Generate intelligent clarifying questions based on context"""
    
    if not clarity_analysis['is_unclear']:
        return []
    
    clarifying_questions = []
    
    # Base clarifying questions by user intent
    intent_questions = {
        'recruiter': [
            "Are you evaluating Yash for a specific role?",
            "What type of position are you considering him for?",
            "What's your team's tech stack or main challenges?"
        ],
        'technical': [
            "Are you working on a similar project?", 
            "What specific technical area interests you most?",
            "Are you looking for implementation details or high-level architecture?"
        ],
        'collaborator': [
            "What kind of project are you working on?",
            "How do you envision collaborating with Yash?",
            "What's your background - are you also in AI/ML?"
        ],
        'student': [
            "What's your current experience level?",
            "What specific skills are you trying to develop?", 
            "Are you looking for learning resources or career advice?"
        ],
        'general': [
            "What brings you here today?",
            "Are you a recruiter, developer, student, or someone else?",
            "What specific aspect of Yash's background interests you?"
        ]
    }
    
    # Add context-specific questions based on clarity issue
    if clarity_analysis['reason'] == 'too_short':
        clarifying_questions.extend([
            "I'd love to help! Could you tell me more about what you're looking for?",
            "What specific information would be most valuable to you?"
        ])
    elif clarity_analysis['reason'] == 'ambiguous_scope':
        clarifying_questions.extend(intent_questions.get(user_intent, intent_questions['general']))
    elif clarity_analysis['reason'] == 'too_general':
        clarifying_questions.extend([
            "That's a broad topic! What would you like to focus on first?",
            "I can share details about his projects, experience, or skills - what interests you most?"
        ])
    
    # Note: Removed returning user logic to keep conversations natural
    
    # Return top 2-3 most relevant questions
    return clarifying_questions[:3]

def generate_follow_up_suggestions(question, answer, user_type, sophistication_level, user_profile=None):
    """Generate intelligent follow-up suggestions to continue the conversation"""
    
    suggestions = []
    
    # Base follow-up suggestions by user type
    follow_up_templates = {
        'recruiter': {
            'advanced': [
                "What specific technical leadership qualities are you looking for?",
                "How does Yash's architecture experience compare to your current needs?",
                "Would you like to discuss his experience with scaling AI systems?",
                "What's your team's biggest technical challenge right now?"
            ],
            'intermediate': [
                "What role level are you considering him for?",
                "Would you like to see examples of his project impact metrics?",
                "How important is AI/ML experience for this position?",
                "What's your hiring timeline looking like?"
            ],
            'beginner': [
                "What type of position are you hiring for?",
                "Would you like to know about his educational background?",
                "How do his AI/ML skills fit your current openings?",
                "What qualities are most important for this role?"
            ]
        },
        'technical': {
            'advanced': [
                "Want to dive deeper into the technical architecture of any specific project?",
                "Are you interested in discussing implementation challenges and solutions?",
                "Would you like to explore his approach to system design and scalability?",
                "How does his tech stack align with what you're working on?"
            ],
            'intermediate': [
                "Which specific technologies interest you most?",
                "Would you like to hear about his development approach?",
                "Are you working on similar AI/ML projects?",
                "What's your experience with RAG systems or vector databases?"
            ],
            'beginner': [
                "Would you like me to explain any of these technologies in more detail?",
                "Are you interested in learning about AI/ML development?",
                "What's your current programming experience?",
                "Would learning resources be helpful?"
            ]
        },
        'collaborator': {
            'advanced': [
                "What type of technical collaboration are you envisioning?",
                "Are you looking for a co-founder, team member, or consultant?",
                "What's the scope and timeline of your project?",
                "How do you see Yash contributing to your technical strategy?"
            ],
            'intermediate': [
                "What kind of project are you working on?",
                "What skills would complement your current team?",
                "Are you looking for AI/ML expertise specifically?",
                "What's your collaboration timeline?"
            ]
        },
        'student': {
            'intermediate': [
                "What specific AI/ML skills do you want to develop next?",
                "Are you interested in career guidance or technical learning?",
                "Would you like project ideas to build your portfolio?",
                "What's your ultimate career goal in tech?"
            ],
            'beginner': [
                "What got you interested in AI and machine learning?",
                "Are you looking for beginner-friendly learning resources?",
                "What's your current programming background?",
                "Would you like a learning roadmap for AI/ML?"
            ]
        },
        'general': [
            "What specific aspect of Yash's background interests you most?",
            "Are you a developer, recruiter, student, or something else?",
            "What brought you here today?",
            "How can I best help you learn about Yash?"
        ]
    }
    
    # Get base suggestions for user type and sophistication
    user_suggestions = follow_up_templates.get(user_type, {})
    if isinstance(user_suggestions, dict):
        suggestions.extend(user_suggestions.get(sophistication_level, user_suggestions.get('intermediate', [])))
    else:
        suggestions.extend(user_suggestions)
    
    # Add contextual suggestions based on question content
    question_lower = question.lower()
    
    if 'project' in question_lower:
        suggestions.extend([
            "Would you like to hear about his other innovative projects?",
            "Are you curious about the technical challenges he solved?"
        ])
    
    if any(tech in question_lower for tech in ['ai', 'ml', 'machine learning', 'artificial intelligence']):
        suggestions.extend([
            "Want to explore his experience with different AI/ML frameworks?",
            "Would you like to know about his approach to AI problem-solving?"
        ])
    
    if any(word in question_lower for word in ['experience', 'work', 'career']):
        suggestions.extend([
            "Interested in learning about his career progression?",
            "Would you like to hear about his leadership and mentoring experience?"
        ])
    
    # Note: Removed returning user suggestions to keep conversations natural
    
    # Add engagement boosters
    engagement_boosters = [
        "What questions do you have that I haven't answered yet?",
        "Is there anything specific you'd like to know more about?",
        "How else can I help you learn about Yash?"
    ]
    
    # Smart deduplication and selection
    unique_suggestions = []
    seen = set()
    
    for suggestion in suggestions + engagement_boosters:
        if suggestion.lower() not in seen and len(suggestion) > 10:
            unique_suggestions.append(suggestion)
            seen.add(suggestion.lower())
        
        if len(unique_suggestions) >= 5:  # Limit to top 5 suggestions
            break
    
    return unique_suggestions[:4]  # Return top 4 suggestions

def get_recommended_topics(conversation_memory, user_type):
    """Get recommended topics based on conversation history and user type"""
    if not conversation_memory:
        return []
    
    discussed_themes = set(conversation_memory.get('conversation_themes', []))
    all_possible_topics = {'projects', 'ai_ml', 'technical_skills', 'experience', 'education'}
    
    # Topics not yet discussed
    undiscussed_topics = all_possible_topics - discussed_themes
    
    # Map internal topics to user-friendly recommendations
    topic_mapping = {
        'projects': 'His innovative projects and implementations',
        'ai_ml': 'AI/ML expertise and frameworks',
        'technical_skills': 'Programming languages and technical stack',
        'experience': 'Work experience and career progression',
        'education': 'Educational background and achievements'
    }
    
    recommendations = []
    
    # Prioritize based on user type
    if user_type == 'recruiter':
        priority_order = ['experience', 'projects', 'technical_skills', 'education', 'ai_ml']
    elif user_type == 'technical':
        priority_order = ['projects', 'ai_ml', 'technical_skills', 'experience', 'education']
    elif user_type == 'student':
        priority_order = ['education', 'ai_ml', 'projects', 'technical_skills', 'experience']
    else:
        priority_order = ['projects', 'experience', 'ai_ml', 'technical_skills', 'education']
    
    # Add undiscussed topics in priority order
    for topic in priority_order:
        if topic in undiscussed_topics and len(recommendations) < 3:
            recommendations.append(topic_mapping[topic])
    
    return recommendations[:3]

def analyze_conversation_flow(conversation_memory):
    """Analyze conversation flow patterns for intelligent suggestions"""
    if not conversation_memory or not conversation_memory.get('conversation_history'):
        return {
            'flow_type': 'initial',
            'progression': 'starting',
            'depth_trend': 'surface',
            'engagement_pattern': 'new'
        }
    
    history = conversation_memory['conversation_history']
    user_types = conversation_memory.get('progression_pattern', [])
    
    # Analyze progression patterns
    if len(set(user_types)) > 2:
        progression = 'exploring'  # User is exploring different aspects
    elif len(user_types) > 2 and len(set(user_types)) <= 2:
        progression = 'deepening'  # User is going deeper in specific areas
    else:
        progression = 'focused'   # User has consistent intent
    
    # Analyze depth trend
    recent_topics = []
    for exchange in history[-3:]:  # Last 3 exchanges
        recent_topics.extend(exchange.get('topics_discussed', []))
    
    unique_recent_topics = len(set(recent_topics))
    if unique_recent_topics > 2:
        depth_trend = 'broad'     # Covering many topics
    elif unique_recent_topics == 2:
        depth_trend = 'balanced'  # Mix of topics
    else:
        depth_trend = 'deep'      # Focused on one topic
    
    # Determine flow type
    total_exchanges = len(history)
    if total_exchanges < 2:
        flow_type = 'initial'
    elif total_exchanges < 4:
        flow_type = 'developing'
    else:
        flow_type = 'established'
    
    return {
        'flow_type': flow_type,
        'progression': progression,
        'depth_trend': depth_trend,
        'engagement_pattern': 'high' if total_exchanges > 3 else 'moderate'
    }

def generate_smart_suggestions(question, user_type, sophistication_level, conversation_memory, conversation_flow):
    """Generate intelligent suggestions based on conversation flow and context"""
    
    flow_analysis = analyze_conversation_flow(conversation_memory)
    suggestions = {
        'immediate_follow_ups': [],
        'topic_transitions': [],
        'depth_exploration': [],
        'meta_suggestions': []
    }
    
    # Immediate follow-ups based on current question
    question_lower = question.lower()
    
    if 'project' in question_lower:
        if 'docutalk' in question_lower:
            suggestions['immediate_follow_ups'].extend([
                "How did the FAISS vector database integration work?",
                "What challenges did you face with the Flutter implementation?",
                "How does the semantic search accuracy compare to traditional search?"
            ])
        elif 'finance' in question_lower:
            suggestions['immediate_follow_ups'].extend([
                "What specific RBI regulations does it handle?",
                "How accurate is the compliance prediction?",
                "What was the business impact of this solution?"
            ])
        else:
            suggestions['immediate_follow_ups'].extend([
                "Which project had the biggest technical challenges?",
                "How do these projects showcase his AI expertise?",
                "What's the common thread in his project approach?"
            ])
    
    elif any(term in question_lower for term in ['skill', 'technology', 'experience']):
        suggestions['immediate_follow_ups'].extend([
            "How did he develop expertise in these areas?",
            "What projects best demonstrate these skills?",
            "How does he stay updated with new technologies?"
        ])
    
    # Topic transitions based on conversation flow
    if flow_analysis['progression'] == 'exploring':
        suggestions['topic_transitions'].extend([
            "Let's dive deeper into the area that interests you most",
            "Which aspect would you like to explore in more detail?",
            "We've covered several areas - what resonates with your needs?"
        ])
    elif flow_analysis['progression'] == 'deepening':
        suggestions['topic_transitions'].extend([
            "How does this connect to your specific requirements?",
            "Would you like to see how this applies to real scenarios?",
            "What other aspects of this area interest you?"
        ])
    
    # Depth exploration based on user type and sophistication
    if user_type == 'technical':
        if sophistication_level == 'advanced':
            suggestions['depth_exploration'].extend([
                "Want to discuss the system architecture in detail?",
                "How about exploring the scalability considerations?",
                "Interested in the performance optimization strategies?"
            ])
        elif sophistication_level == 'intermediate':
            suggestions['depth_exploration'].extend([
                "Would you like to understand the implementation approach?",
                "How about exploring the technology choices and reasoning?",
                "Interested in the development workflow and best practices?"
            ])
        else:  # beginner
            suggestions['depth_exploration'].extend([
                "Want to understand how these technologies work together?",
                "Would explanations of the core concepts be helpful?",
                "Interested in learning resources for similar development?"
            ])
    
    elif user_type == 'recruiter':
        suggestions['depth_exploration'].extend([
            "How do these skills translate to team leadership?",
            "What's his capacity for mentoring junior developers?",
            "How does he handle project deadlines and pressure?"
        ])
    
    # Meta suggestions based on conversation state
    themes_discussed = conversation_memory.get('conversation_themes', []) if conversation_memory else []
    total_exchanges = conversation_memory.get('total_exchanges', 0) if conversation_memory else 0
    
    if total_exchanges > 4 and flow_analysis['engagement_pattern'] == 'high':
        suggestions['meta_suggestions'].extend([
            "You seem very interested - are you considering a specific opportunity?",
            "Based on our discussion, what's your overall impression?",
            "How can I help you take the next step with Yash?"
        ])
    elif flow_analysis['depth_trend'] == 'broad':
        suggestions['meta_suggestions'].extend([
            "We've covered a lot - which area is most relevant to you?",
            "What's the primary focus you'd like me to address?",
            "Should we narrow down to the most important aspects?"
        ])
    
    return suggestions

def create_contextual_suggestion_prompt(smart_suggestions, user_type, conversation_flow):
    """Create a prompt section for contextual suggestions"""
    
    flow_analysis = analyze_conversation_flow(conversation_flow)
    
    prompt_section = f"""

🎯 SMART SUGGESTIONS INTEGRATION:
Based on conversation flow analysis:
- Flow Pattern: {flow_analysis['progression'].upper()} ({flow_analysis['depth_trend']} focus)
- Engagement Level: {flow_analysis['engagement_pattern'].upper()}
- Conversation Stage: {flow_analysis['flow_type'].upper()}

Intelligent Suggestions Available:"""
    
    if smart_suggestions['immediate_follow_ups']:
        prompt_section += f"""
β€’ Immediate Follow-ups: {', '.join(smart_suggestions['immediate_follow_ups'][:2])}"""
    
    if smart_suggestions['topic_transitions']:
        prompt_section += f"""
β€’ Topic Transitions: {', '.join(smart_suggestions['topic_transitions'][:2])}"""
    
    if smart_suggestions['depth_exploration']:
        prompt_section += f"""
β€’ Depth Exploration: {', '.join(smart_suggestions['depth_exploration'][:2])}"""
    
    prompt_section += f"""

πŸ’‘ SUGGESTION STRATEGY:
- Naturally weave the most relevant suggestions into your response
- Use the flow analysis to determine suggestion timing and style
- Match suggestion sophistication to user's technical level
- Build on the established conversation pattern"""
    
    return prompt_section

def extract_rich_project_content(question, project_name, yash_profile):
    """Extract rich, contextual content for specific projects based on user query"""
    
    # Find the project
    project = None
    for proj in yash_profile['flagship_projects']:
        if project_name.lower() in proj['name'].lower():
            project = proj
            break
    
    if not project or 'rich_content' not in project:
        return {}
    
    rich_content = project['rich_content']
    question_lower = question.lower()
    
    # Determine what type of rich content to include based on question
    content_response = {
        'project_name': project['name'],
        'basic_info': {
            'description': project['description'],
            'technologies': project['technologies'],
            'impact': project['impact']
        },
        'contextual_details': {}
    }
    
    # Technical architecture questions
    if any(term in question_lower for term in ['architecture', 'system', 'design', 'structure']):
        content_response['contextual_details']['architecture'] = rich_content['technical_details']['architecture']
        if 'data_flow' in rich_content['technical_details']:
            content_response['contextual_details']['data_flow'] = rich_content['technical_details']['data_flow']
        content_response['contextual_details']['tech_stack'] = rich_content['tech_stack_details']
    
    # Implementation questions
    if any(term in question_lower for term in ['implement', 'build', 'develop', 'create', 'code']):
        content_response['contextual_details']['implementation'] = rich_content['implementation_highlights']
        content_response['contextual_details']['challenges'] = rich_content['challenges_solved']
    
    # Performance questions
    if any(term in question_lower for term in ['performance', 'speed', 'accuracy', 'scalability']):
        content_response['contextual_details']['performance'] = rich_content['technical_details'].get('performance', '')
        if 'scalability' in rich_content['technical_details']:
            content_response['contextual_details']['scalability'] = rich_content['technical_details']['scalability']
    
    # Demo/links questions
    if any(term in question_lower for term in ['demo', 'see', 'show', 'example', 'link', 'github']):
        if 'demo_link' in rich_content:
            content_response['contextual_details']['demo_link'] = rich_content['demo_link']
        if 'github_repo' in rich_content:
            content_response['contextual_details']['github_repo'] = rich_content['github_repo']
    
    # If no specific context detected, provide overview
    if not content_response['contextual_details']:
        content_response['contextual_details'] = {
            'overview': rich_content['technical_details'],
            'highlights': rich_content['implementation_highlights'][:3],
            'links': {
                'demo': rich_content.get('demo_link', ''),
                'github': rich_content.get('github_repo', '')
            }
        }
    
    return content_response

def detect_project_mentions(question, yash_profile):
    """Detect which projects are mentioned in the question"""
    question_lower = question.lower()
    mentioned_projects = []
    
    for project in yash_profile['flagship_projects']:
        project_keywords = [
            project['name'].lower(),
            project['name'].split(' ')[0].lower(),  # First word of project name
        ]
        
        # Add specific project keywords
        if 'docutalk' in project['name'].lower():
            project_keywords.extend(['document', 'conversation', 'chat', 'pdf'])
        elif 'inhance' in project['name'].lower():
            project_keywords.extend(['linkedin', 'profile', 'optimize'])
        elif 'finance' in project['name'].lower():
            project_keywords.extend(['finance', 'rbi', 'compliance', 'advisor'])
        elif 'crypto' in project['name'].lower():
            project_keywords.extend(['crypto', 'cryptocurrency', 'bitcoin'])
        elif 'churn' in project['name'].lower():
            project_keywords.extend(['churn', 'customer', 'retention', 'prediction'])
        
        if any(keyword in question_lower for keyword in project_keywords):
            mentioned_projects.append(project['name'])
    
    return mentioned_projects

def create_rich_content_prompt_section(question, yash_profile):
    """Create prompt section with rich project content based on question context"""
    
    mentioned_projects = detect_project_mentions(question, yash_profile)
    
    if not mentioned_projects:
        return ""
    
    prompt_section = f"""

🎨 RICH CONTENT INTEGRATION:
The user's question mentions specific project(s): {', '.join(mentioned_projects)}

Enhanced Project Details Available:"""
    
    for project_name in mentioned_projects[:2]:  # Limit to 2 projects to avoid overwhelming
        rich_content = extract_rich_project_content(question, project_name, yash_profile)
        if rich_content and 'contextual_details' in rich_content:
            prompt_section += f"""

πŸ“‹ {rich_content['project_name']}:"""
            
            for key, value in rich_content['contextual_details'].items():
                if isinstance(value, list):
                    prompt_section += f"""
β€’ {key.replace('_', ' ').title()}: {', '.join(value[:3])}"""
                elif isinstance(value, dict):
                    prompt_section += f"""
β€’ {key.replace('_', ' ').title()}: {str(value)[:150]}"""
                else:
                    prompt_section += f"""
β€’ {key.replace('_', ' ').title()}: {str(value)[:150]}"""
    
    prompt_section += f"""

πŸ’‘ RICH CONTENT STRATEGY:
- Use the enhanced project details to provide comprehensive, technical answers
- Include relevant links, performance metrics, and implementation details
- Reference specific technical challenges and solutions
- Highlight unique aspects and innovations in the projects
- Make the response highly informative and technically detailed"""
    
    return prompt_section

def create_intelligent_agent_prompt(question, profile, session_id=None, user_profile=None, conversation_memory=None):
    """Create AI Agent prompt with natural conversation flow and context detection"""
    
    user_intent = detect_user_intent(question)
    sophistication = analyze_user_sophistication(question, user_profile)
    clarity_analysis = detect_question_clarity(question)
    response_template = get_response_template(user_intent, sophistication)
    
    # Generate clarifying questions if needed
    clarifying_questions = generate_clarifying_questions(question, user_intent, clarity_analysis, user_profile)
    
    # Generate smart suggestions based on conversation flow
    smart_suggestions = generate_smart_suggestions(question, user_intent, sophistication, conversation_memory, conversation_memory)
    
    # Create conversation context summary
    context_summary = create_conversation_context_summary(conversation_memory) if conversation_memory else "This is the first conversation with this user."
    
    # Create contextual suggestion prompt
    suggestion_prompt = create_contextual_suggestion_prompt(smart_suggestions, user_intent, conversation_memory)
    
    # Create rich content prompt section if project-specific questions are detected
    rich_content_prompt = create_rich_content_prompt_section(question, profile)
    
    base_prompt = f"""You're helping someone learn about Yash Gori. Answer naturally and keep it SHORT - don't repeat project names after every sentence. Use proper grammar and capitalization but stay conversational. Here are examples:

Example 1:
Human: I'm a recruiter at Paytm, what can you tell me about Yash?
Assistant: He's an AI Product IC - bridges AI engineering with product thinking. Led products from 0β†’1, secured Microsoft AI Hub funding, converted pilots to paid B2B deployments. He's builder-first, learns by making things. Currently looking for AI PM or AI Product IC roles in early-stage GenAI startups. What kind of role are you hiring for?

Example 2:
Human: Tell me about the SwiftCheck AI project.
Assistant: It's an enterprise QC automation platform for manufacturing and food industries. Built RAG pipelines with Azure OpenAI, achieved 90% faster QC generation with 80% accuracy. Converted pilot to production and secured Microsoft AI Hub funding. He handled everything from architecture to client demos. Similar to your use case?

Example 3:
Human: What makes Yash different from other AI engineers?
Assistant: He's not just coding - he owns problems end-to-end. Understands user problems, builds solutions, ships products, gathers feedback, iterates. That's the full cycle. He's collaborative, product-first, works well in cross-functional teams. Not a lone wolf type. What matters more to you - pure engineering or product ownership?

Example 4:
Human: I'm learning AI, any tips from Yash's journey?
Assistant: His philosophy is simple: "If I don't know how something works, I'll learn it until I do." He's experiment-first, learns by building real things and breaking them. Started with fundamentals, then jumped into AI through actual projects like DocuTalk and FinLLM. Just-in-time learning, not academic theory. What are you building right now?

Example 5:
Human: Tell me about his ChargeOrFill project.
Assistant: That was a 0β†’1 EV charging aggregator concept for Mumbai. He did extensive research - on-ground interviews, surveys, competitive analysis. Key finding: 80% of EV users charged at home, so no B2C product-market fit. He made the go/no-go call based on data. Shows strong product thinking and ownership mindset. Ever done that kind of validation work?

Example 6:
Human: What's his work style like?
Assistant: Builder-first, curious, hands-on. Thrives in cross-functional teams, not a lone wolf. Cares about "why we're building" as much as "how." Long-term oriented in relationships and projects. He's the "progress beats perfection" type - once demoed an unfinished product to investors and it worked out. What kind of team culture are you looking for?

Keep responses short and conversational. Don't use markdown formatting, asterisks, or bold text."""

    # Add conversation context if needed
    if conversation_memory and conversation_memory.get('total_exchanges', 0) > 0:
        base_prompt += f"""

CONVERSATION HISTORY:"""
        # Show last few exchanges for context
        for exchange in conversation_memory.get('conversation_history', [])[-2:]:  # Last 2 exchanges
            base_prompt += f"""
Human: {exchange['question']}
Assistant: {exchange['answer'][:150]}{'...' if len(exchange['answer']) > 150 else ''}"""
    
    # Note: Removed suggestion prompts - let examples guide the natural conversation style
    
    # Note: Keeping prompt simple - let multi-shot examples handle the responses

    base_prompt += f"""

YASH'S INFO:
- Core Identity: {profile['personal_info']['core_identity']}
- Current Role: {profile['current_position']['role']} at {profile['current_position']['company']} ({profile['current_position']['company_context']})
- Work Style: {profile['personal_info']['work_style']}
- Sweet Spot: {profile['personal_info']['sweet_spot']}
- Philosophy: {profile['personal_info']['philosophy']}
- Education: {profile['education']['current']['degree']} (CGPA: {profile['education']['current']['cgpa']})
- Key Skills: {', '.join(profile['technical_skills']['ai_ml'][:5])}, {', '.join(profile['technical_skills']['llm_platforms'][:3])}
- Main Projects: SwiftCheck AI (enterprise QC, Microsoft funding), ChargeOrFill (0β†’1 product validation), DocuTalk (document AI), FinLLM (compliance automation)
- Key Traits: Collaborative (not lone wolf), product-first thinking, experiment-first learner, progress beats perfection

User's question: "{question}"

Answer naturally following the style of the examples above."""
    
    return base_prompt

@app.route('/', methods=['GET'])
def home():
    """API status and info"""
    return jsonify({
        "status": "πŸš€ Yash Gori's AI Portfolio API is Live!",
        "developer": "Yash Gori - AI Engineer",
        "description": "Ask me anything about Yash's AI expertise, projects, and experience!",
        "endpoints": {
            "POST /ask": "Ask questions about Yash (send JSON with 'question' field, optional 'session_id')",
            "GET /profile": "Get Yash's complete profile information",
            "GET /session/{session_id}/state": "Get complete session state and conversation context",
            "GET /session/{session_id}/history": "Get detailed conversation history (optional ?limit=N)",
            "GET /admin/conversations": "View all visitor conversations (admin only)",
            "GET /admin/profiles": "View user profiles and analytics (admin only)"
        },
        "api_format": {
            "request": {"question": "your question", "session_id": "optional - will be generated if not provided"},
            "response": {
                "success": True, 
                "api_version": "2.0",
                "session": {
                    "session_id": "unique_session_id",
                    "conversation_number": "1-N",
                    "user_status": "new|returning"
                },
                "request": {
                    "question": "user question",
                    "processed_at": "timestamp"
                },
                "response": {
                    "answer": "AI response",
                    "model_used": "openai/gpt-oss-120b",
                    "confidence_indicators": {}
                },
                "intelligence": {
                    "user_analysis": {},
                    "conversation_state": {}
                },
                "engagement": {
                    "clarifying_questions": [],
                    "follow_up_suggestions": [],
                    "conversation_guidance": {}
                }
            }
        },
        "sample_questions": [
            "What makes Yash special as an AI developer?",
            "Tell me about his experience with RAG systems",
            "How did he achieve 94% accuracy in customer churn prediction?",
            "What's his experience with different LLM platforms?",
            "Can you explain his DocuTalk project?",
            "What business impact has he created?",
            "What's his current role and responsibilities?"
        ],
        "clarity_examples": {
            "unclear_questions": [
                "About Yash",
                "Tell me about him",
                "His work"
            ],
            "clear_questions": [
                "What are Yash's main technical skills?",
                "How did Yash implement the DocuTalk project?",
                "Are you hiring for an AI engineer role?"
            ],
            "note": "Unclear questions will receive clarifying questions to better understand your needs"
        },
        "engagement_features": {
            "follow_up_suggestions": {
                "description": "Each response includes 3-4 intelligent follow-up suggestions",
                "examples": {
                    "recruiter": ["What role level are you considering?", "What's your hiring timeline?"],
                    "technical": ["Want to dive deeper into the architecture?", "Are you working on similar projects?"],
                    "student": ["What skills do you want to develop next?", "Would learning resources be helpful?"]
                }
            },
            "conversation_continuity": "AI remembers your previous questions and builds on your interests",
            "personalized_suggestions": "Follow-ups adapt based on your detected type and sophistication level"
        },
        "conversation_memory": {
            "description": "AI maintains context across multiple exchanges within a session",
            "features": {
                "topic_tracking": "Remembers what topics have been discussed (projects, AI/ML, experience, etc.)",
                "context_building": "References previous conversations naturally",
                "progression_awareness": "Tracks how your interests and questions evolve",
                "duplicate_avoidance": "Avoids repeating previously covered information"
            },
            "example": "If you first ask about projects, then about AI experience, the AI will connect these topics and reference your previous interest in projects when discussing AI implementations"
        },
        "smart_suggestions": {
            "description": "AI analyzes conversation flow patterns to provide intelligent next-step suggestions",
            "categories": {
                "immediate_follow_ups": "Direct follow-up questions based on current topic",
                "topic_transitions": "Natural transitions to related topics",
                "depth_exploration": "Deeper dives based on user sophistication level",
                "meta_suggestions": "High-level conversation guidance and next steps"
            },
            "flow_analysis": {
                "progression": "exploring|deepening|focused - how user interest is evolving",
                "depth_trend": "broad|balanced|deep - topic coverage pattern",
                "engagement_pattern": "new|moderate|high - level of user engagement"
            },
            "example": "After asking about DocuTalk project, you might get immediate follow-ups about FAISS integration, topic transitions to other AI projects, or depth exploration about system architecture"
        },
        "rich_content_integration": {
            "description": "AI automatically detects project-specific questions and provides enhanced technical details",
            "features": {
                "project_detection": "Automatically identifies when specific projects (DocuTalk, Inhance, Finance Advisor, etc.) are mentioned",
                "contextual_details": "Provides relevant technical information based on question type (architecture, implementation, performance, links)",
                "comprehensive_data": "Includes GitHub repos, demo links, technical specifications, challenges solved, and implementation highlights"
            },
            "content_types": {
                "architecture": "System design, data flow, scalability details",
                "implementation": "Development highlights, challenges solved, technical approaches",
                "performance": "Metrics, accuracy rates, response times, scalability numbers",
                "links": "GitHub repositories, live demos, documentation"
            },
            "example_enhanced_response": {
                "question": "How did you implement DocuTalk?",
                "enhanced_content": {
                    "architecture": "Microservices architecture with Flutter frontend, Flask API backend, and FAISS vector database",
                    "implementation": ["Custom document preprocessing pipeline", "Optimized FAISS index configuration"],
                    "performance": "95% accuracy on 100+ page documents, sub-second query response times",
                    "links": {"github": "https://github.com/yashgori/docutalk", "demo": "https://docutalk-demo.streamlit.app"}
                }
            }
        }
    })

@app.route('/ask', methods=['POST'])
@rate_limit_decorator(limit=60, window=3600, per_session_limit=20)
def ask_question():
    """Main endpoint: Recruiters ask questions about Yash"""
    try:
        # Check if Groq client is available
        if not client:
            return jsonify({
                "error": "AI service temporarily unavailable",
                "fallback_answer": "Yash Gori is an exceptional AI Engineer actively seeking new opportunities. He specializes in RAG systems, multi-LLM integration, and has built impressive projects like DocuTalk and Finance Advisor Agent. Contact: [email protected]"
            }), 503
        
        data = request.get_json()
        
        if not data or 'question' not in data:
            return jsonify({
                "error": "Please provide a 'question' in JSON format",
                "example": {"question": "What makes Yash a great AI developer?"}
            }), 400
        
        question = data['question'].strip()
        if not question:
            return jsonify({"error": "Question cannot be empty"}), 400
            
        # Generate or get session ID
        session_id = data.get('session_id')
        if not session_id:
            session_id = str(uuid.uuid4())
            logger.info(f"New session created: {session_id}")
        
        # Get visitor IP
        visitor_ip = request.remote_addr or request.environ.get('HTTP_X_FORWARDED_FOR', 'unknown')
        
        # Get existing user profile and conversation memory
        existing_profile = get_user_profile(session_id)
        conversation_memory = get_conversation_memory(session_id, limit=5)
        
        # Analyze user sophistication level
        sophistication_level = analyze_user_sophistication(question, existing_profile)
        
        # Create intelligent agent prompt with context detection, user profile, and conversation memory
        prompt = create_intelligent_agent_prompt(question, YASH_PROFILE, session_id, existing_profile, conversation_memory)
        
        # Get AI response with error handling
        try:
            chat_completion = client.chat.completions.create(
                messages=[
                    {
                        'role': 'system',
                        'content': 'You\'re Yash Gori\'s personal AI assistant. Yash is an AI Product IC who bridges AI engineering with product thinking - builder-first, curious, hands-on. He owns problems end-to-end: understands user problems β†’ builds solutions β†’ ships products β†’ gathers feedback β†’ iterates. Use proper grammar and capitalize sentences, but keep responses SHORT and conversational. No long-winded explanations or marketing speak. Don\'t repeat project names after every reply. Reflect his philosophy: "If I don\'t know how something works, I\'ll learn it until I do." He\'s collaborative (not a lone wolf), product-first, and thrives in early-stage GenAI startups. Sound helpful and authentic, not like a salesperson or formal resume.'
                    },
                    {
                        'role': 'user',
                        'content': 'hey'
                    },
                    {
                        'role': 'assistant',
                        'content': 'Hey! I\'m Yash Gori\'s personal bot. Is there anything you\'d like to know about him?'
                    },
                    {
                        'role': 'user',
                        'content': 'tell me about his ai skills'
                    },
                    {
                        'role': 'assistant',
                        'content': 'He\'s pretty solid with the full AI stack. Works a lot with LangChain and RAG systems, building pipelines that connect vector databases to LLMs for smart document retrieval. Knows his way around FAISS, Pinecone, and Azure AI Search.\n\nComfortable with different LLM platforms like GPT-4, Mixtral, Gemini, and Groq. Does a lot of prompt engineering and knows how to chain things together. Also builds the actual products with Python, Flask, FastAPI on backend and Flutter for mobile.\n\nWhat area are you interested in?'
                    },
                    {
                        'role': 'user',
                        'content': 'what projects has he built?'
                    },
                    {
                        'role': 'assistant',
                        'content': 'He\'s built quite a few things. His main one is probably DocuTalk - it lets you chat with documents using AI, pretty handy for extracting info from PDFs without reading everything.\n\nThen there\'s Inhance for LinkedIn profile optimization, Swift Check AI for compliance automation, and a finance advisor that understands RBI regulations. Also did a customer churn predictor that hit 94% accuracy.\n\nThey\'re all full applications with actual UIs and backends, not just demos. Anything specific catch your interest?'
                    },
                    {
                        'role': 'user',
                        'content': prompt
                    }
                ],
                model="llama-3.3-70b-versatile",
                stream=False,
                temperature=0.7,
                max_tokens=1000
            )
        except Exception as groq_error:
            logger.error(f"Groq API error: {groq_error}")
            
            # Create a comprehensive fallback response based on the question
            question_lower = question.lower()
            
            if any(word in question_lower for word in ['skills', 'technical', 'technology', 'programming']):
                fallback_response = "Yash has strong technical skills in AI/ML, Python, Flask, RAG systems, and cloud platforms like Azure. He works with multiple LLM APIs including Groq, Gemini, and Mixtral. His expertise includes machine learning, deep learning, NLP, and full-stack development with frameworks like Streamlit and Gradio."
            elif any(word in question_lower for word in ['project', 'work', 'experience', 'built']):
                fallback_response = "Yash has built impressive projects including DocuTalk (conversational document AI), Finance Advisor Agent (RBI compliance), and Customer Churn Predictor with 94% accuracy. He's actively seeking AI/ML opportunities and has extensive experience with RAG-based systems, Flask, and Azure integration."
            elif any(word in question_lower for word in ['contact', 'reach', 'email', 'hire']):
                fallback_response = "You can contact Yash Gori at [email protected]. He's currently pursuing BTech in IT at KJ Somaiya College (CGPA: 8.12) and available for AI Engineer positions. He's passionate about building innovative AI solutions and contributing to cutting-edge projects."
            elif any(word in question_lower for word in ['education', 'study', 'college', 'degree']):
                fallback_response = "Yash is currently pursuing BTech in Information Technology at KJ Somaiya College of Engineering with a CGPA of 8.12. He has strong academic foundations in computer science, AI/ML, and software development, complemented by hands-on project experience."
            else:
                fallback_response = f"I'd be happy to tell you about Yash! He's actively seeking AI/ML opportunities and has extensive experience with RAG-based AI systems, Flask, and Azure integration. He has strong experience with multiple LLM platforms including Gemini, GROQ, Mixtral, and Gemma. His flagship projects include DocuTalk (conversational document AI), Finance Advisor Agent (RBI compliance), and Customer Churn Predictor (94% accuracy). Contact him at [email protected] for more details!"
            
            return jsonify({
                "success": True,
                "api_version": "2.0",
                "session": {
                    "session_id": session_id,
                    "conversation_number": 1,
                    "user_status": "new"
                },
                "request": {
                    "question": question,
                    "processed_at": datetime.now().isoformat()
                },
                "response": {
                    "answer": fallback_response,
                    "model_used": "fallback-mode",
                    "note": "AI service temporarily using fallback responses"
                },
                "intelligence": {
                    "user_analysis": {
                        "detected_type": "general",
                        "sophistication_level": "intermediate"
                    }
                },
                "timestamp": datetime.now().isoformat()
            }), 200
        
        ai_response = chat_completion.choices[0].message.content.strip()
        
        # Debug: Log the raw AI response for verification
        logger.info(f"[DEBUG] Raw AI Response for session {session_id}: {ai_response[:200]}...")
        
        # Detect user type and save conversation to database
        user_type = detect_user_intent(question)
        
        # Update user profile with new insights
        update_user_profile(session_id, question, user_type, sophistication_level)
        
        # Enhanced user info for database
        enhanced_user_info = {
            "detected_intent": user_type,
            "sophistication_level": sophistication_level,
            "returning_user": False,
            "conversation_number": existing_profile["conversation_count"] + 1 if existing_profile else 1,
            "primary_type": existing_profile["primary_type"] if existing_profile else user_type
        }
        
        save_conversation(
            session_id=session_id,
            question=question,
            answer=ai_response,
            user_type=user_type,
            user_info=enhanced_user_info,
            ip_address=visitor_ip
        )
        
        # Store in conversation context
        conversation_context.append({
            "session_id": session_id,
            "question": question,
            "answer": ai_response,
            "timestamp": datetime.now().isoformat()
        })
        
        # Keep only last 10 conversations to manage memory
        if len(conversation_context) > 10:
            conversation_context.pop(0)
        
        logger.info(f"Question processed for session {session_id}: {question[:50]}...")
        
        # Analyze question clarity for response metadata
        clarity_analysis = detect_question_clarity(question)
        clarifying_questions = generate_clarifying_questions(question, user_type, clarity_analysis, existing_profile)
        
        # Generate follow-up suggestions to continue conversation
        follow_up_suggestions = generate_follow_up_suggestions(
            question, ai_response, user_type, sophistication_level, existing_profile
        )
        
        # Generate smart suggestions based on conversation flow
        flow_analysis = analyze_conversation_flow(conversation_memory)
        smart_suggestions = generate_smart_suggestions(
            question, user_type, sophistication_level, conversation_memory, conversation_memory
        )
        
        # Detect and extract rich content for project-specific questions
        mentioned_projects = detect_project_mentions(question, YASH_PROFILE)
        rich_content_data = {}
        if mentioned_projects:
            for project_name in mentioned_projects[:2]:
                rich_content_data[project_name] = extract_rich_project_content(question, project_name, YASH_PROFILE)
        
        # Create enhanced response structure
        response_data = {
            "success": True,
            "api_version": "2.0",
            "session": {
                "session_id": session_id,
                "conversation_number": existing_profile['conversation_count'] + 1 if existing_profile else 1,
                "user_status": "returning" if existing_profile else "new",
                "session_created": existing_profile['first_interaction'][:19] if existing_profile else datetime.now().isoformat()[:19]
            },
            "request": {
                "question": question,
                "processed_at": datetime.now().isoformat(),
                "response_time_ms": None  # Will be calculated if needed
            },
            "response": {
                "answer": ai_response,
                "model_used": "openai/gpt-oss-120b",
                "confidence_indicators": {
                    "question_clarity": clarity_analysis['clarity_score'],
                    "user_type_confidence": 0.8 if user_type != 'general' else 0.5,
                    "response_relevance": 0.9  # Could be calculated based on content analysis
                }
            },
            "intelligence": {
                "user_analysis": {
                    "detected_type": user_type,
                    "sophistication_level": sophistication_level,
                    "question_clarity": clarity_analysis['reason'],
                    "is_returning_user": False,
                    "previous_topics": conversation_memory.get('conversation_themes', []) if conversation_memory else []
                },
                "conversation_state": {
                    "total_exchanges": conversation_memory.get('total_exchanges', 0) if conversation_memory else 0,
                    "main_themes": conversation_memory.get('conversation_themes', []) if conversation_memory else [],
                    "user_progression": conversation_memory.get('progression_pattern', [])[-3:] if conversation_memory else [],
                    "conversation_depth": "surface" if not conversation_memory or conversation_memory.get('total_exchanges', 0) < 2 else "moderate" if conversation_memory.get('total_exchanges', 0) < 5 else "deep"
                }
            },
            "engagement": {
                "clarifying_questions": clarifying_questions if clarity_analysis['is_unclear'] else [],
                "follow_up_suggestions": follow_up_suggestions,
                "smart_suggestions": {
                    "immediate_follow_ups": smart_suggestions.get('immediate_follow_ups', []),
                    "topic_transitions": smart_suggestions.get('topic_transitions', []),
                    "depth_exploration": smart_suggestions.get('depth_exploration', []),
                    "meta_suggestions": smart_suggestions.get('meta_suggestions', []),
                    "flow_analysis": flow_analysis
                },
                "conversation_guidance": {
                    "next_recommended_topics": get_recommended_topics(conversation_memory, user_type) if conversation_memory else [],
                    "engagement_level": "high" if len(follow_up_suggestions) > 2 else "moderate"
                }
            },
            "rich_content": {
                "mentioned_projects": mentioned_projects,
                "project_details": rich_content_data,
                "has_enhanced_content": len(rich_content_data) > 0,
                "content_type": "project_specific" if rich_content_data else "general"
            },
            "metadata": {
                "developer": "Yash Gori",
                "timestamp": datetime.now().isoformat(),
                "processing_notes": []
            }
        }
        
        # Debug: Log the final response structure
        logger.info(f"[DEBUG] Final API Response for session {session_id}: answer='{response_data['response']['answer'][:100]}...', user_type='{response_data['intelligence']['user_analysis']['detected_type']}', model='{response_data['response']['model_used']}'")
        
        return jsonify(response_data)
        
    except Exception as e:
        logger.error(f"Error processing question: {str(e)}")
        return jsonify({
            "success": False,
            "api_version": "2.0",
            "error": {
                "type": "processing_error",
                "message": "Sorry, I couldn't process your question right now. Please try again.",
                "code": "INTERNAL_ERROR",
                "details": str(e) if app.debug else "Internal processing error"
            },
            "session": {
                "session_id": session_id if 'session_id' in locals() else None,
                "request_preserved": True
            },
            "fallback": {
                "answer": "I'd be happy to tell you about Yash! He's actively seeking AI/ML opportunities and has extensive experience with RAG-based AI systems, Flask, and Azure integration. He has strong experience with multiple LLM platforms including Gemini, GROQ, Mixtral, and Gemma. His flagship projects include DocuTalk (conversational document AI), Finance Advisor Agent (RBI compliance), and Customer Churn Predictor (94% accuracy). Contact him at [email protected] for more details!",
                "suggested_action": "Try asking a more specific question about his skills, projects, or experience."
            },
            "timestamp": datetime.now().isoformat()
        }), 500

@app.route('/profile', methods=['GET'])
def get_profile():
    """Get Yash's complete profile data"""
    try:
        return jsonify({
            "success": True,
            "developer": YASH_PROFILE['personal_info']['name'],
            "profile": YASH_PROFILE,
            "summary": {
                "current_role": f"{YASH_PROFILE['current_position']['role']} at {YASH_PROFILE['current_position']['company']}",
                "education": f"{YASH_PROFILE['education']['current']['degree']} (CGPA: {YASH_PROFILE['education']['current']['cgpa']})",
                "key_skills": YASH_PROFILE['technical_skills']['ai_ml'][:5],
                "flagship_projects": len(YASH_PROFILE['flagship_projects']),
                "work_experience": len(YASH_PROFILE['work_experience'])
            },
            "timestamp": datetime.now().isoformat()
        })
    except Exception as e:
        logger.error(f"Error getting profile: {str(e)}")
        return jsonify({"error": "Could not retrieve profile data"}), 500

@app.route('/admin/conversations', methods=['GET'])
def get_conversations():
    """Admin endpoint to view all conversations"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT id, session_id, timestamp, user_type, question, answer, user_info, ip_address
            FROM visitors 
            ORDER BY timestamp DESC
        ''')
        
        conversations = []
        for row in cursor.fetchall():
            conversations.append({
                "id": row[0],
                "session_id": row[1],
                "timestamp": row[2],
                "user_type": row[3],
                "question": row[4],
                "answer": row[5],
                "user_info": json.loads(row[6]) if row[6] else None,
                "ip_address": row[7]
            })
        
        conn.close()
        
        return jsonify({
            "success": True,
            "total_conversations": len(conversations),
            "conversations": conversations,
            "timestamp": datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error retrieving conversations: {str(e)}")
        return jsonify({"error": "Could not retrieve conversations"}), 500

@app.route('/admin/profiles', methods=['GET'])
def get_user_profiles():
    """Admin endpoint to view user profiles and analytics"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # Get all user profiles
        cursor.execute('''
            SELECT session_id, primary_type, sophistication_level, conversation_count, 
                   first_seen, last_seen, profile_data
            FROM user_profiles 
            ORDER BY conversation_count DESC, last_seen DESC
        ''')
        
        profiles = []
        for row in cursor.fetchall():
            profiles.append({
                "session_id": row[0],
                "primary_type": row[1],
                "sophistication_level": row[2],
                "conversation_count": row[3],
                "first_seen": row[4],
                "last_seen": row[5],
                "profile_data": json.loads(row[6]) if row[6] else None
            })
        
        # Get analytics
        cursor.execute('SELECT primary_type, COUNT(*) FROM user_profiles GROUP BY primary_type')
        type_stats = {row[0]: row[1] for row in cursor.fetchall()}
        
        cursor.execute('SELECT sophistication_level, COUNT(*) FROM user_profiles GROUP BY sophistication_level')
        skill_stats = {row[0]: row[1] for row in cursor.fetchall()}
        
        conn.close()
        
        return jsonify({
            "success": True,
            "total_unique_visitors": len(profiles),
            "profiles": profiles,
            "analytics": {
                "user_types": type_stats,
                "skill_levels": skill_stats,
                "most_engaged": profiles[:5] if profiles else []
            },
            "timestamp": datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error retrieving user profiles: {str(e)}")
        return jsonify({"error": "Could not retrieve user profiles"}), 500

@app.route('/session/<session_id>/state', methods=['GET'])
def get_session_state(session_id):
    """Get complete session state and conversation context"""
    try:
        # Get user profile and conversation memory
        user_profile = get_user_profile(session_id)
        conversation_memory = get_conversation_memory(session_id, limit=10)
        
        if not user_profile and not conversation_memory:
            return jsonify({
                "error": "Session not found",
                "session_id": session_id,
                "exists": False
            }), 404
        
        # Create comprehensive session state
        session_state = {
            "success": True,
            "session_id": session_id,
            "session_exists": True,
            "profile": {
                "conversation_count": user_profile['conversation_count'] if user_profile else 0,
                "primary_type": user_profile.get('primary_type', 'unknown') if user_profile else 'unknown',
                "interests": user_profile.get('interests', []) if user_profile else [],
                "first_interaction": user_profile.get('first_interaction') if user_profile else None,
                "last_interaction": user_profile.get('last_interaction') if user_profile else None
            },
            "conversation_memory": {
                "total_exchanges": conversation_memory.get('total_exchanges', 0) if conversation_memory else 0,
                "main_themes": conversation_memory.get('conversation_themes', []) if conversation_memory else [],
                "recent_topics": conversation_memory.get('mentioned_topics', []) if conversation_memory else [],
                "user_progression": conversation_memory.get('progression_pattern', []) if conversation_memory else [],
                "conversation_depth": "surface" if not conversation_memory or conversation_memory.get('total_exchanges', 0) < 2 else "moderate" if conversation_memory.get('total_exchanges', 0) < 5 else "deep"
            },
            "recommended_actions": {
                "next_topics": get_recommended_topics(conversation_memory, user_profile.get('primary_type', 'general') if user_profile else 'general'),
                "conversation_suggestions": [
                    "Continue exploring topics of interest",
                    "Ask more specific questions for detailed responses",
                    "Inquire about aspects not yet discussed"
                ] if conversation_memory and conversation_memory.get('total_exchanges', 0) > 0 else [
                    "Start by asking about Yash's background",
                    "Inquire about specific projects or skills",
                    "Ask about his current work or experience"
                ]
            },
            "timestamp": datetime.now().isoformat()
        }
        
        return jsonify(session_state)
        
    except Exception as e:
        logger.error(f"Error retrieving session state: {str(e)}")
        return jsonify({
            "error": "Could not retrieve session state",
            "session_id": session_id
        }), 500

@app.route('/session/<session_id>/history', methods=['GET'])
def get_session_history(session_id):
    """Get detailed conversation history for a session"""
    try:
        limit = request.args.get('limit', 10, type=int)
        conversation_memory = get_conversation_memory(session_id, limit=min(limit, 50))
        
        if not conversation_memory:
            return jsonify({
                "error": "No conversation history found",
                "session_id": session_id
            }), 404
        
        # Format conversation history
        formatted_history = {
            "success": True,
            "session_id": session_id,
            "total_exchanges": conversation_memory['total_exchanges'],
            "returned_exchanges": len(conversation_memory['conversation_history']),
            "conversation_themes": conversation_memory['conversation_themes'],
            "exchanges": []
        }
        
        for exchange in conversation_memory['conversation_history']:
            formatted_history["exchanges"].append({
                "exchange_number": exchange['exchange_number'],
                "timestamp": exchange['timestamp'],
                "user_type": exchange['user_type'],
                "question": exchange['question'],
                "answer": exchange['answer'],
                "topics_discussed": exchange['topics_discussed']
            })
        
        return jsonify(formatted_history)
        
    except Exception as e:
        logger.error(f"Error retrieving session history: {str(e)}")
        return jsonify({
            "error": "Could not retrieve session history",
            "session_id": session_id
        }), 500

@app.route('/analytics/dashboard', methods=['GET'])
def analytics_dashboard():
    """Comprehensive analytics dashboard for Yash to see all visitor insights"""
    try:
        analytics_data = get_visitor_analytics()
        
        if "error" in analytics_data:
            return jsonify(analytics_data), 500
            
        # Add additional dashboard-specific metrics
        dashboard_data = {
            "success": True,
            "dashboard_title": "Yash Gori's AI Portfolio Analytics Dashboard",
            "generated_at": datetime.now().isoformat(),
            **analytics_data,
            "summary_insights": {
                "total_visitors": analytics_data["overview"]["unique_visitors"],
                "total_interactions": analytics_data["overview"]["total_conversations"],
                "engagement_rate": round(
                    analytics_data["overview"]["total_conversations"] / max(analytics_data["overview"]["unique_visitors"], 1), 2
                ),
                "top_user_type": max(analytics_data["user_types"], key=analytics_data["user_types"].get) if analytics_data["user_types"] else "unknown",
                "peak_activity_hour": max(
                    analytics_data["temporal_analysis"]["hourly_distribution"], 
                    key=analytics_data["temporal_analysis"]["hourly_distribution"].get,
                    default="unknown"
                ) if analytics_data["temporal_analysis"]["hourly_distribution"] else "unknown"
            }
        }
        
        return jsonify(dashboard_data)
        
    except Exception as e:
        logger.error(f"Error generating analytics dashboard: {e}")
        return jsonify({"error": "Could not generate analytics dashboard"}), 500

@app.route('/analytics/session/<session_id>', methods=['GET'])
def get_session_analytics(session_id):
    """Get detailed analytics for a specific session"""
    try:
        session_insights = get_session_insights(session_id)
        
        if "error" in session_insights:
            return jsonify(session_insights), 404 if session_insights["error"] == "Session not found" else 500
        
        return jsonify({
            "success": True,
            "requested_at": datetime.now().isoformat(),
            **session_insights
        })
        
    except Exception as e:
        logger.error(f"Error getting session analytics for {session_id}: {e}")
        return jsonify({"error": "Could not retrieve session analytics"}), 500

@app.route('/analytics/daily', methods=['GET'])
def get_daily_analytics():
    """Get daily analytics summary"""
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # Get daily analytics for the past 30 days
        cursor.execute('''
            SELECT date, total_conversations, unique_sessions, user_type_breakdown, 
                   avg_conversation_length, top_questions, updated_at
            FROM daily_analytics 
            ORDER BY date DESC 
            LIMIT 30
        ''')
        
        daily_data = []
        for row in cursor.fetchall():
            date, total_convs, unique_sessions, user_types_str, avg_length, top_questions_str, updated = row
            daily_data.append({
                "date": date,
                "total_conversations": total_convs,
                "unique_sessions": unique_sessions,
                "user_type_breakdown": json.loads(user_types_str) if user_types_str else {},
                "avg_conversation_length": avg_length,
                "top_questions": json.loads(top_questions_str) if top_questions_str else [],
                "updated_at": updated
            })
        
        conn.close()
        
        # Calculate trends
        trends = {}
        if len(daily_data) >= 2:
            today = daily_data[0] if daily_data else {}
            yesterday = daily_data[1] if len(daily_data) > 1 else {}
            
            trends = {
                "conversation_trend": today.get("total_conversations", 0) - yesterday.get("total_conversations", 0),
                "session_trend": today.get("unique_sessions", 0) - yesterday.get("unique_sessions", 0),
                "avg_length_trend": today.get("avg_conversation_length", 0) - yesterday.get("avg_conversation_length", 0)
            }
        
        return jsonify({
            "success": True,
            "daily_analytics": daily_data,
            "trends": trends,
            "period_summary": {
                "days_analyzed": len(daily_data),
                "total_conversations": sum(day.get("total_conversations", 0) for day in daily_data),
                "total_sessions": sum(day.get("unique_sessions", 0) for day in daily_data)
            },
            "retrieved_at": datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"Error getting daily analytics: {e}")
        return jsonify({"error": "Could not retrieve daily analytics"}), 500

@app.route('/analytics/export', methods=['GET'])
def export_analytics():
    """Export comprehensive analytics data for external analysis"""
    try:
        # Get all analytics data
        full_analytics = get_visitor_analytics()
        
        if "error" in full_analytics:
            return jsonify(full_analytics), 500
        
        # Get daily analytics
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # Export conversation data
        cursor.execute('''
            SELECT session_id, timestamp, user_type, question, answer, user_info, ip_address
            FROM visitors 
            ORDER BY timestamp DESC
        ''')
        
        conversations_export = []
        for row in cursor.fetchall():
            session_id, timestamp, user_type, question, answer, user_info_str, ip = row
            user_info = json.loads(user_info_str) if user_info_str else {}
            
            conversations_export.append({
                "session_id": session_id,
                "timestamp": timestamp,
                "user_type": user_type,
                "question": question,
                "answer_length": len(answer),
                "sophistication_level": user_info.get("sophistication_level", "unknown"),
                "conversation_number": user_info.get("conversation_number", 1),
                "returning_user": False,
                "ip_address": ip[:8] + "..." if ip else None  # Partial IP for privacy
            })
        
        conn.close()
        
        export_data = {
            "success": True,
            "export_metadata": {
                "generated_at": datetime.now().isoformat(),
                "total_records": len(conversations_export),
                "analytics_version": "2.0",
                "privacy_note": "IP addresses are partially masked for privacy"
            },
            "full_analytics": full_analytics,
            "conversation_records": conversations_export
        }
        
        return jsonify(export_data)
        
    except Exception as e:
        logger.error(f"Error exporting analytics: {e}")
        return jsonify({"error": "Could not export analytics data"}), 500

@app.errorhandler(404)
def not_found(error):
    return jsonify({
        "error": "Endpoint not found",
        "available": {
            "POST /ask": "Ask questions about Yash",
            "GET /profile": "Get complete profile",
            "GET /analytics/dashboard": "Comprehensive analytics dashboard",
            "GET /analytics/session/<session_id>": "Session-specific insights",
            "GET /analytics/daily": "Daily analytics trends",
            "GET /analytics/export": "Export all analytics data",
            "GET /": "API information"
        }
    }), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({"error": "Internal server error"}), 500

def background_cleanup_scheduler():
    """Background thread to periodically clean up sessions and rate limits"""
    while True:
        try:
            # Cleanup session manager
            session_manager._cleanup_old_sessions()
            
            # Sleep for 10 minutes before next cleanup
            time.sleep(600)
        except Exception as e:
            logger.error(f"Background cleanup error: {e}")
            time.sleep(300)  # Wait 5 minutes before retrying on error

if __name__ == '__main__':
    print("πŸš€ Starting Yash Gori's AI Portfolio API...")
    print("πŸ“§ Contact: [email protected]")
    print("πŸ’Ό Current Status: Actively seeking AI/ML opportunities")
    print("πŸŽ“ Education: BTech IT, KJ Somaiya College (CGPA: 8.12)")
    print("πŸ”§ Ready to answer recruiter questions!")
    
    # Start background cleanup thread
    cleanup_thread = threading.Thread(target=background_cleanup_scheduler, daemon=True)
    cleanup_thread.start()
    print("✨ Background session cleanup activated")
    
    # Use environment port for HF Spaces compatibility
    port = int(os.environ.get("PORT", 7860))
    app.run(host='0.0.0.0', port=port, debug=False)