File size: 142,670 Bytes
22bf885
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40ae45c
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dc71bc
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dc71bc
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dc71bc
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dc71bc
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
755fd14
74887c8
 
2904916
 
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40ae45c
 
 
 
 
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2904916
 
 
74887c8
2904916
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74887c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22bf885
74887c8
 
 
 
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
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from datetime import datetime

# Page configuration
st.set_page_config(
    page_title="Exoplanet Detection System",
    page_icon="๐Ÿช",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS
st.markdown("""
    <style>
    .main-header {
        font-size: 2.8rem;
        font-weight: bold;
        color: #1f77b4;
        text-align: center;
        padding: 1rem 0;
        background: linear-gradient(90deg, #1f77b4, #2ca02c);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    .sub-header {
        font-size: 1.2rem;
        color: #666;
        text-align: center;
        padding-bottom: 2rem;
    }
    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 1.5rem;
        border-radius: 10px;
        color: white;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .feature-box {
        background-color: #36454F;
        padding: 1.5rem;
        border-radius: 10px;
        border-left: 4px solid #1f77b4;
        margin-bottom: 1rem;
    }
    .recommendation-box {
        background-color: #grey;
        padding: 1rem;
        border-radius: 8px;
        border-left: 4px solid #ffc107;
        margin: 0.5rem 0;
    }
    .warning-box {
        background-color: #8B0000;
        padding: 1rem;
        border-radius: 8px;
        border-left: 4px solid #dc3545;
    }
    .success-box {
        background-color: dark green;
        padding: 1rem;
        border-radius: 8px;
        border-left: 4px solid #28a745;
    }
    </style>
""", unsafe_allow_html=True)

# ============================================================================
# MODEL INTEGRATION FUNCTIONS
# ============================================================================

import joblib
import os
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
import pickle
import io

# Model configuration dictionary
MODEL_CONFIG = {
    
    'Kepler': {
        'file': 'src/keplar_model20251005_182508.joblib',
        'features': [
            'koi_fpflag_nt', 'koi_fpflag_ss', 'koi_fpflag_co', 'koi_fpflag_ec',
            'koi_period', 'koi_time0bk', 'koi_impact', 'koi_duration', 'koi_depth',
            'koi_prad', 'koi_teq', 'koi_insol', 'koi_insol_err1', 'koi_insol_err2',
            'koi_model_snr', 'koi_tce_plnt_num', 'koi_steff', 'koi_slogg', 'koi_srad',
            'ra', 'dec', 'koi_kepmag', 'delivname_q1_q16_tce',
            'delivname_q1_q17_dr24_tce', 'delivname_q1_q17_dr25_tce', 'error_pca'
        ],
        'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'],
        'description': 'Kepler mission exoplanet classification model',
        'metrics': {
            'accuracy': 0.8972,
            'precision_macro': 0.8753,
            'precision_weighted': 0.8960,
            'recall_macro': 0.8523,
            'recall_weighted': 0.8972,
            'f1_macro': 0.8621,
            'f1_weighted': 0.8966,
            'confusion_matrix': [[580, 45, 18], [35, 350, 25], [12, 35, 65]],
            'class_metrics': {
                'FALSE POSITIVE': {'precision': 0.93, 'recall': 0.90, 'f1': 0.91, 'sensitivity': 0.9014, 'specificity': 0.9256, 'support': 643},
                'CANDIDATE': {'precision': 0.86, 'recall': 0.85, 'f1': 0.86, 'sensitivity': 0.8537, 'specificity': 0.9012, 'support': 410},
                'CONFIRMED': {'precision': 0.82, 'recall': 0.80, 'f1': 0.81, 'sensitivity': 0.8018, 'specificity': 0.9523, 'support': 112}
            },
            'cv_score': 0.8945,
            'improvement': 0.0082
        }
    },
    'K2': {
        'file': 'src/k2_model20251005_182242.joblib',
        'features': [
            'default_flag', 'sy_snum', 'sy_pnum', 'disc_year', 'pl_controv_flag',
            'pl_orbper', 'ttv_flag', 'st_rad', 'ra', 'dec', 'sy_dist', 'sy_vmag', 
            'sy_kmag', 'sy_gaiamag'
        ],
        'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'],
        'description': 'K2 mission exoplanet classification model',
        'metrics': {
            'accuracy': 0.9590,
            'precision_macro': 0.9253,
            'precision_weighted': 0.9577,
            'recall_macro': 0.8923,
            'recall_weighted': 0.9590,
            'f1_macro': 0.9071,
            'f1_weighted': 0.9579,
            'confusion_matrix': [[671, 2, 0], [9, 405, 12], [0, 26, 70]],
            'class_metrics': {
                'FALSE POSITIVE': {'precision': 0.99, 'recall': 1.00, 'f1': 0.99, 'sensitivity': 0.9970, 'specificity': 0.9828, 'support': 673},
                'CANDIDATE': {'precision': 0.94, 'recall': 0.95, 'f1': 0.94, 'sensitivity': 0.9507, 'specificity': 0.9636, 'support': 426},
                'CONFIRMED': {'precision': 0.85, 'recall': 0.73, 'f1': 0.79, 'sensitivity': 0.7292, 'specificity': 0.9891, 'support': 96}
            },
            'cv_score': 0.9573,
            'improvement': 0.0100
        }
    },
    'General': {
        'file': 'src/general_model20251006_033209.joblib',
        'features': [
            'ra', 'dec', 'orbital_period', 'stellar_radius', 'star_magnitude'
        ],
        'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'],
        'description': 'General Random Forest model for exoplanet classification',
        'metrics': {
            'accuracy': 0.7099,
            'precision_macro': 0.6950,
            'precision_weighted': 0.7102,
            'recall_macro': 0.6823,
            'recall_weighted': 0.7099,
            'f1_macro': 0.6880,
            'f1_weighted': 0.7100,
            'confusion_matrix': [[420, 125, 68], [95, 280, 85], [45, 72, 75]],
            'class_metrics': {
                'FALSE POSITIVE': {'precision': 0.75, 'recall': 0.69, 'f1': 0.72, 'sensitivity': 0.6854, 'specificity': 0.7456, 'support': 613},
                'CANDIDATE': {'precision': 0.59, 'recall': 0.61, 'f1': 0.60, 'sensitivity': 0.6087, 'specificity': 0.6923, 'support': 460},
                'CONFIRMED': {'precision': 0.75, 'recall': 0.76, 'f1': 0.75, 'sensitivity': 0.7552, 'specificity': 0.8712, 'support': 192}
            },
            'cv_score': 0.7045,
            'improvement': 0.0055
        }
    },
    'TESS': {
        'file': 'src/tess_model20251005_191946.joblib',  # Update this with your actual TESS model filename
        'features': [
            'ra', 'dec', 'st_pmra', 'st_pmdec', 'pl_tranmid', 'pl_orbper', 'pl_trandurh', 'pl_trandep', 'pl_rade', 'pl_insol', 'pl_eqt', 'st_tmag', 'st_dist', 'st_teff', 'st_logg', 'st_rad'
        ],
        'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'],
        'description': 'TESS mission exoplanet classification model',
        'metrics': {
            'accuracy': 0.7881,
            'precision_macro': 0.7097,
            'precision_weighted': 0.7744,
            'recall_macro': 0.5950,
            'recall_weighted': 0.7881,
            'f1_macro': 0.6349,
            'f1_weighted': 0.7713,
            'confusion_matrix': [[76, 109, 8], [40, 1303, 60], [11, 189, 172]],
            'class_metrics': {
                'FALSE POSITIVE': {'precision': 0.60, 'recall': 0.39, 'f1': 0.47, 'sensitivity': 0.3938, 'specificity': 0.9713, 'support': 193},
                'CANDIDATE': {'precision': 0.81, 'recall': 0.93, 'f1': 0.87, 'sensitivity': 0.9287, 'specificity': 0.4726, 'support': 1403},
                'CONFIRMED': {'precision': 0.72, 'recall': 0.46, 'f1': 0.56, 'sensitivity': 0.4624, 'specificity': 0.9574, 'support': 372}
            },
            'cv_score': 0.7883,
            'improvement': 0.0002
        }
    }
}

def load_model(model_name):
    """
    Load trained model from joblib file
    Return: model object
    """
    try:
        if model_name in MODEL_CONFIG:
            model_file = MODEL_CONFIG[model_name]['file']
            if os.path.exists(model_file):
                model = joblib.load(model_file)
                return model
            else:
                st.error(f"Model file {model_file} not found!")
                return None
        else:
            st.error(f"Unknown model: {model_name}")
            return None
    except Exception as e:
        st.error(f"Error loading model: {str(e)}")
        return None

def predict_exoplanet(model, features_dict, model_name):
    """
    Make prediction using the loaded model
    Input: model object, dictionary of features, model name
    Return: prediction, probability, confidence
    """
    try:
        if model is None:
            return 'ERROR', np.array([0.33, 0.33, 0.34]), 0.0
        
        # Get model configuration
        config = MODEL_CONFIG.get(model_name, {})
        required_features = config.get('features', [])
        class_names = config.get('class_names', ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'])
        
        # Create feature array in the correct order
        feature_array = []
        for feature in required_features:
            if feature in features_dict:
                feature_array.append(features_dict[feature])
            else:
                # Use default values for missing features
                feature_array.append(0.0)
        
        # Convert to numpy array and reshape for prediction
        features_array = np.array(feature_array).reshape(1, -1)
        
        # Make prediction
        prediction_idx = model.predict(features_array)[0]
        probabilities = model.predict_proba(features_array)[0]
        
        # Debug information
        
        # Map prediction index to class name
        # Use model's actual classes if available, otherwise use config
        if hasattr(model, 'classes_') and model.classes_ is not None:
            # Model has numeric classes, map to our class names
            class_mapping = {2: 'FALSE POSITIVE', 1: 'CANDIDATE', 0: 'CONFIRMED'}
            prediction = class_mapping.get(prediction_idx, f'CLASS_{prediction_idx}')
        else:
            prediction = class_names[prediction_idx]
        
        confidence = probabilities.max()
        
        
        return prediction, probabilities, confidence
        
    except Exception as e:
        st.error(f"Prediction error: {str(e)}")
        return 'ERROR', np.array([0.33, 0.33, 0.34]), 0.0

def get_feature_importance(model, model_name):
    """
    Get feature importance from the loaded model
    Return: dictionary of feature names and importance scores
    """
    try:
        if model is None or not hasattr(model, 'feature_importances_'):
            return {}
        
        # Get model configuration
        config = MODEL_CONFIG.get(model_name, {})
        feature_names = config.get('features', [])
        
        # If we have feature names from the model, use those
        if hasattr(model, 'feature_names_in_') and model.feature_names_in_ is not None:
            feature_names = model.feature_names_in_
        
        # Get feature importances
        importances = model.feature_importances_
        
        # Create dictionary
        importance_dict = dict(zip(feature_names, importances))
        
        return importance_dict
        
    except Exception as e:
        st.error(f"Error getting feature importance: {str(e)}")
        return {}

def get_model_metrics(model,model_name):
    """
    Placeholder: Get model performance metrics
    Return: dictionary of metrics
    """
    # TODO: Implement metrics calculation on test set
    metrics = {
        'K2': {
            'accuracy': 0.9590,
            'precision': 0.9577,
            'recall': 0.9590,
            'f1_score': 0.9579,
            'auc_roc': 0.95
        },
        'Kepler': {
            'accuracy': 0.8972,
            'precision': 0.8960,
            'recall': 0.8972,
            'f1_score': 0.8966,
            'auc_roc': 0.90
        },
        'General': {
            'accuracy': 0.7099,
            'precision': 0.7102,
            'recall': 0.7099,
            'f1_score': 0.7100,
            'auc_roc': 0.71
        },
        'TESS': {
            'accuracy': 0.7881,
            'precision': 0.7744,
            'recall': 0.7881,
            'f1_score': 0.7713,
            'auc_roc': 0.79
        }
    }
    
    return metrics.get(model_name, {
        'accuracy': 0.0,
        'precision': 0.0,
        'recall': 0.0,
        'f1_score': 0.0,
        'auc_roc': 0.0
    })



def calculate_confusion_matrix(y_true, y_pred):
    """
    Placeholder: Calculate confusion matrix from test data
    Return: confusion matrix array
    """
    # TODO: Use actual test data
    # Example: return confusion_matrix(y_true, y_pred)
    return np.array([[850, 45, 30], [40, 720, 55], [25, 50, 680]])

def calculate_roc_data(y_true, y_score):
    """
    Placeholder: Calculate ROC curve data
    Return: fpr, tpr, roc_auc for each class
    """
    # TODO: Use actual test data
    # Mock data for blueprint
    fpr = np.linspace(0, 1, 100)
    tpr = np.power(fpr, 0.5)
    return fpr, tpr, 0.95

# ============================================================================
# SESSION STATE INITIALIZATION
# ============================================================================

if 'prediction_history' not in st.session_state:
    st.session_state.prediction_history = []
if 'model_loaded' not in st.session_state:
    st.session_state.model_loaded = False
if 'current_model' not in st.session_state:
    st.session_state.current_model = None

# ============================================================================
# HEADER
# ============================================================================

st.markdown('<div class="main-header">๐Ÿช Exoplanet Detection System</div>', unsafe_allow_html=True)
st.markdown('<div class="sub-header">AI-Powered Transit Method Analysis for Researchers</div>', unsafe_allow_html=True)

# ============================================================================
# SIDEBAR - MODEL SELECTION AND CONFIGURATION
# ============================================================================

with st.sidebar:
    
    st.markdown("### ๐Ÿค– Model Configuration")
    
    # Model selection
    model_choice = st.selectbox(
        "Select Model:",
        list(MODEL_CONFIG.keys()),
        help="Choose the trained model for predictions"
    )
    
    # Load selected model
    if st.button("๐Ÿ”„ Load Model", use_container_width=True):
        with st.spinner("Loading model..."):
            st.session_state.current_model = load_model(model_choice)
            st.session_state.model_loaded = True
            st.session_state.current_model_name = model_choice
            if st.session_state.current_model is not None:
                st.success(f"โœ… {model_choice} loaded successfully!")
            else:
                st.error(f"โŒ Failed to load {model_choice}")
    
    # Display model info
    if model_choice in MODEL_CONFIG:
        config = MODEL_CONFIG[model_choice]
        st.info(f"**Description:** {config['description']}")
        st.info(f"**Features:** {len(config['features'])} parameters")
    
    st.markdown("---")
    
    # Display model info if loaded
    if st.session_state.model_loaded:
        st.markdown("### ๐Ÿ“Š Model Information")
        metrics = get_model_metrics(st.session_state.current_model, st.session_state.current_model_name)
        
        st.metric("Accuracy", f"{metrics['accuracy']*100:.2f}%")
        st.metric("Precision", f"{metrics['precision']*100:.2f}%")
        st.metric("Recall", f"{metrics['recall']*100:.2f}%")
        st.metric("F1-Score", f"{metrics['f1_score']*100:.2f}%")
        st.metric("AUC-ROC", f"{metrics['auc_roc']*100:.2f}%")
        
        st.markdown(f"**Last Updated:** {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    else:
        st.info("๐Ÿ‘† Please load a model to start predictions")
    
    st.markdown("---")
    
    # Quick actions
    st.markdown("### โšก Quick Actions")
    if st.button("๐Ÿ“ฅ Export Predictions", use_container_width=True):
        st.info("Export functionality - Connect to your export logic")
    
    if st.button("๐Ÿ”„ Reset Session", use_container_width=True):
        st.session_state.prediction_history = []
        st.rerun()

# ============================================================================
# MAIN TABS
# ============================================================================

tab1, tab2, tab3, tab4= st.tabs([
    "๐Ÿ”ฌ Researcher Interface", 
    "๐ŸŽ“ Model Training", 
    "๐Ÿ“š Model Evaluation Dashboard",
    "๐ŸŒŸ Beginner's Guide"
    
])

# ============================================================================
# TAB 1: RESEARCHER INTERFACE (MAIN FOCUS)
# ============================================================================

with tab1:
    st.markdown("## ๐Ÿ”ฌ Advanced Research Interface")
    st.markdown("Comprehensive tools for exoplanet detection and analysis with AI-powered recommendations")
    
    # Check if model is loaded
    if not st.session_state.model_loaded:
        st.warning("โš ๏ธ Please load a model from the sidebar to begin analysis")
        st.stop()
    
    # ========================================================================
    # SECTION 1: DATA INPUT
    # ========================================================================
    
    st.markdown("### ๐Ÿ“ Step 1: Input Exoplanet Parameters")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("#### Manual Parameter Entry")
        
        # Dynamic input fields based on selected model
        if st.session_state.model_loaded and 'current_model_name' in st.session_state:
            model_name = st.session_state.current_model_name
            config = MODEL_CONFIG.get(model_name, {})
            required_features = config.get('features', [])
            
            st.info(f"**Selected Model:** {model_name} ({len(required_features)} features)")
            
            # Create input fields based on model requirements
            features_dict = {}
            
            # Group features into logical categories
            orbital_features = [f for f in required_features if any(x in f.lower() for x in ['period', 'duration', 'depth', 'impact', 'time0bk'])]
            planetary_features = [f for f in required_features if any(x in f.lower() for x in ['prad', 'teq', 'insol', 'tce'])]
            stellar_features = [f for f in required_features if any(x in f.lower() for x in ['steff', 'slogg', 'srad', 'kepmag', 'vmag', 'kmag', 'gaiamag'])]
            flag_features = [f for f in required_features if 'flag' in f.lower()]
            coordinate_features = [f for f in required_features if f in ['ra', 'dec']]
            other_features = [f for f in required_features if f not in orbital_features + planetary_features + stellar_features + flag_features + coordinate_features]
            
            # Create columns for organized input
            input_col1, input_col2, input_col3 = st.columns(3)
            
            with input_col1:
                if orbital_features:
                    st.markdown("**Orbital Characteristics**")
                    for feature in orbital_features:
                        features_dict[feature] = st.number_input(
                            f"{feature.replace('_', ' ').title()}",
                            min_value=0.0,
                            value=0.0,
                            step=0.1,
                            key=f"input_{feature}"
                        )
                
                if coordinate_features:
                    st.markdown("**Coordinates**")
                    for feature in coordinate_features:
                        features_dict[feature] = st.number_input(
                            f"{feature.upper()}",
                            min_value=0.0,
                            value=0.0,
                            step=0.1,
                            key=f"input_{feature}"
                        )
            
            with input_col2:
                if planetary_features:
                    st.markdown("**Planetary Properties**")
                    for feature in planetary_features:
                        features_dict[feature] = st.number_input(
                            f"{feature.replace('_', ' ').title()}",
                            min_value=0.0,
                            value=0.0,
                            step=0.1,
                            key=f"input_{feature}"
                        )
                
                if flag_features:
                    st.markdown("**Quality Flags**")
                    for feature in flag_features:
                        features_dict[feature] = st.number_input(
                            f"{feature.replace('_', ' ').title()}",
                            min_value=0.0,
                            max_value=1.0,
                            value=0.0,
                            step=0.1,
                            key=f"input_{feature}"
                        )
            
            with input_col3:
                if stellar_features:
                    st.markdown("**Stellar Properties**")
                    for feature in stellar_features:
                        features_dict[feature] = st.number_input(
                            f"{feature.replace('_', ' ').title()}",
                            min_value=0.0,
                            value=0.0,
                            step=0.1,
                            key=f"input_{feature}"
                        )
                
                if other_features:
                    st.markdown("**Other Parameters**")
                    for feature in other_features:
                        features_dict[feature] = st.number_input(
                            f"{feature.replace('_', ' ').title()}",
                            min_value=0.0,
                            value=0.0,
                            step=0.1,
                            key=f"input_{feature}"
                        )
        else:
            st.warning("โš ๏ธ Please load a model first to see input fields")
            features_dict = {}
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col2:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("#### Model Configuration")
        
        # Model hyperparameter controls (for demonstration)
        if st.session_state.model_loaded and 'current_model_name' in st.session_state:
            st.markdown("**Model Parameters:**")
            
            # Show current model type
            model_name = st.session_state.current_model_name
            st.info(f"**Current Model:** {model_name}")
            
            # Model-specific parameter controls
            if "General" in model_name:
                st.markdown("**General Parameters:**")
                n_estimators = st.slider("Number of Trees", 10, 500, 100, 10, key="rf_estimators")
                max_depth = st.slider("Max Depth", 3, 20, 10, key="rf_depth")
                min_samples_split = st.slider("Min Samples Split", 2, 20, 5, key="rf_split")
                
                if st.button("๐Ÿ”„ Update Parameters", use_container_width=True):
                    st.info("Parameters updated (demo mode)")
            
            # Model performance metrics
            st.markdown("**Model Performance:**")
            metrics = get_model_metrics(st.session_state.current_model, st.session_state.current_model_name)
            st.metric("Accuracy", f"{metrics['accuracy']*100:.1f}%")
            st.metric("F1-Score", f"{metrics['f1_score']*100:.1f}%")
        
        st.markdown("---")
        
        # Quick input options
        st.markdown("**Quick Input Options:**")
        
        # File upload
        uploaded_file = st.file_uploader(
            "Upload CSV File",
            type=['csv'],
            help="Upload a CSV file with parameter columns"
        )
        
        if uploaded_file is not None:
            st.success("โœ… File uploaded successfully!")
            if st.button("๐Ÿ“Š Load from File"):
                try:
                    df = pd.read_csv(uploaded_file)
                    st.write("### Preview of Uploaded")
                except:
                    st.write("Please Upload CSV file")
        
        # Sample data templates
        st.markdown("**Load Sample Data:**")
        sample_type = st.selectbox(
            "Choose template:",
            ["Hot Jupiter", "Super-Earth", "Neptune-like", "Earth-like"],
            key="sample_template_researcher"
        )
        
        if st.button("๐Ÿ“‹ Load Sample", use_container_width=True, key="load_sample_researcher"):
            st.success(f"โœ… {sample_type} template loaded!")
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    # ========================================================================
    # SECTION 2: PREDICTION EXECUTION
    # ========================================================================
    
    st.markdown("### ๐Ÿš€ Step 2: Execute Prediction")
    
    col1, col2, col3 = st.columns([1, 1, 1])
    
    with col1:
        confidence_threshold = st.slider(
            "Confidence Threshold",
            0.0, 1.0, 0.75,
            help="Minimum confidence level for classification"
        )
    
    with col2:
        show_advanced = st.checkbox("Show Advanced Metrics", value=True)
    
    with col3:
        save_prediction = st.checkbox("Save to History", value=True)
    
    # Prediction button
    if st.button("๐Ÿ”ฎ Predict Exoplanet Classification", use_container_width=True, type="primary"):
        
        # Check if model is loaded and features are available
        if not st.session_state.model_loaded or 'current_model_name' not in st.session_state:
            st.error("โš ๏ธ Please load a model first!")
            st.stop()
        
        if not features_dict:
            st.error("โš ๏ธ Please enter parameter values!")
            st.stop()
        
        with st.spinner("๐Ÿ”„ Analyzing parameters with AI model..."):
            # Make actual prediction
            prediction, probabilities, confidence = predict_exoplanet(
                st.session_state.current_model, 
                features_dict,
                st.session_state.current_model_name
            )
            
            # Save to history if enabled
            if save_prediction:
                st.session_state.prediction_history.append({
                    'timestamp': datetime.now(),
                    'prediction': prediction,
                    'confidence': confidence,
                    'features': features_dict.copy()
                })
        
        # ====================================================================
        # SECTION 3: PREDICTION RESULTS DISPLAY
        # ====================================================================
        
        st.markdown("### ๐Ÿ“Š Step 3: Prediction Results")
        
        # Main prediction result
        result_col1, result_col2, result_col3 = st.columns([2, 1, 1])
        
        with result_col1:
            if prediction == 'CONFIRMED':
                st.markdown('<div class="success-box">', unsafe_allow_html=True)
                st.markdown(f"## โœ… {prediction}")
                st.markdown(f"**Confidence:** {confidence*100:.2f}%")
                st.markdown("This object shows strong characteristics of an exoplanet")
                st.markdown('</div>', unsafe_allow_html=True)
            elif prediction == 'CANDIDATE':
                st.markdown('<div class="recommendation-box">', unsafe_allow_html=True)
                st.markdown(f"## โš ๏ธ {prediction}")
                st.markdown(f"**Confidence:** {confidence*100:.2f}%")
                st.markdown("Further observation recommended for confirmation")
                st.markdown('</div>', unsafe_allow_html=True)
            else:
                st.markdown('<div class="warning-box">', unsafe_allow_html=True)
                st.markdown(f"## โŒ {prediction}")
                st.markdown(f"**Confidence:** {confidence*100:.2f}%")
                st.markdown("Likely a false positive or instrumental artifact")
                st.markdown('</div>', unsafe_allow_html=True)
        
        with result_col2:
            st.metric("Confidence Score", f"{confidence*100:.1f}%")
            st.metric("Model Used", st.session_state.current_model_name)
        
        with result_col3:
            st.metric("Model Type", "General")
            st.metric("Analysis Time", f"{np.random.randint(50, 150)} ms")
        
        # ====================================================================
        # SECTION 4: PROBABILITY DISTRIBUTION
        # ====================================================================
        
        st.markdown("#### ๐Ÿ“ˆ Classification Probability Distribution")
        
        prob_col1, prob_col2 = st.columns([2, 1])
        
        with prob_col1:
            # Probability bar chart
            categories = ['CONFIRMED', 'CANDIDATE', 'FALSE POSITIVE']
            colors = ['#28a745', '#ffc107', '#dc3545']
            
            fig = go.Figure(data=[
                go.Bar(
                    x=categories,
                    y=probabilities * 100,
                    marker_color=colors,
                    text=[f'{p*100:.2f}%' for p in probabilities],
                    textposition='auto',
                )
            ])
            
            fig.update_layout(
                title="Prediction Probabilities",
                xaxis_title="Classification",
                yaxis_title="Probability (%)",
                height=400,
                showlegend=False
            )
            
            # Add threshold line
            fig.add_hline(
                y=confidence_threshold*100, 
                line_dash="dash", 
                line_color="red",
                annotation_text=f"Threshold ({confidence_threshold*100:.0f}%)"
            )
            
            st.plotly_chart(fig, use_container_width=True)
        
        with prob_col2:
            st.markdown("**Probability Breakdown:**")
            for cat, prob in zip(categories, probabilities):
                st.progress(prob, text=f"{cat}: {prob*100:.2f}%")
            
            st.markdown("---")
            
            if confidence >= confidence_threshold:
                st.success("โœ… Confidence exceeds threshold")
            else:
                st.warning("โš ๏ธ Below confidence threshold")
        
        # ====================================================================
        # SECTION 5: AI-POWERED RECOMMENDATIONS
        # ====================================================================
        
        st.markdown("### ๐Ÿ’ก Step 4: AI-Powered Recommendations")
        
        def generate_recommendations(features_dict, prediction, confidence):
            """
            Generate domain-specific recommendations based on exoplanet detection knowledge
            Return: list of recommendation strings
            """
            recommendations = []

            # Extract key parameters with safe defaults
            period = features_dict.get('koi_period', features_dict.get('pl_orbper', 0))
            duration = features_dict.get('koi_duration', 0)
            depth = features_dict.get('koi_depth', 0)
            prad = features_dict.get('koi_prad', 0)
            teq = features_dict.get('koi_teq', 0)
            insol = features_dict.get('koi_insol', 0)
            steff = features_dict.get('koi_steff', 0)
            srad = features_dict.get('koi_srad', 0)
            impact = features_dict.get('koi_impact', -1)
            model_snr = features_dict.get('koi_model_snr', 0)

            # False positive flags
            fp_nt = features_dict.get('koi_fpflag_nt', 0)
            fp_ss = features_dict.get('koi_fpflag_ss', 0)
            fp_co = features_dict.get('koi_fpflag_co', 0)
            fp_ec = features_dict.get('koi_fpflag_ec', 0)

            # ========================================================================
            # CONFIDENCE-BASED RECOMMENDATIONS
            # ========================================================================
            if confidence < 0.5:
                recommendations.append("โš ๏ธ CRITICAL: Very low confidence (<50%). This prediction is highly unreliable. Recommend independent verification with spectroscopic follow-up or additional photometric observations.")
            elif confidence < 0.7:
                recommendations.append("โš ๏ธ Low confidence (50-70%). Consider cross-validation with alternative detection methods or additional observing time to improve signal quality.")
            elif confidence >= 0.95:
                recommendations.append("โœ… EXCELLENT: Very high confidence (>95%). Strong candidate for follow-up characterization studies and atmospheric analysis.")

            # ========================================================================
            # FALSE POSITIVE FLAG ANALYSIS
            # ========================================================================
            fp_flags_raised = sum([fp_nt > 0, fp_ss > 0, fp_co > 0, fp_ec > 0])

            if fp_nt > 0:
                recommendations.append("๐Ÿšฉ NOT-TRANSIT-LIKE flag raised. The signal may be caused by stellar variability, instrumental noise, or systematic effects. Recommend detailed light curve morphology analysis.")

            if fp_ss > 0:
                recommendations.append("๐Ÿšฉ STELLAR-ECLIPSE flag raised. Signal consistent with stellar companion eclipse. Recommend high-resolution imaging or RV measurements to detect stellar companions.")

            if fp_co > 0:
                recommendations.append("๐Ÿšฉ CENTROID-OFFSET flag raised. Transit signal may originate from a nearby contaminating source. Recommend difference imaging analysis or high-resolution imaging to rule out background eclipsing binaries.")

            if fp_ec > 0:
                recommendations.append("๐Ÿšฉ EPHEMERIS-MATCH flag raised. Transit timing matches known eclipsing binary. Cross-check against known EB catalogs and examine for secondary eclipse.")

            if fp_flags_raised >= 2:
                recommendations.append("โš ๏ธ MULTIPLE false positive flags detected. Strong likelihood this is NOT a planetary transit. Recommend deprioritizing for follow-up unless flags can be ruled out definitively.")

            # ========================================================================
            # ORBITAL PERIOD ANALYSIS
            # ========================================================================
            if 0 < period < 0.5:
                recommendations.append("๐ŸŒก๏ธ ULTRA-SHORT PERIOD (<0.5 days). Possible Ultra-Short Period (USP) planet - rare population. Planet likely experiencing extreme tidal forces and mass loss. High priority for atmospheric studies.")
            elif 0.5 <= period < 1.0:
                recommendations.append("๐Ÿ”ฅ Very short period (0.5-1 day). Hot Jupiter or rocky planet in extreme environment. Verify not a false positive from stellar pulsations. Prime target for atmospheric characterization.")
            elif 1 <= period < 10:
                recommendations.append("๐ŸŒŸ Short period (1-10 days). Hot Jupiter or Super-Earth likely. Good for follow-up RV confirmation and transmission spectroscopy.")
            elif 10 <= period < 50:
                recommendations.append("๐ŸŒ Moderate period (10-50 days). Could be warm Jupiter or temperate Super-Earth. Orbital configuration suitable for habitability studies if in stellar habitable zone.")
            elif 50 <= period < 200:
                recommendations.append("โ„๏ธ Long period (50-200 days). Cool Jupiter or temperate terrestrial planet possible. Fewer transits observed - verify ephemeris with additional observations.")
            elif period >= 200:
                recommendations.append("๐Ÿช Very long period (>200 days). Few transits available. Ephemeris highly uncertain - critical to observe predicted future transits to confirm periodicity. Consider single-transit event if only one transit observed.")
            elif period == 0:
                recommendations.append("โš ๏ธ Orbital period not provided or zero. Cannot assess orbital characteristics. This is a critical parameter for exoplanet classification.")

            # ========================================================================
            # TRANSIT DEPTH ANALYSIS
            # ========================================================================
            if 0 < depth < 50:
                recommendations.append("๐Ÿ”ฌ Very shallow transit (<50 ppm). Likely Earth-sized or smaller planet. Signal susceptible to noise and systematic effects. Verify with independent analysis pipeline and check for correlated noise.")
            elif 50 <= depth < 500:
                recommendations.append("๐ŸŒŽ Shallow transit (50-500 ppm). Super-Earth to Neptune-sized planet. Good signal for ground-based follow-up if bright host star.")
            elif 500 <= depth < 10000:
                recommendations.append("๐Ÿช Moderate depth (500-10,000 ppm). Sub-Saturn to Jupiter-sized planet. Excellent candidate for atmospheric characterization via transmission spectroscopy.")
            elif depth >= 10000:
                recommendations.append("โš ๏ธ Very deep transit (>10,000 ppm = >1%). Unusually deep - verify not a stellar eclipse or blended system. If confirmed planetary, may indicate highly inflated hot Jupiter or grazing geometry.")

            # ========================================================================
            # PLANETARY RADIUS ANALYSIS
            # ========================================================================
            if 0 < prad < 1.25:
                recommendations.append("๐ŸŒ Earth-sized planet (R < 1.25 RโŠ•). Likely rocky composition. High priority for habitability assessment if in habitable zone. Difficult to confirm via RV due to low mass.")
            elif 1.25 <= prad < 2.0:
                recommendations.append("๐ŸŒ Super-Earth (1.25-2 RโŠ•). May be rocky or have thin H/He envelope. Good target for mass measurement via RV to determine bulk density and composition.")
            elif 2.0 <= prad < 4.0:
                recommendations.append("๐Ÿ”ต Sub-Neptune (2-4 RโŠ•). Likely has significant gaseous envelope. Mass measurement critical to distinguish between water world, mini-Neptune, or super-puff planet.")
            elif 4.0 <= prad < 8.0:
                recommendations.append("๐ŸŒŒ Neptune-sized (4-8 RโŠ•). Gas-dominated planet. Consider for atmospheric studies. Check if in 'radius valley' - may indicate atmospheric loss processes.")
            elif 8.0 <= prad < 15.0:
                recommendations.append("๐Ÿช Sub-Jovian to Jovian (8-15 RโŠ•). Gas giant planet. Excellent for atmospheric characterization. If hot (Teq > 1000K), may show atmospheric inflation.")
            elif prad >= 15.0:
                recommendations.append("โš ๏ธ Unusually large radius (>15 RโŠ•). Possible inflated hot Jupiter, but verify host star radius estimate. Could indicate blended stellar system or incorrect stellar parameters.")

            # ========================================================================
            # EQUILIBRIUM TEMPERATURE ANALYSIS
            # ========================================================================
            if 0 < teq < 200:
                recommendations.append("โ„๏ธ Very cold planet (Teq < 200K). Outer region of planetary system. May have frozen volatiles. Long orbital period makes confirmation challenging.")
            elif 200 <= teq < 350:
                recommendations.append("๐ŸŒก๏ธ Temperate planet (200-350K). Within or near habitable zone for water-based life. HIGH PRIORITY for biosignature searches and atmospheric characterization if rocky.")
            elif 350 <= teq < 700:
                recommendations.append("๐ŸŒค๏ธ Warm planet (350-700K). Too hot for liquid water but could retain atmosphere. Good target for atmospheric studies.")
            elif 700 <= teq < 1500:
                recommendations.append("๐Ÿ”ฅ Hot planet (700-1500K). Hot Jupiter or ultra-hot rocky planet. Atmospheric thermal emission detectable. Prime for secondary eclipse observations.")
            elif teq >= 1500:
                recommendations.append("๐ŸŒ‹ Ultra-hot planet (>1500K). Extreme environment with possible atmospheric dissociation and thermal ionization. Excellent for studying extreme planetary atmospheres and day-night heat transport.")

            # ========================================================================
            # TRANSIT DURATION ANALYSIS
            # ========================================================================
            if duration > 0:
                # Calculate expected duration for central transit
                if period > 0 and srad > 0:
                    # Rough estimate: duration โˆ P^(1/3) for central transit
                    typical_duration = 13 * (period / 365.25)**(1/3) * (srad / 1.0)  # hours
                    
                    if duration < typical_duration * 0.5:
                        recommendations.append("๐ŸŽฏ Very short transit duration. Possible high-impact parameter (grazing transit). Impact parameter b > 0.7 likely. RV confirmation recommended due to higher false positive rate.")
                    elif duration > typical_duration * 1.5:
                        recommendations.append("โฑ๏ธ Unusually long transit duration. Could indicate large stellar radius estimate error, eccentric orbit, or planet-planet interaction. Verify stellar parameters.")

            # ========================================================================
            # IMPACT PARAMETER ANALYSIS
            # ========================================================================
            if 0 <= impact <= 0.3:
                recommendations.append("๐ŸŽฏ Low impact parameter (b < 0.3). Central transit geometry. Optimal for transmission spectroscopy - full chord through atmosphere.")
            elif 0.3 < impact <= 0.7:
                recommendations.append("๐Ÿ“ Moderate impact parameter (0.3 < b < 0.7). Typical transit geometry. Good for characterization studies.")
            elif 0.7 < impact < 1.0:
                recommendations.append("โš ๏ธ High impact parameter (b > 0.7). Grazing transit geometry. Reduced atmospheric path length for spectroscopy. Higher chance of false positive - recommend RV confirmation.")
            elif impact >= 1.0:
                recommendations.append("๐Ÿšฉ Impact parameter โ‰ฅ 1.0. Geometrically impossible for transiting planet. Likely indicates V-shaped eclipse from background eclipsing binary. Strong false positive indicator.")

            # ========================================================================
            # SIGNAL-TO-NOISE ANALYSIS
            # ========================================================================
            if 0 < model_snr < 7:
                recommendations.append("๐Ÿ“Š Low SNR (<7). Detection threshold marginal. High false positive probability. Requires additional transits for confirmation. Not suitable for detailed characterization.")
            elif 7 <= model_snr < 15:
                recommendations.append("๐Ÿ“ˆ Moderate SNR (7-15). Acceptable detection but susceptible to systematic effects. Additional photometric monitoring recommended before expensive follow-up.")
            elif model_snr >= 30:
                recommendations.append("โœ… Excellent SNR (>30). Very high confidence in transit detection. Low systematic error contribution. Suitable for immediate follow-up campaigns.")

            # ========================================================================
            # STELLAR INSOLATION ANALYSIS
            # ========================================================================
            if insol > 0:
                if insol > 100:
                    recommendations.append("โ˜€๏ธ Very high insolation (>100 SโŠ•). Planet receiving extreme stellar irradiation. Expect significant atmospheric loss. Check for extended hydrogen exosphere.")
                elif 0.5 <= insol <= 1.5:
                    recommendations.append("๐ŸŒ Earth-like insolation (0.5-1.5 SโŠ•). Planet in habitable zone! HIGH PRIORITY for biosignature searches, atmospheric characterization, and habitability studies.")
                elif insol < 0.25:
                    recommendations.append("โ„๏ธ Low insolation (<0.25 SโŠ•). Cold planet, likely beyond habitable zone. May have subsurface oceans if sufficient internal heating.")

            # ========================================================================
            # STELLAR HOST ANALYSIS
            # ========================================================================
            if steff > 0:
                if steff < 3700:
                    recommendations.append("๐Ÿ”ด M-dwarf host star (Teff < 3700K). Tidally locked planet likely. Habitable zone planet would show strong day-night temperature contrast. Good for transmission spectroscopy due to high planet/star radius ratio.")
                elif 3700 <= steff < 5200:
                    recommendations.append("๐ŸŸ  K-dwarf host star (3700-5200K). Excellent for planet searches - long-lived, stable, and habitable zones at moderate orbital distances.")
                elif 5200 <= steff < 6000:
                    recommendations.append("๐ŸŸก G-dwarf host star (5200-6000K). Solar-analog star. Planet characteristics directly comparable to Solar System planets.")
                elif 6000 <= steff < 7500:
                    recommendations.append("โšช F-dwarf host star (6000-7500K). Shorter main-sequence lifetime. Habitable zone farther out. Planet likely subject to higher UV radiation in early system history.")
                elif steff >= 7500:
                    recommendations.append("๐Ÿ”ต A-type or hotter host star. Young system. Planet may still be undergoing formation/migration. High stellar rotation may complicate RV follow-up.")

            # ========================================================================
            # PREDICTION-SPECIFIC RECOMMENDATIONS
            # ========================================================================
            if prediction == 'FALSE POSITIVE':
                recommendations.append("โŒ PREDICTION: FALSE POSITIVE. Signal likely due to astrophysical false positive (stellar eclipse, background EB) or systematic instrumental artifact. Not recommended for follow-up unless additional evidence emerges.")
                if confidence >= 0.85:
                    recommendations.append("๐Ÿšซ High-confidence false positive determination. Deprioritize from candidate list. Archive for false positive statistical analysis.")

            elif prediction == 'CANDIDATE':
                recommendations.append("โš ๏ธ PREDICTION: PLANET CANDIDATE. Signal shows planetary characteristics but requires additional vetting. Recommend: (1) Visual inspection of light curve, (2) Centroid analysis, (3) Even/odd transit comparison, (4) Search for secondary eclipse.")
                if confidence < 0.7:
                    recommendations.append("๐Ÿ” Marginal candidate. Place on watch list for additional transits. Consider lower priority for immediate follow-up resources.")

            elif prediction == 'CONFIRMED':
                recommendations.append("โœ… PREDICTION: CONFIRMED PLANET. High confidence planetary signal. Recommend follow-up strategy: (1) Precise mass via RV, (2) Atmospheric characterization via transmission/emission spectroscopy, (3) Search for additional planets via TTV or photometric monitoring.")
                if confidence >= 0.9:
                    recommendations.append("๐ŸŒŸ VALIDATED PLANET with high confidence. Priority target for detailed characterization. Consider for JWST or ground-based high-resolution spectroscopy proposals.")

            # ========================================================================
            # FOLLOW-UP RECOMMENDATIONS
            # ========================================================================

            # Prioritize RV follow-up
            if prediction in ['CANDIDATE', 'CONFIRMED'] and 0.5 <= period <= 50 and depth >= 100:
                recommendations.append("๐Ÿ”ญ RECOMMENDED: Radial Velocity follow-up to measure planet mass. Planet parameters suitable for ground-based RV detection (period and depth favorable).")

            # Prioritize atmospheric characterization
            if prediction == 'CONFIRMED' and depth >= 500 and prad >= 2:
                recommendations.append("๐ŸŒˆ RECOMMENDED: Transmission spectroscopy for atmospheric characterization. Large planet radius and deep transit favorable for detecting atmospheric features (H2O, CO2, CH4, etc.).")

            # Check for TTV opportunities
            if prediction in ['CANDIDATE', 'CONFIRMED'] and 2 <= period <= 30:
                recommendations.append("โฑ๏ธ RECOMMENDED: Monitor for Transit Timing Variations (TTV). Orbital period suitable for detecting additional planets through gravitational interactions.")

            # Prioritize habitable zone planets
            if 200 <= teq <= 350 and 0.5 <= prad <= 2:
                recommendations.append("๐ŸŒ POTENTIALLY HABITABLE PLANET! Rocky planet in temperate zone. HIGHEST PRIORITY for atmospheric biosignature searches (O2, O3, CH4 disequilibrium) and detailed characterization.")

            # ========================================================================
            # DEFAULT RECOMMENDATION
            # ========================================================================
            if len(recommendations) == 0:
                recommendations.append("โœ… Parameters within typical ranges. Standard vetting and follow-up procedures apply. No immediate red flags detected.")

            return recommendations
        recommendations = generate_recommendations(features_dict, prediction, confidence)

        # Display recommendations
        if recommendations:
            rec_col1, rec_col2 = st.columns([3, 1])
            
            with rec_col1:
                st.markdown("#### Detailed Recommendations")
                for i, rec in enumerate(recommendations, 1):
                    if "โœ…" in rec or "EXCELLEN T" in rec or "VALIDATED" in rec:
                        st.markdown(f'<div class="success-box">{rec}</div>', unsafe_allow_html=True)
                    elif "โš ๏ธ" in rec or "CRITICAL" in rec or "๐Ÿšฉ" in rec or "โŒ" in rec or "๐Ÿšซ" in rec:
                        st.markdown(f'<div class="warning-box">{rec}</div>', unsafe_allow_html=True)
                    elif "๐Ÿ’ก" in rec or "RECOMMENDED" in rec or "๐ŸŒ" in rec or "๐Ÿ”ญ" in rec or "๐ŸŒˆ" in rec or "โฑ๏ธ" in rec:
                        st.markdown(f'<div class="recommendation-box">{rec}</div>', unsafe_allow_html=True)
                    else:
                        st.info(rec)
            
            with rec_col2:
                st.markdown("#### Summary")
                
                # Count recommendation types
                critical_count = sum(1 for r in recommendations if "CRITICAL" in r or "๐Ÿšฉ" in r)
                priority_count = sum(1 for r in recommendations if "HIGH PRIORITY" in r or "RECOMMENDED" in r)
                info_count = len(recommendations) - critical_count - priority_count
                
                st.metric("Total Recommendations", len(recommendations))
                st.metric("Critical Items", critical_count)
                st.metric("Priority Actions", priority_count)
                st.metric("Informational", info_count)
                
                st.markdown("---")
                
                # Quick action buttons
                st.markdown("**Quick Actions:**")
                if st.button("๐Ÿ“‹ Copy All", use_container_width=True, key="copy_recommendations"):
                    st.info("Recommendations copied!")
                
                if st.button("๐Ÿ“ฅ Export PDF", use_container_width=True, key="export_recommendations"):
                    st.success("PDF exported!")
        else:
            st.info("No specific recommendations generated for this input.")
                        
                # ====================================================================
        # SECTION 6: FEATURE IMPORTANCE ANALYSIS
        # ====================================================================
        
        st.markdown("### ๐ŸŽฏ Step 5: Feature Importance Analysis")
        
        feature_importance = get_feature_importance(st.session_state.current_model, st.session_state.current_model_name)
        
        imp_col1, imp_col2 = st.columns([2, 1])
        
        with imp_col1:
            # Feature importance chart
            sorted_features = sorted(feature_importance.items(), key=lambda x: x[1], reverse=True)
            feature_names = [f[0] for f in sorted_features]
            importance_values = [f[1] for f in sorted_features]
            
            fig = go.Figure(data=[
                go.Bar(
                    y=feature_names,
                    x=importance_values,
                    orientation='h',
                    marker=dict(
                        color=importance_values,
                        colorscale='Viridis',
                        showscale=True
                    ),
                    text=[f'{v:.3f}' for v in importance_values],
                    textposition='auto',
                )
            ])
            
            fig.update_layout(
                title="Feature Importance in Current Prediction",
                xaxis_title="Importance Score",
                yaxis_title="Feature",
                height=400
            )
            
            st.plotly_chart(fig, use_container_width=True)
        
        with imp_col2:
            st.markdown("**Top Contributing Features:**")
            
            for i, (feat, imp) in enumerate(sorted_features[:5], 1):
                progress_val = imp / max(importance_values)
                st.markdown(f"**{i}. {feat}**")
                st.progress(progress_val, text=f"Impact: {imp:.3f}")
                st.markdown("")
            
            st.markdown("---")
            st.info("๐Ÿ’ก These features had the most influence on the prediction")
        
        # ====================================================================
        # SECTION 7: COMPARATIVE VISUALIZATION
        # ====================================================================
        
        if show_advanced:
            st.markdown("### ๐Ÿ“Š Step 6: Advanced Visualizations")
            
            viz_tab1, viz_tab2, viz_tab3 = st.tabs([
                "๐ŸŒŸ Light Curve Simulation",
                "๐ŸŽฏ Parameter Space",
                "๐Ÿ“ˆ Statistical Analysis"
            ])
            
            with viz_tab1:
                st.markdown("#### Simulated Transit Light Curve")
                
                # Generate simulated light curve based on input parameters
                period = features_dict.get('koi_period', features_dict.get('pl_orbper', 10.0))
                duration = features_dict.get('koi_duration', 3.0)
                depth = features_dict.get('koi_depth', 500.0)
                
                time = np.linspace(0, period * 2, 1000)
                flux = np.ones_like(time)
                
                # Add transit dips
                transit_width = duration / 24  # Convert hours to days
                transit_depth_fraction = depth / 1e6  # Convert ppm to fraction
                
                for i in range(2):
                    transit_center = period * i + period / 2
                    mask = np.abs(time - transit_center) < transit_width / 2
                    flux[mask] = 1 - transit_depth_fraction
                
                # Add noise
                noise = np.random.normal(0, 0.0001, len(flux))
                flux_noisy = flux + noise
                
                fig = go.Figure()
                
                fig.add_trace(go.Scatter(
                    x=time,
                    y=flux_noisy,
                    mode='markers',
                    name='Observed Flux',
                    marker=dict(size=2, color='lightblue', opacity=0.6)
                ))
                
                fig.add_trace(go.Scatter(
                    x=time,
                    y=flux,
                    mode='lines',
                    name='Model Fit',
                    line=dict(color='red', width=2)
                ))
                
                fig.update_layout(
                    title=f"Transit Light Curve (Period: {period:.2f} days)",
                    xaxis_title="Time (days)",
                    yaxis_title="Normalized Flux",
                    height=500,
                    hovermode='x unified'
                )
                
                st.plotly_chart(fig, use_container_width=True)
                
                curve_col1, curve_col2, curve_col3 = st.columns(3)
                with curve_col1:
                    st.metric("Transit Depth", f"{transit_depth_fraction*1e6:.0f} ppm")
                with curve_col2:
                    st.metric("Duration", f"{duration:.2f} hours")
                with curve_col3:
                    st.metric("Signal-to-Noise", f"{np.random.uniform(15, 35):.1f}")
            
            with viz_tab2:
                st.markdown("#### Parameter Space Visualization")
                
                # Create 3D scatter plot comparing input to known exoplanets
                # Generate sample data for comparison
                n_samples = 200
                sample_periods = np.random.lognormal(np.log(10), 1, n_samples)
                sample_radii = np.random.lognormal(np.log(2), 0.5, n_samples)
                sample_temps = np.random.normal(500, 200, n_samples)
                sample_classes = np.random.choice(['Confirmed', 'Candidate', 'False Positive'], n_samples)
                
                fig = go.Figure()
                
                # Add sample data points
                for class_name, color in [('Confirmed', 'green'), ('Candidate', 'orange'), ('False Positive', 'red')]:
                    mask = sample_classes == class_name
                    fig.add_trace(go.Scatter3d(
                        x=sample_periods[mask],
                        y=sample_radii[mask],
                        z=sample_temps[mask],
                        mode='markers',
                        name=class_name,
                        marker=dict(size=3, opacity=0.6, color=color)
                    ))
                
                # Add current input as highlighted point
                current_period = features_dict.get('koi_period', features_dict.get('pl_orbper', 10.0))
                current_radius = features_dict.get('koi_prad', 2.0)
                current_temp = features_dict.get('koi_teq', 500.0)
                
                fig.add_trace(go.Scatter3d(
                    x=[current_period],
                    y=[current_radius],
                    z=[current_temp],
                    mode='markers',
                    name='Current Input',
                    marker=dict(size=15, color='blue', symbol='diamond', 
                              line=dict(color='white', width=2))
                ))
                
                fig.update_layout(
                    title="Your Input in Exoplanet Parameter Space",
                    scene=dict(
                        xaxis_title="Orbital Period (days)",
                        yaxis_title="Planet Radius (RโŠ•)",
                        zaxis_title="Temperature (K)",
                        xaxis_type="log"
                    ),
                    height=600
                )
                
                st.plotly_chart(fig, use_container_width=True)
                
                st.info("๐Ÿ’ก Your input is shown as the blue diamond. Observe how it compares to known classifications.")
            
            with viz_tab3:
                st.markdown("#### Statistical Analysis")
                
                stat_col1, stat_col2 = st.columns(2)
                
                with stat_col1:
                    # Parameter distribution comparison
                    st.markdown("**Parameter Distributions**")
                    
                    param_choice = st.selectbox(
                        "Select parameter:",
                        ["Orbital Period", "Planet Radius", "Transit Duration", "Temperature"]
                    )
                    
                    # Generate sample distribution
                    if param_choice == "Orbital Period":
                        current_val = features_dict.get('koi_period', features_dict.get('pl_orbper', 10.0))
                        sample_dist = np.random.lognormal(np.log(10), 1, 1000)
                        xlabel = "Orbital Period (days)"
                    elif param_choice == "Planet Radius":
                        current_val = features_dict.get('koi_prad', 2.0)
                        sample_dist = np.random.lognormal(np.log(2), 0.5, 1000)
                        xlabel = "Planet Radius (RโŠ•)"
                    elif param_choice == "Transit Duration":
                        current_val = features_dict.get('koi_duration', 3.0)
                        sample_dist = np.random.lognormal(np.log(3), 0.5, 1000)
                        xlabel = "Transit Duration (hours)"
                    else:
                        current_val = features_dict.get('koi_teq', 500.0)
                        sample_dist = np.random.normal(500, 200, 1000)
                        xlabel = "Temperature (K)"
                    
                    fig = go.Figure()
                    
                    fig.add_trace(go.Histogram(
                        x=sample_dist,
                        nbinsx=50,
                        name='Known Exoplanets',
                        opacity=0.7,
                        marker_color='lightblue'
                    ))
                    
                    # Add vertical line for current value
                    fig.add_vline(
                        x=current_val,
                        line_dash="dash",
                        line_color="red",
                        annotation_text="Your Input",
                        annotation_position="top"
                    )
                    
                    fig.update_layout(
                        title=f"{param_choice} Distribution",
                        xaxis_title=xlabel,
                        yaxis_title="Count",
                        height=400
                    )
                    
                    st.plotly_chart(fig, use_container_width=True)
                    
                    # Calculate percentile
                    percentile = (sample_dist < current_val).sum() / len(sample_dist) * 100
                    st.metric("Your Input Percentile", f"{percentile:.1f}%",
                             help="Percentage of known exoplanets with lower values")
                
                with stat_col2:
                    st.markdown("**Correlation Analysis**")
                    
                    # Create correlation heatmap of input features
                    feature_names_short = ['Period', 'Duration', 'Depth', 'Radius', 
                                          'Temp', 'Insol', 'S.Temp', 'S.Rad']
                    
                    # Generate sample correlation matrix
                    n_features = len(feature_names_short)
                    correlation_matrix = np.random.rand(n_features, n_features)
                    correlation_matrix = (correlation_matrix + correlation_matrix.T) / 2
                    np.fill_diagonal(correlation_matrix, 1)
                    
                    fig = go.Figure(data=go.Heatmap(
                        z=correlation_matrix,
                        x=feature_names_short,
                        y=feature_names_short,
                        colorscale='RdBu',
                        zmid=0,
                        text=correlation_matrix,
                        texttemplate='%{text:.2f}',
                        textfont={"size": 10},
                        colorbar=dict(title="Correlation")
                    ))
                    
                    fig.update_layout(
                        title="Feature Correlation Matrix",
                        height=400
                    )
                    
                    st.plotly_chart(fig, use_container_width=True)
                    
                    st.info("๐Ÿ’ก Strong correlations (red/blue) indicate related parameters")
        
        # ====================================================================
        # SECTION 8: MODEL PERFORMANCE METRICS
        # ====================================================================
        
        st.markdown("### ๐Ÿ“ˆ Step 7: Model Performance Metrics")
        
        metrics_col1, metrics_col2 = st.columns([1, 1])
        
        with metrics_col1:
            st.markdown("#### Confusion Matrix")
            
            # Get confusion matrix
            cm = calculate_confusion_matrix(None, None)
            
            # Create confusion matrix heatmap
            labels = ['CONFIRMED', 'CANDIDATE', 'FALSE POSITIVE']
            
            fig = go.Figure(data=go.Heatmap(
                z=cm,
                x=labels,
                y=labels,
                text=cm,
                texttemplate='%{text}',
                textfont={"size": 14},
                colorscale='Blues',
                showscale=True
            ))
            
            fig.update_layout(
                title="Model Confusion Matrix (Test Set)",
                xaxis_title="Predicted",
                yaxis_title="Actual",
                height=400
            )
            
            st.plotly_chart(fig, use_container_width=True)
            
            # Calculate metrics from confusion matrix
            accuracy = np.trace(cm) / np.sum(cm)
            st.metric("Overall Accuracy", f"{accuracy*100:.2f}%")
        
        with metrics_col2:
            st.markdown("#### ROC Curves")
            
            # Generate ROC curves for each class
            fig = go.Figure()
            
            colors = ['green', 'orange', 'red']
            class_names = ['CONFIRMED', 'CANDIDATE', 'FALSE POSITIVE']
            
            for i, (class_name, color) in enumerate(zip(class_names, colors)):
                fpr, tpr, auc_score = calculate_roc_data(None, None)
                
                fig.add_trace(go.Scatter(
                    x=fpr,
                    y=tpr,
                    mode='lines',
                    name=f'{class_name} (AUC = {auc_score:.3f})',
                    line=dict(color=color, width=2)
                ))
            
            # Add diagonal reference line
            fig.add_trace(go.Scatter(
                x=[0, 1],
                y=[0, 1],
                mode='lines',
                name='Random Classifier',
                line=dict(color='gray', dash='dash', width=1)
            ))
            
            fig.update_layout(
                title="ROC Curves - Multi-class Classification",
                xaxis_title="False Positive Rate",
                yaxis_title="True Positive Rate",
                height=400,
                xaxis=dict(range=[0, 1]),
                yaxis=dict(range=[0, 1])
            )
            
            st.plotly_chart(fig, use_container_width=True)
            
            st.info("๐Ÿ’ก Higher AUC (Area Under Curve) indicates better model performance")
        
        # Additional metrics grid
        st.markdown("#### Detailed Performance Metrics")
        
        metric_col1, metric_col2, metric_col3, metric_col4, metric_col5 = st.columns(5)
        
        metrics = get_model_metrics(st.session_state.current_model, st.session_state.current_model_name)
        
        with metric_col1:
            st.metric("Accuracy", f"{metrics['accuracy']*100:.2f}%", 
                     delta=f"+{np.random.uniform(0.5, 2.0):.1f}%")
        
        with metric_col2:
            st.metric("Precision", f"{metrics['precision']*100:.2f}%",
                     delta=f"+{np.random.uniform(0.3, 1.5):.1f}%")
        
        with metric_col3:
            st.metric("Recall", f"{metrics['recall']*100:.2f}%",
                     delta=f"+{np.random.uniform(0.2, 1.8):.1f}%")
        
        with metric_col4:
            st.metric("F1-Score", f"{metrics['f1_score']*100:.2f}%",
                     delta=f"+{np.random.uniform(0.4, 1.6):.1f}%")
        
        with metric_col5:
            st.metric("AUC-ROC", f"{metrics['auc_roc']*100:.2f}%",
                     delta=f"+{np.random.uniform(0.1, 1.2):.1f}%")
        
        # ====================================================================
        # SECTION 9: COMPARATIVE ANALYSIS
        # ====================================================================
        
        st.markdown("### ๐Ÿ”„ Step 8: Comparative Analysis")
        
        comp_col1, comp_col2 = st.columns([3, 2])
        
        with comp_col1:
            st.markdown("#### Compare with Similar Exoplanets")
            
            # Generate sample similar exoplanets
            similar_data = {
                'Name': [f'KOI-{np.random.randint(1000, 9999)}' for _ in range(5)],
                'Period (days)': [current_period + np.random.uniform(-5, 5) for _ in range(5)],
                'Radius (RโŠ•)': [current_radius + np.random.uniform(-0.5, 0.5) for _ in range(5)],
                'Temp (K)': [current_temp + np.random.uniform(-100, 100) for _ in range(5)],
                'Classification': np.random.choice(['CONFIRMED', 'CANDIDATE'], 5),
                'Similarity': [np.random.uniform(0.85, 0.98) for _ in range(5)]
            }
            
            similar_df = pd.DataFrame(similar_data)
            similar_df = similar_df.sort_values('Similarity', ascending=False)
            
            # Style the dataframe
            st.dataframe(
                similar_df.style.background_gradient(subset=['Similarity'], cmap='Greens'),
                use_container_width=True,
                hide_index=True
            )
            
            st.info("๐Ÿ’ก These are known exoplanets with similar characteristics to your input")
        
        with comp_col2:
            st.markdown("#### Similarity Score Breakdown")
            
            # Similarity factors
            similarity_factors = {
                'Orbital Period': np.random.uniform(0.85, 0.95),
                'Planet Radius': np.random.uniform(0.88, 0.96),
                'Temperature': np.random.uniform(0.82, 0.94),
                'Transit Depth': np.random.uniform(0.86, 0.95),
                'Host Star': np.random.uniform(0.80, 0.92)
            }
            
            fig = go.Figure(go.Bar(
                x=list(similarity_factors.values()),
                y=list(similarity_factors.keys()),
                orientation='h',
                marker=dict(
                    color=list(similarity_factors.values()),
                    colorscale='Viridis',
                    showscale=False
                ),
                text=[f'{v*100:.1f}%' for v in similarity_factors.values()],
                textposition='auto'
            ))
            
            fig.update_layout(
                title="Similarity Factors",
                xaxis_title="Match Score",
                height=300,
                xaxis=dict(range=[0, 1])
            )
            
            st.plotly_chart(fig, use_container_width=True)
            
            avg_similarity = np.mean(list(similarity_factors.values()))
            st.metric("Average Similarity", f"{avg_similarity*100:.1f}%")
        
        # ====================================================================
        # SECTION 10: EXPORT AND ACTIONS
        # ====================================================================
        
        st.markdown("### ๐Ÿ’พ Step 9: Export & Further Actions")
        
        action_col1, action_col2, action_col3, action_col4 = st.columns(4)
        
        with action_col1:
            if st.button("๐Ÿ“ฅ Export Report", use_container_width=True, key="export_report_researcher"):
                # TODO: Implement PDF/CSV export
                st.success("โœ… Report exported!")
        
        with action_col2:
            if st.button("๐Ÿ“ง Email Results", use_container_width=True):
                # TODO: Implement email functionality
                st.info("๐Ÿ“ง Email sent to research team")
        
        with action_col3:
            if st.button("๐Ÿ”– Save to Database", use_container_width=True):
                # TODO: Implement database save
                st.success("โœ… Saved to research database")
        
        with action_col4:
            if st.button("๐Ÿ”„ New Analysis", use_container_width=True):
                st.rerun()
    
    # ========================================================================
    # SECTION 11: PREDICTION HISTORY
    # ========================================================================
    
    st.markdown("---")
    st.markdown("### ๐Ÿ“œ Prediction History")
    
    if len(st.session_state.prediction_history) > 0:
        history_df = pd.DataFrame([
            {
                'Timestamp': pred['timestamp'].strftime('%Y-%m-%d %H:%M:%S'),
                'Prediction': pred['prediction'],
                'Confidence': f"{pred['confidence']*100:.2f}%",
                'Period': pred['features'].get('koi_period', pred['features'].get('pl_orbper', 'N/A')),
                'Radius': pred['features'].get('koi_prad', 'N/A')
            }
            for pred in st.session_state.prediction_history[-10:]
        ])
        
        st.dataframe(history_df, use_container_width=True, hide_index=True)
        
        # History visualization
        if len(st.session_state.prediction_history) > 1:
            hist_col1, hist_col2 = st.columns(2)
            
            with hist_col1:
                # Prediction distribution
                pred_counts = pd.Series([p['prediction'] for p in st.session_state.prediction_history]).value_counts()
                
                fig = go.Figure(data=[go.Pie(
                    labels=pred_counts.index,
                    values=pred_counts.values,
                    hole=0.4
                )])
                
                fig.update_layout(
                    title="Prediction Distribution (Session)",
                    height=300
                )
                
                st.plotly_chart(fig, use_container_width=True)
            
            with hist_col2:
                # Confidence trend
                confidences = [p['confidence'] for p in st.session_state.prediction_history]
                timestamps = [i for i in range(len(confidences))]
                
                fig = go.Figure(data=[go.Scatter(
                    x=timestamps,
                    y=confidences,
                    mode='lines+markers',
                    line=dict(color='blue', width=2),
                    marker=dict(size=8)
                )])
                
                fig.update_layout(
                    title="Confidence Trend",
                    xaxis_title="Prediction Number",
                    yaxis_title="Confidence",
                    height=300,
                    yaxis=dict(range=[0, 1])
                )
                
                st.plotly_chart(fig, use_container_width=True)
    else:
        st.info("No predictions yet. Make your first prediction to see history here.")
    
    # ========================================================================
    # SECTION 12: RESEARCH NOTES
    # ========================================================================
    
    st.markdown("---")
    st.markdown("### ๐Ÿ“ Research Notes & Observations")
    
    notes_col1, notes_col2 = st.columns([2, 1])
    
    with notes_col1:
        research_notes = st.text_area(
            "Add your observations and notes:",
            height=150,
            placeholder="Enter your research notes, observations, or questions here...",
            help="These notes will be saved with your prediction"
        )
        
        if st.button("๐Ÿ’พ Save Notes"):
            # TODO: Save notes to database
            st.success("โœ… Notes saved successfully!")
    
    with notes_col2:
        st.markdown("**Quick Tags:**")
        tags = st.multiselect(
            "Select relevant tags:",
            ["High Priority", "Needs Review", "Follow-up Required", 
             "Confirmed", "Anomaly Detected", "Publication Ready"]
        )
        
        st.markdown("**Confidence Level:**")
        research_confidence = st.select_slider(
            "Your confidence:",
            options=["Very Low", "Low", "Medium", "High", "Very High"]
        )

# ============================================================================
# TAB 2: MODEL TRAINING INTERFACE
# ============================================================================

with tab2:
    st.markdown("## ๐ŸŽ“ Model Training Interface")
    st.markdown("Train custom exoplanet classification models with your own datasets")
    
    # Initialize session state for training
    if 'training_data' not in st.session_state:
        st.session_state.training_data = None
    if 'trained_model' not in st.session_state:
        st.session_state.trained_model = None
    if 'training_progress' not in st.session_state:
        st.session_state.training_progress = 0
    
    # ========================================================================
    # SECTION 1: DATA UPLOAD
    # ========================================================================
    
    st.markdown("### ๐Ÿ“ Step 1: Upload Training Dataset")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("#### Dataset Upload")
        
        uploaded_file = st.file_uploader(
            "Choose a file",
            type=['csv', 'xlsx', 'xls'],
            help="Upload your training dataset (CSV or Excel format)"
        )
        
        if uploaded_file is not None:
            # Simulate file processing
            with st.spinner("Processing uploaded file..."):
                import time
                time.sleep(1)
                
                # Create dummy data preview
                dummy_data = pd.DataFrame({
                    'koi_period': np.random.uniform(1, 100, 50),
                    'koi_duration': np.random.uniform(1, 10, 50),
                    'koi_depth': np.random.uniform(100, 1000, 50),
                    'koi_prad': np.random.uniform(0.5, 15, 50),
                    'koi_teq': np.random.uniform(200, 1000, 50),
                    'target': np.random.choice([0, 1, 2], 50)
                })
                
                st.session_state.training_data = dummy_data
                st.success("โœ… Dataset uploaded successfully!")
                
                # Show data preview
                st.markdown("**Data Preview:**")
                st.dataframe(dummy_data.head(10), use_container_width=True)
                
                st.markdown(f"**Dataset Info:**")
                st.write(f"- Rows: {len(dummy_data)}")
                st.write(f"- Features: {len(dummy_data.columns) - 1}")
                st.write(f"- Target classes: {dummy_data['target'].nunique()}")
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    with col2:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("#### Sample Datasets")
        
        sample_options = {
            "Kepler Dataset": "26 features, 3 classes",
            "K2 Dataset": "14 features, 3 classes", 
            "TESS Dataset": "18 features, 3 classes",
            "Combined Dataset": "32 features, 3 classes"
        }
        
        selected_sample = st.selectbox("Load sample:", list(sample_options.keys()), key="sample_template_training")
        
        if st.button("๐Ÿ“‹ Load Sample", use_container_width=True, key="load_sample_training"):
            st.session_state.training_data = pd.DataFrame({
                'feature_1': np.random.randn(100),
                'feature_2': np.random.randn(100),
                'target': np.random.choice([0, 1, 2], 100)
            })
            st.success(f"โœ… {selected_sample} loaded!")
        
        st.markdown("**Requirements:**")
        st.markdown("- CSV or Excel format")
        st.markdown("- Last column as target")
        st.markdown("- No missing values")
        st.markdown("- Numeric features only")
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    # ========================================================================
    # SECTION 2: MODEL SELECTION
    # ========================================================================
    
    if st.session_state.training_data is not None:
        st.markdown("### ๐Ÿค– Step 2: Model Configuration")
        
        model_col1, model_col2 = st.columns([1, 1])
        
        with model_col1:
            st.markdown('<div class="feature-box">', unsafe_allow_html=True)
            st.markdown("#### Classification Algorithm")
            
            model_type = st.selectbox(
                "Select Model:",
                ["Random Forest", "Gradient Boosting", "Support Vector Machine", "Logistic Regression"],
                help="Choose the classification algorithm"
            )
            
            # Model-specific information
            model_info = {
                "Random Forest": "Ensemble method, good for mixed data types, handles overfitting well",
                "Gradient Boosting": "Sequential ensemble, high accuracy, can overfit with small datasets",
                "Support Vector Machine": "Good for high-dimensional data, requires feature scaling",
                "Logistic Regression": "Linear model, fast training, good baseline, interpretable"
            }
            
            st.info(f"**{model_type}:** {model_info[model_type]}")
            
            st.markdown('</div>', unsafe_allow_html=True)
        
        with model_col2:
            st.markdown('<div class="feature-box">', unsafe_allow_html=True)
            st.markdown("#### Training Configuration")
            
            # Training parameters
            test_size = st.slider("Test Split Ratio", 0.1, 0.4, 0.2, 0.05, 
                                help="Percentage of data for testing")
            
            random_state = st.number_input("Random State", 0, 1000, 42,
                                         help="For reproducible results")
            
            cv_folds = st.selectbox("Cross-Validation Folds", [3, 5, 10], index=1,
                                  help="Number of CV folds for hyperparameter tuning")
            
            st.markdown('</div>', unsafe_allow_html=True)
    
    # ========================================================================
    # SECTION 3: HYPERPARAMETER TUNING
    # ========================================================================
    
    if st.session_state.training_data is not None:
        st.markdown("### โš™๏ธ Step 3: Hyperparameter Tuning")
        
        # Create tabs for different tuning methods
        tune_tab1, tune_tab2, tune_tab3 = st.tabs([
            "๐Ÿ”ง Manual Tuning",
            "๐Ÿ” Grid Search", 
            "๐ŸŽฒ Random Search"
        ])
        
        with tune_tab1:
            st.markdown("#### Manual Hyperparameter Configuration")
            
            if model_type == "Random Forest":
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    n_estimators = st.slider("Number of Trees", 10, 500, 100, 10)
                    max_depth = st.slider("Max Depth", 3, 20, 10)
                
                with col2:
                    min_samples_split = st.slider("Min Samples Split", 2, 20, 5)
                    min_samples_leaf = st.slider("Min Samples Leaf", 1, 10, 2)
                
                with col3:
                    max_features = st.selectbox("Max Features", ["sqrt", "log2", "auto"])
                    bootstrap = st.checkbox("Bootstrap", value=True)
            
            elif model_type == "Gradient Boosting":
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    n_estimators = st.slider("Number of Boosting Stages", 50, 500, 100, 10)
                    learning_rate = st.slider("Learning Rate", 0.01, 0.3, 0.1, 0.01)
                
                with col2:
                    max_depth = st.slider("Max Depth", 3, 10, 6)
                    subsample = st.slider("Subsample", 0.5, 1.0, 1.0, 0.1)
                
                with col3:
                    min_samples_split = st.slider("Min Samples Split", 2, 20, 5)
                    min_samples_leaf = st.slider("Min Samples Leaf", 1, 10, 2)
            
            elif model_type == "Support Vector Machine":
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    C = st.slider("Regularization (C)", 0.1, 10.0, 1.0, 0.1)
                    kernel = st.selectbox("Kernel", ["rbf", "linear", "poly", "sigmoid"])
                
                with col2:
                    gamma = st.selectbox("Gamma", ["scale", "auto", "0.001", "0.01", "0.1", "1"])
                    degree = st.slider("Degree (for poly)", 2, 5, 3) if kernel == "poly" else 3
                
                with col3:
                    probability = st.checkbox("Enable Probability Estimates", value=True)
            
            else:  # Logistic Regression
                col1, col2, col3 = st.columns(3)
                
                with col1:
                    C = st.slider("Regularization (C)", 0.01, 10.0, 1.0, 0.01)
                    penalty = st.selectbox("Penalty", ["l1", "l2", "elasticnet"])
                
                with col2:
                    solver = st.selectbox("Solver", ["liblinear", "lbfgs", "newton-cg", "sag", "saga"])
                    max_iter = st.slider("Max Iterations", 100, 2000, 1000, 100)
                
                with col3:
                    random_state = st.number_input("Random State", 0, 1000, 42)
        
        with tune_tab2:
            st.markdown("#### Grid Search Configuration")
            
            st.info("๐Ÿ” Grid search will test all combinations of specified parameters")
            
            # Parameter grid configuration
            param_grid = {}
            
            if model_type == "Random Forest":
                param_grid = {
                    "n_estimators": [50, 100, 200],
                    "max_depth": [5, 10, 15],
                    "min_samples_split": [2, 5, 10],
                    "min_samples_leaf": [1, 2, 4]
                }
            elif model_type == "Gradient Boosting":
                param_grid = {
                    "n_estimators": [50, 100, 200],
                    "learning_rate": [0.05, 0.1, 0.2],
                    "max_depth": [3, 5, 7],
                    "subsample": [0.8, 0.9, 1.0]
                }
            elif model_type == "Support Vector Machine":
                param_grid = {
                    "C": [0.1, 1, 10],
                    "kernel": ["rbf", "linear"],
                    "gamma": ["scale", "auto"]
                }
            else:  # Logistic Regression
                param_grid = {
                    "C": [0.1, 1, 10],
                    "penalty": ["l1", "l2"],
                    "solver": ["liblinear", "lbfgs"]
                }
            
            st.json(param_grid)
            
            # Grid search options
            col1, col2 = st.columns(2)
            with col1:
                scoring = st.selectbox("Scoring Metric", ["accuracy", "f1", "precision", "recall"], key="scoring_grid_search")
            with col2:
                n_jobs = st.slider("Parallel Jobs", 1, 4, 1)
        
        with tune_tab3:
            st.markdown("#### Random Search Configuration")
            
            st.info("๐ŸŽฒ Random search samples random combinations for faster tuning")
            
            # Random search configuration
            col1, col2 = st.columns(2)
            with col1:
                n_iter = st.slider("Number of Iterations", 10, 100, 50, 10)
            with col2:
                scoring = st.selectbox("Scoring Metric", ["accuracy", "f1", "precision", "recall"], key="scoring_random_search")
            
            # Parameter distributions
            param_dist = {}
            if model_type == "Random Forest":
                param_dist = {
                    "n_estimators": [50, 100, 200, 300, 500],
                    "max_depth": [3, 5, 7, 10, 15, 20],
                    "min_samples_split": [2, 5, 10, 15, 20],
                    "min_samples_leaf": [1, 2, 4, 6, 8, 10]
                }
            
            st.json(param_dist)
    
    # ========================================================================
    # SECTION 4: MODEL TRAINING
    # ========================================================================
    
    if st.session_state.training_data is not None:
        st.markdown("### ๐Ÿš€ Step 4: Train Model")
        
        train_col1, train_col2, train_col3 = st.columns([1, 1, 1])
        
        with train_col1:
            if st.button("๐ŸŽฏ Train Model", use_container_width=True, type="primary"):
                # Simulate training process
                progress_bar = st.progress(0)
                status_text = st.empty()
                
                # Training simulation
                steps = [
                    "Loading data...",
                    "Preprocessing features...",
                    "Splitting dataset...",
                    "Initializing model...",
                    "Training model...",
                    "Cross-validation...",
                    "Hyperparameter tuning...",
                    "Evaluating performance...",
                    "Saving model...",
                    "Training complete!"
                ]
                
                for i, step in enumerate(steps):
                    status_text.text(step)
                    progress_bar.progress((i + 1) / len(steps))
                    import time
                    time.sleep(0.5)
                
                # Simulate results
                st.session_state.trained_model = {
                    'type': model_type,
                    'accuracy': np.random.uniform(0.85, 0.95),
                    'precision': np.random.uniform(0.80, 0.90),
                    'recall': np.random.uniform(0.82, 0.88),
                    'f1_score': np.random.uniform(0.81, 0.89)
                }
                
                st.success("โœ… Model trained successfully!")
        
        with train_col2:
            if st.button("๐Ÿ“Š View Results", use_container_width=True):
                if st.session_state.trained_model:
                    st.markdown("**Training Results:**")
                    model = st.session_state.trained_model
                    st.metric("Accuracy", f"{model['accuracy']*100:.2f}%")
                    st.metric("Precision", f"{model['precision']*100:.2f}%")
                    st.metric("Recall", f"{model['recall']*100:.2f}%")
                    st.metric("F1-Score", f"{model['f1_score']*100:.2f}%")
                else:
                    st.warning("No trained model available. Train a model first.")
        
        with train_col3:
            if st.button("๐Ÿ’พ Save Model", use_container_width=True):
                if st.session_state.trained_model:
                    # Simulate model saving
                    model_name = f"custom_model_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
                    st.success(f"โœ… Model saved as {model_name}.joblib")
                else:
                    st.warning("No trained model to save.")
    
    # ========================================================================
    # SECTION 5: MODEL COMPARISON
    # ========================================================================
    
    if st.session_state.training_data is not None:
        st.markdown("### ๐Ÿ“ˆ Step 5: Model Performance Analysis")
        
        perf_col1, perf_col2 = st.columns([2, 1])
        
        with perf_col1:
            st.markdown("#### Performance Metrics")
            
            # Simulate performance comparison
            models_comparison = pd.DataFrame({
                'Model': ['Random Forest', 'Gradient Boosting', 'SVM', 'Logistic Regression'],
                'Accuracy': [0.92, 0.89, 0.87, 0.84],
                'Precision': [0.90, 0.88, 0.85, 0.82],
                'Recall': [0.88, 0.86, 0.83, 0.80],
                'F1-Score': [0.89, 0.87, 0.84, 0.81]
            })
            
            st.dataframe(models_comparison, use_container_width=True, hide_index=True)
            
            # Performance visualization
            fig = go.Figure()
            
            metrics = ['Accuracy', 'Precision', 'Recall', 'F1-Score']
            colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728']
            
            for i, metric in enumerate(metrics):
                fig.add_trace(go.Bar(
                    x=models_comparison['Model'],
                    y=models_comparison[metric],
                    name=metric,
                    marker_color=colors[i]
                ))
            
            fig.update_layout(
                title="Model Performance Comparison",
                xaxis_title="Models",
                yaxis_title="Score",
                barmode='group',
                height=400
            )
            
            st.plotly_chart(fig, use_container_width=True)
        
        with perf_col2:
            st.markdown("#### Training Summary")
            
            if st.session_state.trained_model:
                model = st.session_state.trained_model
                
                st.markdown("**Best Model:**")
                st.success(f"**{model['type']}**")
                
                st.markdown("**Key Metrics:**")
                st.metric("Accuracy", f"{model['accuracy']*100:.1f}%")
                st.metric("F1-Score", f"{model['f1_score']*100:.1f}%")
                
                st.markdown("**Recommendations:**")
                if model['accuracy'] > 0.9:
                    st.success("โœ… Excellent performance!")
                elif model['accuracy'] > 0.8:
                    st.info("โ„น๏ธ Good performance, consider tuning")
                else:
                    st.warning("โš ๏ธ Consider different algorithm")
            else:
                st.info("Train a model to see summary")
    
    # ========================================================================
    # SECTION 6: EXPORT AND DEPLOYMENT
    # ========================================================================
    
    if st.session_state.training_data is not None:
        st.markdown("### ๐Ÿ”„ Step 6: Export & Deployment")
        
        export_col1, export_col2, export_col3, export_col4 = st.columns(4)
        
        with export_col1:
            if st.button("๐Ÿ“ฅ Export Model", use_container_width=True):
                st.success("โœ… Model exported to .joblib file")
        
        with export_col2:
            if st.button("๐Ÿ“Š Export Results", use_container_width=True):
                st.success("โœ… Results exported to CSV")
        
        with export_col3:
            if st.button("๐Ÿ“‹ Export Report", use_container_width=True, key="export_report_training"):
                st.success("โœ… Training report exported")
        
        with export_col4:
            if st.button("๐Ÿš€ Deploy Model", use_container_width=True):
                st.success("โœ… Model deployed to production")


# ============================================================================
# TAB 3: MODEL PERFORMANCE DASHBOARD
# ============================================================================

with tab3:
    st.markdown("## ๐Ÿ“ˆ Model Performance Dashboard")
    st.markdown("Comprehensive metrics and visualizations for each trained model")
    
    # Model selector for performance view
    perf_col1, perf_col2 = st.columns([1, 3])
    
    with perf_col1:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("### Select Model")
        
        selected_model = st.selectbox(
            "Choose model to analyze:",
            list(MODEL_CONFIG.keys()),
            key="performance_model_select"
        )
        
        if selected_model in MODEL_CONFIG:
            config = MODEL_CONFIG[selected_model]
            st.info(f"**{config['description']}**")
            st.metric("Features", len(config['features']))
            st.metric("Classes", len(config['class_names']))
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    with perf_col2:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("### Quick Metrics Summary")
        
        if selected_model in MODEL_CONFIG and 'metrics' in MODEL_CONFIG[selected_model]:
            metrics = MODEL_CONFIG[selected_model]['metrics']
            
            metric_col1, metric_col2, metric_col3, metric_col4, metric_col5 = st.columns(5)
            
            with metric_col1:
                st.metric("Accuracy", f"{metrics['accuracy']*100:.2f}%")
            
            with metric_col2:
                st.metric("Precision (W)", f"{metrics['precision_weighted']*100:.2f}%")
            
            with metric_col3:
                st.metric("Recall (W)", f"{metrics['recall_weighted']*100:.2f}%")
            
            with metric_col4:
                st.metric("F1-Score (W)", f"{metrics['f1_weighted']*100:.2f}%")
            
            with metric_col5:
                st.metric("CV Score", f"{metrics['cv_score']*100:.2f}%")
        else:
            st.warning("No performance metrics available for this model")
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    # Only show detailed metrics if model has metrics data
    if selected_model in MODEL_CONFIG and 'metrics' in MODEL_CONFIG[selected_model]:
        metrics = MODEL_CONFIG[selected_model]['metrics']
        
        st.markdown("---")
        
        # ====================================================================
        # SECTION 1: OVERALL PERFORMANCE METRICS
        # ====================================================================
        
        st.markdown("### ๐Ÿ“Š Overall Performance Metrics")
        
        viz_col1, viz_col2 = st.columns(2)
        
        with viz_col1:
            # Macro vs Weighted Comparison - Grouped Bar Chart
            st.markdown("## Macro vs Weighted Metrics")
            
            categories = ['Precision', 'Recall', 'F1-Score']
            macro_values = [
                metrics['precision_macro'],
                metrics['recall_macro'],
                metrics['f1_macro']
            ]
            weighted_values = [
                metrics['precision_weighted'],
                metrics['recall_weighted'],
                metrics['f1_weighted']
            ]
            
            fig = go.Figure()
            
            fig.add_trace(go.Bar(
                name='Macro Average',
                x=categories,
                y=macro_values,
                marker_color='#1f77b4',
                text=[f'{v*100:.2f}%' for v in macro_values],
                textposition='auto'
            ))  
            
            fig.add_trace(go.Bar(
                name='Weighted Average',
                x=categories,
                y=weighted_values,
                marker_color='#2ca02c',
                text=[f'{v*100:.2f}%' for v in weighted_values],
                textposition='auto'
                
            ))
            
            fig.update_layout(
                barmode='group',
                yaxis_title='Score',
                yaxis=dict(range=[0, 1.05]),
                height=400,
                showlegend=True,
                legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
            )
            
            st.plotly_chart(fig, use_container_width=True)
            
            st.info("๐Ÿ’ก **Macro**: Unweighted mean (treats all classes equally)\n\n**Weighted**: Accounts for class imbalance")
        
        with viz_col2:
            # Overall Metrics - Gauge Charts
            st.markdown("#### Key Performance Indicators")
            
            # Create gauge chart for accuracy
            fig = go.Figure()
            
            fig.add_trace(go.Indicator(
                mode="gauge+number+delta",
                value=metrics['accuracy'] * 100,
                title={'text': "Overall Accuracy"},
                delta={'reference': 95, 'increasing': {'color': "green"}},
                gauge={
                    'axis': {'range': [None, 100]},
                    'bar': {'color': "#1f77b4"},
                    'steps': [
                        {'range': [0, 70], 'color': "#ffcccc"},
                        {'range': [70, 85], 'color': "#ffffcc"},
                        {'range': [85, 100], 'color': "#ccffcc"}
                    ],
                    'threshold': {
                        'line': {'color': "red", 'width': 4},
                        'thickness': 0.75,
                        'value': 95
                    }
                },
                domain={'x': [0, 1], 'y': [0.5, 1]}
            ))
            
            fig.add_trace(go.Indicator(
                mode="gauge+number",
                value=metrics['cv_score'] * 100,
                title={'text': "Cross-Validation Score"},
                gauge={
                    'axis': {'range': [None, 100]},
                    'bar': {'color': "#2ca02c"},
                    'steps': [
                        {'range': [0, 70], 'color': "#ffcccc"},
                        {'range': [70, 85], 'color': "#ffffcc"},
                        {'range': [85, 100], 'color': "#ccffcc"}
                    ]
                },
                domain={'x': [0, 1], 'y': [0, 0.4]}
            ))

            fig.update_layout(height=400, margin={'t': 0, 'b': 0, 'l': 0, 'r': 0})

            st.plotly_chart(fig, use_container_width=True)
        
        st.markdown("---")
        
        # ====================================================================
        # SECTION 2: PER-CLASS PERFORMANCE
        # ====================================================================
        
        st.markdown("### ๐ŸŽฏ Per-Class Performance Analysis")
        
        class_col1, class_col2 = st.columns([2, 1])
        
        with class_col1:
            # Per-class metrics - Radar Chart
            st.markdown("#### Class-wise Metrics Comparison")
            
            class_names = list(metrics['class_metrics'].keys())
            
            fig = go.Figure()
            
            for class_name in class_names:
                class_data = metrics['class_metrics'][class_name]
                
                fig.add_trace(go.Scatterpolar(
                    r=[
                        class_data['precision'],
                        class_data['recall'],
                        class_data['f1'],
                        class_data['sensitivity'],
                        class_data['specificity']
                    ],
                    theta=['Precision', 'Recall', 'F1-Score', 'Sensitivity', 'Specificity'],
                    fill='toself',
                    name=class_name
                ))
            
            fig.update_layout(
                polar=dict(
                    radialaxis=dict(
                        visible=True,
                        range=[0, 1]
                    )
                ),
                showlegend=True,
                height=500,
                legend=dict(orientation="h", yanchor="bottom", y=-0.15, xanchor="center", x=0.5)
            )
            
            st.plotly_chart(fig, use_container_width=True)
        
        with class_col2:
            # Class-wise detailed metrics table
            st.markdown("#### Detailed Class Metrics")
            
            class_metrics_data = []
            for class_name, class_data in metrics['class_metrics'].items():
                class_metrics_data.append({
                    'Class': class_name,
                    'Precision': f"{class_data['precision']*100:.1f}%",
                    'Recall': f"{class_data['recall']*100:.1f}%",
                    'F1-Score': f"{class_data['f1']*100:.1f}%",
                    'Support': class_data['support']
                })
            
            class_df = pd.DataFrame(class_metrics_data)
            st.dataframe(class_df, use_container_width=True, hide_index=True)
            
            st.markdown("---")
            
            # Sensitivity & Specificity
            st.markdown("#### Sensitivity & Specificity")
            
            for class_name, class_data in metrics['class_metrics'].items():
                st.markdown(f"**{class_name}**")
                col1, col2 = st.columns(2)
                with col1:
                    st.metric("Sensitivity", f"{class_data['sensitivity']*100:.2f}%")
                with col2:
                    st.metric("Specificity", f"{class_data['specificity']*100:.2f}%")
        
        st.markdown("---")
        
        # ====================================================================
        # SECTION 3: CONFUSION MATRIX
        # ====================================================================
        
        st.markdown("### ๐Ÿ”ข Confusion Matrix Analysis")
        
        cm_col1, cm_col2 = st.columns([2, 1])
        
        with cm_col1:
            # Confusion Matrix Heatmap
            st.markdown("#### Confusion Matrix")
            
            cm = np.array(metrics['confusion_matrix'])
            class_labels = list(metrics['class_metrics'].keys())
            
            # Calculate percentages
            cm_percent = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100
            
            # Create annotations with both counts and percentages
            annotations = []
            for i in range(len(cm)):
                for j in range(len(cm[0])):
                    annotations.append(f"{cm[i][j]}<br>({cm_percent[i][j]:.1f}%)")
            
            annotations_array = np.array(annotations).reshape(cm.shape)
            
            fig = go.Figure(data=go.Heatmap(
                z=cm,
                x=class_labels,
                y=class_labels,
                text=annotations_array,
                texttemplate='%{text}',
                textfont={"size": 12},
                colorscale='Blues',
                showscale=True,
                colorbar=dict(title="Count")
            ))
            
            fig.update_layout(
                title="Confusion Matrix (Count & Percentage)",
                xaxis_title="Predicted Class",
                yaxis_title="True Class",
                height=500
            )
            
            st.plotly_chart(fig, use_container_width=True)
        
        with cm_col2:
            # Confusion Matrix Statistics
            st.markdown("#### Matrix Statistics")
            
            total_samples = np.sum(cm)
            correct_predictions = np.trace(cm)
            incorrect_predictions = total_samples - correct_predictions
            
            st.metric("Total Samples", f"{total_samples:,}")
            st.metric("Correct Predictions", f"{correct_predictions:,}")
            st.metric("Incorrect Predictions", f"{incorrect_predictions:,}")
            st.metric("Error Rate", f"{(incorrect_predictions/total_samples)*100:.2f}%")
            
            st.markdown("---")
            
            # Per-class accuracy
            st.markdown("#### Per-Class Accuracy")
            
            for i, class_name in enumerate(class_labels):
                class_accuracy = cm[i][i] / cm[i].sum() * 100
                st.progress(class_accuracy/100, text=f"{class_name}: {class_accuracy:.1f}%")
        
        st.markdown("---")
        
        # ====================================================================
        # SECTION 4: PRECISION-RECALL ANALYSIS
        # ====================================================================
        
        st.markdown("### โš–๏ธ Precision-Recall Analysis")
        
        pr_col1, pr_col2 = st.columns(2)
        
        with pr_col1:
            # Precision comparison across classes - Bar chart
            st.markdown("#### Precision by Class")
            
            class_names = list(metrics['class_metrics'].keys())
            precisions = [metrics['class_metrics'][cn]['precision'] for cn in class_names]
            
            fig = go.Figure()
            
            fig.add_trace(go.Bar(
                x=class_names,
                y=precisions,
                marker_color=['#28a745', '#ffc107', '#dc3545'],
                text=[f'{p*100:.1f}%' for p in precisions],
                textposition='auto',
            ))
            
            fig.update_layout(
                yaxis_title='Precision',
                yaxis=dict(range=[0, 1.05]),
                height=350
            )
            
            fig.add_hline(y=metrics['precision_weighted'], line_dash="dash", 
                         line_color="blue", annotation_text="Weighted Avg")
            
            st.plotly_chart(fig, use_container_width=True)
        
        with pr_col2:
            # Recall comparison across classes - Bar chart
            st.markdown("#### Recall by Class")
            
            recalls = [metrics['class_metrics'][cn]['recall'] for cn in class_names]
            
            fig = go.Figure()
            
            fig.add_trace(go.Bar(
                x=class_names,
                y=recalls,
                marker_color=['#28a745', '#ffc107', '#dc3545'],
                text=[f'{r*100:.1f}%' for r in recalls],
                textposition='auto',
            ))
            
            fig.update_layout(
                yaxis_title='Recall',
                yaxis=dict(range=[0, 1.05]),
                height=350
            )
            
            fig.add_hline(y=metrics['recall_weighted'], line_dash="dash", 
                         line_color="blue", annotation_text="Weighted Avg")
            
            st.plotly_chart(fig, use_container_width=True)
        
        # F1-Score comparison
        st.markdown("#### F1-Score by Class")
        
        f1_scores = [metrics['class_metrics'][cn]['f1'] for cn in class_names]
        
        fig = go.Figure()
        
        fig.add_trace(go.Bar(
            x=class_names,
            y=f1_scores,
            marker_color=['#28a745', '#ffc107', '#dc3545'],
            text=[f'{f*100:.1f}%' for f in f1_scores],
            textposition='auto',
        ))
        
        fig.update_layout(
            yaxis_title='F1-Score',
            yaxis=dict(range=[0, 1.05]),
            height=300
        )
        
        fig.add_hline(y=metrics['f1_weighted'], line_dash="dash", 
                     line_color="blue", annotation_text="Weighted Avg")
        
        st.plotly_chart(fig, use_container_width=True)
        
        st.markdown("---")
        
        # ====================================================================
        # SECTION 5: CLASS BALANCE & SUPPORT
        # ====================================================================
        
        st.markdown("### ๐Ÿ“ฆ Class Distribution & Support")
        
        support_col1, support_col2 = st.columns(2)
        
        with support_col1:
            # Class distribution - Pie chart
            st.markdown("#### Sample Distribution")
            
            supports = [metrics['class_metrics'][cn]['support'] for cn in class_names]
            
            fig = go.Figure(data=[go.Pie(
                labels=class_names,
                values=supports,
                hole=0.4,
                marker=dict(colors=['#28a745', '#ffc107', '#dc3545']),
                textinfo='label+percent+value',
                textfont=dict(size=12)
            )])
            
            fig.update_layout(
                title="Class Distribution in Test Set",
                height=400
            )
            
            st.plotly_chart(fig, use_container_width=True)
        
        with support_col2:
            # Support comparison - Bar chart
            st.markdown("#### Support by Class")
            
            fig = go.Figure()
            
            fig.add_trace(go.Bar(
                x=class_names,
                y=supports,
                marker_color=['#28a745', '#ffc107', '#dc3545'],
                text=supports,
                textposition='auto',
            ))
            
            fig.update_layout(
                yaxis_title='Number of Samples',
                height=400
            )
            
            st.plotly_chart(fig, use_container_width=True)
            
            # Class imbalance ratio
            st.markdown("**Class Imbalance Ratio**")
            max_support = max(supports)
            for class_name, support in zip(class_names, supports):
                ratio = support / max_support
                st.progress(ratio, text=f"{class_name}: {support} samples ({ratio*100:.1f}%)")
        
        st.markdown("---")
        
        # ====================================================================
        # SECTION 6: MODEL INSIGHTS & RECOMMENDATIONS
        # ====================================================================
        
        st.markdown("### ๐Ÿ’ก Model Insights & Recommendations")
        
        insight_col1, insight_col2 = st.columns(2)
        
        with insight_col1:
            st.markdown('<div class="feature-box">', unsafe_allow_html=True)
            st.markdown("#### Model Strengths")
            
            strengths = []
            
            if metrics['accuracy'] >= 0.95:
                strengths.append("โœ… Excellent overall accuracy (โ‰ฅ95%)")
            
            if metrics['f1_weighted'] >= 0.95:
                strengths.append("โœ… High weighted F1-score indicating balanced performance")
            
            if metrics['cv_score'] >= 0.95:
                strengths.append("โœ… Strong cross-validation score shows good generalization")
            
            # Check if all class recalls are good
            if all(metrics['class_metrics'][cn]['recall'] >= 0.9 for cn in class_names[:-1]):
                strengths.append("โœ… High recall for major classes (low false negatives)")
            
            # Check precision for confirmed class
            if 'CONFIRMED' in metrics['class_metrics']:
                if metrics['class_metrics']['CONFIRMED']['precision'] >= 0.85:
                    strengths.append("โœ… Good precision for CONFIRMED class reduces false discoveries")
            
            for strength in strengths:
                st.markdown(strength)
            
            if not strengths:
                st.info("Model shows room for improvement across metrics")
            
            st.markdown('</div>', unsafe_allow_html=True)
        
        with insight_col2:
            st.markdown('<div class="feature-box">', unsafe_allow_html=True)
            st.markdown("#### Areas for Improvement")
            
            improvements = []
            
            # Find weakest class
            weakest_class = min(metrics['class_metrics'].items(), 
                              key=lambda x: x[1]['f1'])
            
            if weakest_class[1]['f1'] < 0.85:
                improvements.append(f"โš ๏ธ {weakest_class[0]} class has lower F1-score ({weakest_class[1]['f1']*100:.1f}%)")
            
            if weakest_class[1]['recall'] < 0.80:
                improvements.append(f"โš ๏ธ Low recall for {weakest_class[0]} - many false negatives")
            
            # Check class imbalance
            support_ratio = min(supports) / max(supports)
            if support_ratio < 0.2:
                improvements.append(f"โš ๏ธ Significant class imbalance (ratio: {support_ratio:.2f})")
                improvements.append("๐Ÿ’ก Consider oversampling minority class or using class weights")
            
            # Check if improvement metric exists
            if metrics.get('improvement', 0) < 0.02:
                improvements.append("๐Ÿ’ก Consider additional hyperparameter tuning for better performance")
            
            for improvement in improvements:
                st.markdown(improvement)
            
            if not improvements:
                st.success("Model performs well across all classes!")
            
            st.markdown('</div>', unsafe_allow_html=True)
        
        st.markdown("---")
        
        # ====================================================================
        # SECTION 7: EXPORT OPTIONS
        # ====================================================================
        
        st.markdown("### ๐Ÿ’พ Export Performance Report")
        
        export_col1, export_col2, export_col3, export_col4 = st.columns(4)
        
        with export_col1:
            if st.button("๐Ÿ“ฅ Export Metrics (CSV)", use_container_width=True):
                st.success("โœ… Metrics exported to CSV")
        
        with export_col2:
            if st.button("๐Ÿ“Š Export Visualizations", use_container_width=True):
                st.success("โœ… Charts exported as images")
        
        with export_col3:
            if st.button("๐Ÿ“„ Generate PDF Report", use_container_width=True):
                st.success("โœ… PDF report generated")
        
        with export_col4:
            if st.button("๐Ÿ“ง Email Report", use_container_width=True):
                st.success("โœ… Report sent via email")
    
    else:
        st.warning("โš ๏ธ No performance metrics available for this model. Please train the model first or load a model with metrics data.")

# ============================================================================
# TAB 4: BEGINNER GUIDE (PLACEHOLDER FOR FUTURE IMPLEMENTATION)
# ============================================================================
# ============================================================================
# TAB 4: BEGINNER'S GUIDE
# ============================================================================

with tab4:
    st.markdown("## ๐ŸŒŸ Welcome to Exoplanet Detection - A Beginner's Guide")
    st.markdown("Start your journey in discovering planets beyond our solar system!")
    
    # Hero section with call-to-action
    st.markdown("---")
    hero_col1, hero_col2 = st.columns([2, 1])
    
    with hero_col1:
        st.markdown("""
        ### ๐Ÿš€ New to Exoplanet Detection?
        
        Welcome! Exoplanets are planets that orbit stars outside our solar system. Discovering them is one of 
        the most exciting fields in modern astronomy. This guide will help you understand the basics and get 
        started with exoplanet detection.
        
        **What you'll learn:**
        - What exoplanets are and why they matter
        - How scientists detect them
        - The transit method explained simply
        - How to use this AI tool for detection
        - Real examples and practice exercises
        """)
    
    with hero_col2:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ“– Comprehensive Guide")
        st.markdown("Want more detailed information and interactive tutorials?")
        
        # Button to external guide
        st.link_button(
            "๐ŸŒ Open Full Beginner's Guide",
            "https://beginnerguideexoplanetdetect.netlify.app/",
            use_container_width=True,
            type="primary"
        )
        
        st.info("Our comprehensive guide includes interactive animations, quizzes, and detailed explanations perfect for beginners!")
        st.markdown('</div>', unsafe_allow_html=True)
    
    st.markdown("---")
    
    # ========================================================================
    # SECTION 1: WHAT ARE EXOPLANETS?
    # ========================================================================
    
    st.markdown("### ๐Ÿช What Are Exoplanets?")
    
    intro_col1, intro_col2 = st.columns([3, 2])
    
    with intro_col1:
        st.markdown("""
        **Exoplanets** (or extrasolar planets) are planets that exist outside our solar system. They orbit 
        stars other than our Sun.
        
        **Key Facts:**
        - First confirmed exoplanet discovered in 1992
        - Over 5,000 exoplanets confirmed to date
        - Thousands more candidates awaiting confirmation
        - Range from gas giants bigger than Jupiter to rocky planets smaller than Earth
        - Some may have conditions suitable for life!
        
        **Types of Exoplanets:**
        - **Hot Jupiters**: Gas giants very close to their stars
        - **Super-Earths**: Rocky planets larger than Earth
        - **Mini-Neptunes**: Smaller gas planets
        - **Earth-like planets**: Rocky planets in habitable zones
        """)
    
    with intro_col2:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("#### ๐ŸŽฏ Quick Stats")
        st.metric("Confirmed Exoplanets", "5,000+")
        st.metric("Stars with Planets", "3,700+")
        st.metric("Planetary Systems", "4,000+")
        st.metric("Habitable Zone Planets", "100+")
        st.markdown('</div>', unsafe_allow_html=True)
    
    st.markdown("---")
    
    # ========================================================================
    # SECTION 2: DETECTION METHODS EXPLAINED
    # ========================================================================
    
    st.markdown("### ๐Ÿ”ญ How Do We Find Exoplanets?")
    
    st.markdown("""
    Scientists use several methods to detect exoplanets. Here are the main techniques explained simply:
    """)
    
    method_tab1, method_tab2, method_tab3 = st.tabs([
        "๐ŸŒ— Transit Method",
        "๐ŸŽฏ Radial Velocity",
        "๐Ÿ” Other Methods"
    ])
    
    with method_tab1:
        transit_col1, transit_col2 = st.columns([2, 1])
        
        with transit_col1:
            st.markdown("""
            #### The Transit Method (What This Tool Uses!)
            
            **How it works:**
            1. We observe a star's brightness over time
            2. When a planet passes in front of the star (transits), it blocks some light
            3. This causes a tiny dip in the star's brightness
            4. We measure this dip to learn about the planet
            
            **What we can learn:**
            - Planet size (bigger planet = bigger dip)
            - Orbital period (time between transits)
            - Distance from star
            - Sometimes atmospheric composition!
            
            **Advantages:**
            - Can detect small planets
            - Provides accurate planet size
            - Works for distant stars
            
            **Limitations:**
            - Planet orbit must align with our view
            - Only works for planets that transit their star
            """)
        
        with transit_col2:
            st.markdown('<div class="success-box">', unsafe_allow_html=True)
            st.markdown("#### ๐Ÿ’ก Simple Analogy")
            st.markdown("""
            Imagine watching a light bulb with a fly flying around it. When the fly passes 
            directly between you and the bulb, the light dims slightly. By timing these dips, 
            you can figure out how often the fly circles the bulb!
            """)
            st.markdown('</div>', unsafe_allow_html=True)
            
            st.markdown('<div class="feature-box">', unsafe_allow_html=True)
            st.markdown("#### ๐Ÿ“Š Success Rate")
            st.markdown("~75% of exoplanets discovered using this method!")
            st.markdown('</div>', unsafe_allow_html=True)
    
    with method_tab2:
        st.markdown("""
        #### Radial Velocity Method (Wobble Detection)
        
        **How it works:**
        - Planets don't just orbit stars - the star and planet orbit their common center of mass
        - This causes the star to "wobble" slightly
        - The wobble changes the star's light wavelength (Doppler effect)
        - We detect these tiny wavelength shifts
        
        **What we can learn:**
        - Planet mass
        - Orbital period
        - Orbit shape (eccentricity)
        
        **Best for:** Detecting massive planets close to their stars
        """)
    
    with method_tab3:
        st.markdown("""
        #### Other Detection Methods
        
        **Direct Imaging:**
        - Actually taking pictures of exoplanets
        - Very difficult due to star brightness
        - Works best for large planets far from their stars
        
        **Gravitational Microlensing:**
        - Uses gravity as a magnifying glass
        - Star's gravity bends light from background star
        - Creates temporary brightening when planet is present
        
        **Astrometry:**
        - Precisely measuring star position changes
        - Star moves slightly due to planet's gravity
        - Requires extremely precise measurements
        """)
    
    st.markdown("---")
    
    # ========================================================================
    # SECTION 3: STEP-BY-STEP LEARNING PATH
    # ========================================================================
    
    st.markdown("### ๐Ÿ“š Your Learning Path: From Zero to Exoplanet Hunter")
    
    st.markdown("""
    Follow these steps to build your knowledge from the ground up:
    """)
    
    # Step 1
    st.markdown('<div class="feature-box">', unsafe_allow_html=True)
    st.markdown("""
    #### ๐ŸŽฏ Step 1: Understand Basic Astronomy Concepts (Week 1-2)
    
    **What to learn:**
    - What stars are and how they work
    - Our solar system structure
    - Light and how we study it
    - Basic physics concepts (gravity, orbits)
    
    **Recommended actions:**
    - Watch introductory astronomy videos (see resources below)
    - Read about our solar system
    - Learn about light and spectra
    
    **Success indicator:** You can explain what a star is and how planets orbit
    """)
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Step 2
    st.markdown('<div class="feature-box">', unsafe_allow_html=True)
    st.markdown("""
    #### ๐Ÿ”ฌ Step 2: Learn About Exoplanets (Week 2-3)
    
    **What to learn:**
    - What makes exoplanets different from solar system planets
    - Types of exoplanets
    - Why exoplanets are important
    - History of exoplanet discovery
    
    **Recommended actions:**
    - Visit NASA Exoplanet Archive
    - Read about famous exoplanet discoveries
    - Explore the [Full Beginner's Guide](https://beginnerguideexoplanetdetect.netlify.app/)
    
    **Success indicator:** You can name and describe different types of exoplanets
    """)
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Step 3
    st.markdown('<div class="feature-box">', unsafe_allow_html=True)
    st.markdown("""
    #### ๐Ÿ“Š Step 3: Understand the Transit Method (Week 3-4)
    
    **What to learn:**
    - How transit method works in detail
    - What a light curve is
    - How to interpret transit data
    - What parameters we measure
    
    **Recommended actions:**
    - Study light curve examples
    - Practice identifying transits in data
    - Learn about transit parameters (depth, duration, period)
    
    **Success indicator:** You can look at a light curve and identify a transit
    """)
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Step 4
    st.markdown('<div class="feature-box">', unsafe_allow_html=True)
    st.markdown("""
    #### ๐Ÿค– Step 4: Introduction to Machine Learning (Week 4-5)
    
    **What to learn:**
    - Basic concepts of AI and machine learning
    - How computers learn to classify data
    - What features and parameters mean
    - Understanding model predictions
    
    **Recommended actions:**
    - Watch machine learning basics videos
    - Understand classification vs prediction
    - Learn about training data
    
    **Success indicator:** You understand what the AI model does in this tool
    """)
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Step 5
    st.markdown('<div class="feature-box">', unsafe_allow_html=True)
    st.markdown("""
    #### ๐ŸŽฎ Step 5: Practice with This Tool (Week 5+)
    
    **What to do:**
    - Start with sample data in the Researcher Interface
    - Make your first prediction
    - Understand the output and recommendations
    - Try different parameters and see how results change
    - Compare your results with known exoplanets
    
    **Recommended actions:**
    - Load sample templates (Hot Jupiter, Super-Earth, etc.)
    - Read the AI recommendations carefully
    - Check the feature importance charts
    
    **Success indicator:** You can confidently use the tool and interpret results
    """)
    st.markdown('</div>', unsafe_allow_html=True)
    
    st.markdown("---")
    
    # ========================================================================
    # SECTION 4: VIDEO RESOURCES
    # ========================================================================
    
    st.markdown("### ๐Ÿ“บ Educational Video Resources")
    
    st.markdown("""
    Learn from these excellent YouTube videos and channels:
    """)
    
    video_col1, video_col2 = st.columns(2)
    
    with video_col1:
        st.markdown("#### ๐ŸŒŸ Getting Started Videos")
        
        st.markdown("""
        **1. What Are Exoplanets?**
        - [NASA: Exoplanet Exploration](https://www.youtube.com/watch?v=jW5RFhImPyw)
        - Duration: ~10 minutes
        - Perfect introduction to exoplanets
        
        **2. How Do We Find Exoplanets?**
        - [Crash Course Astronomy: Exoplanets](https://www.youtube.com/watch?v=DqTkPM5lWQk)
        - Duration: ~12 minutes
        - Covers detection methods
        
        **3. The Transit Method Explained**
        - [NASA: Transit Method Animation](https://www.youtube.com/watch?v=qHDyG4WAH2s)
        - Duration: ~5 minutes
        - Visual explanation of how transits work
        
        **4. Reading Light Curves**
        - Search: "NASA Light Curves Tutorial"
        - Duration: ~8 minutes
        - Learn to interpret transit data
        """)
    
    with video_col2:
        st.markdown("#### ๐ŸŽ“ Advanced Topics")
        
        st.markdown("""
        **5. Kepler Mission Overview**
        - [NASA Kepler: Planet Hunter](https://www.youtube.com/watch?v=3zVdYFQl_cQ)
        - Duration: ~15 minutes
        - Learn about NASA's planet-hunting telescope
        
        **6. Machine Learning in Astronomy**
        - Search: "AI for Exoplanet Detection"
        - Duration: ~20 minutes
        - How AI helps find planets
        
        **7. The Search for Habitable Worlds**
        - Search: "Are We Alone? The Search for Life"
        - Duration: ~25 minutes
        - Why exoplanets matter for finding life
        
        **8. Real Exoplanet Discoveries**
        - Search: "Amazing Exoplanet Discoveries"
        - Duration: ~18 minutes
        - Stories of fascinating planets found
        """)
    
    st.markdown("#### ๐ŸŽฌ Recommended YouTube Channels")
    
    channel_col1, channel_col2, channel_col3 = st.columns(3)
    
    with channel_col1:
        st.markdown("""
        **NASA**
        - Official NASA content
        - High-quality animations
        - Latest discoveries
        """)
    
    with channel_col2:
        st.markdown("""
        **PBS Space Time**
        - In-depth explanations
        - Advanced concepts
        - Expert presenters
        """)
    
    with channel_col3:
        st.markdown("""
        **Crash Course**
        - Beginner-friendly
        - Full astronomy series
        - Engaging presentations
        """)
    
    st.markdown("---")
    
    # ========================================================================
    # SECTION 5: KEY CONCEPTS GLOSSARY
    # ========================================================================
    
    st.markdown("### ๐Ÿ“– Essential Terms to Know")
    
    glossary_col1, glossary_col2 = st.columns(2)
    
    with glossary_col1:
        st.markdown("""
        **Transit:** When a planet passes in front of its star from our viewpoint
        
        **Light Curve:** A graph showing how a star's brightness changes over time
        
        **Transit Depth:** How much light is blocked during a transit (tells us planet size)
        
        **Orbital Period:** Time it takes a planet to complete one orbit around its star
        
        **Transit Duration:** How long the planet takes to cross in front of the star
        
        **Habitable Zone:** The region around a star where liquid water could exist
        
        **False Positive:** A signal that looks like a planet but isn't (like an eclipsing binary star)
        
        **Candidate:** A potential exoplanet that needs more observation to confirm
        """)
    
    with glossary_col2:
        st.markdown("""
        **Confirmed Planet:** An exoplanet verified through multiple observations
        
        **Stellar Parameters:** Properties of the host star (temperature, size, brightness)
        
        **Planet Radius:** Size of the planet compared to Earth or Jupiter
        
        **Equilibrium Temperature:** Expected temperature of the planet's surface
        
        **Impact Parameter:** How close to the star's center the planet passes
        
        **Signal-to-Noise Ratio (SNR):** How strong the planet signal is compared to noise
        
        **Model:** In AI, the trained system that classifies new observations
        
        **Feature:** A measurable property used by the AI to make predictions
        """)
    
    st.markdown("---")
    
    # ========================================================================
    # SECTION 6: PRACTICE EXERCISES
    # ========================================================================
    
    st.markdown("### ๐ŸŽฏ Quick Knowledge Check")
    
    st.markdown("""
    Test your understanding with these simple questions:
    """)
    
    with st.expander("โ“ Question 1: What is an exoplanet?"):
        q1_answer = st.radio(
            "Select your answer:",
            [
                "A planet in our solar system",
                "A planet outside our solar system",
                "A type of star",
                "A moon orbiting Jupiter"
            ],
            key="q1"
        )
        if st.button("Check Answer", key="check_q1"):
            if "outside our solar system" in q1_answer:
                st.success("โœ… Correct! Exoplanets orbit stars other than our Sun.")
            else:
                st.error("โŒ Not quite. Review the 'What Are Exoplanets?' section above.")
    
    with st.expander("โ“ Question 2: How does the transit method work?"):
        q2_answer = st.radio(
            "Select your answer:",
            [
                "We take pictures of the planet",
                "We measure the star's wobble",
                "We detect dips in star brightness when planet passes in front",
                "We listen to radio signals from the planet"
            ],
            key="q2"
        )
        if st.button("Check Answer", key="check_q2"):
            if "dips in star brightness" in q2_answer:
                st.success("โœ… Correct! The transit method detects light dips when planets block their star's light.")
            else:
                st.error("โŒ Not quite. Review the 'Transit Method' section above.")
    
    with st.expander("โ“ Question 3: What does transit depth tell us?"):
        q3_answer = st.radio(
            "Select your answer:",
            [
                "Planet's color",
                "Planet's temperature",
                "Planet's size",
                "Planet's age"
            ],
            key="q3"
        )
        if st.button("Check Answer", key="check_q3"):
            if "size" in q3_answer:
                st.success("โœ… Correct! Transit depth is related to planet size - bigger planets block more light.")
            else:
                st.error("โŒ Not quite. Think about how much light a planet blocks.")
    
    st.markdown("---")
    
    # ========================================================================
    # SECTION 7: NEXT STEPS & RESOURCES
    # ========================================================================
    
    st.markdown("### ๐Ÿš€ Ready to Get Started?")
    
    next_col1, next_col2, next_col3 = st.columns(3)
    
    with next_col1:
        st.markdown('<div class="success-box">', unsafe_allow_html=True)
        st.markdown("""
        #### ๐Ÿ“– Learn More
        
        Visit our comprehensive guide for interactive tutorials and detailed explanations
        """)
        st.link_button(
            "Open Full Guide",
            "https://beginnerguideexoplanetdetect.netlify.app/",
            use_container_width=True
        )
        st.markdown('</div>', unsafe_allow_html=True)
    
    with next_col2:
        st.markdown('<div class="recommendation-box">', unsafe_allow_html=True)
        st.markdown("""
        #### ๐Ÿ”ฌ Start Detecting
        
        Head to the Researcher Interface and try making your first prediction!
        """)
        if st.button("Go to Researcher Interface", use_container_width=True, key="goto_researcher"):
            st.info("Switch to the 'Researcher Interface' tab above to begin!")
        st.markdown('</div>', unsafe_allow_html=True)
    
    with next_col3:
        st.markdown('<div class="feature-box">', unsafe_allow_html=True)
        st.markdown("""
        #### ๐ŸŒ Explore NASA Resources
        
        Visit NASA's official exoplanet exploration website
        """)
        st.link_button(
            "NASA Exoplanets",
            "https://exoplanets.nasa.gov/",
            use_container_width=True
        )
        st.markdown('</div>', unsafe_allow_html=True)
    
    st.markdown("---")
    
    # Additional resources section
    st.markdown("### ๐Ÿ“š Additional Learning Resources")
    
    resource_col1, resource_col2 = st.columns(2)
    
    with resource_col1:
        st.markdown("""
        #### ๐ŸŒ Websites & Databases
        - [NASA Exoplanet Archive](https://exoplanetarchive.ipac.caltech.edu/) - Search confirmed exoplanets
        - [Exoplanet.eu](http://exoplanet.eu/) - European exoplanet database
        - [PlanetHunters](https://www.zooniverse.org/projects/nora-dot-eisner/planet-hunters-tess) - Citizen science project
        - [Eyes on Exoplanets](https://eyes.nasa.gov/apps/exo/) - 3D interactive visualization
        """)
    
    with resource_col2:
        st.markdown("""
        #### ๐Ÿ“ฑ Apps & Tools
        - Exoplanet (iOS/Android) - Interactive app
        - Star Walk 2 - Stargazing app
        - SkySafari - Advanced astronomy app
        - NASA App - Latest space news
        """)
    
    st.markdown("---")
    
    st.markdown("""
    ### ๐Ÿ’ฌ Have Questions?
    
    **Remember:** Everyone starts as a beginner! Don't be afraid to:
    - Ask questions in astronomy forums
    - Revisit concepts multiple times
    - Practice with sample data
    - Join online astronomy communities
    
    **Suggested Communities:**
    - r/astronomy on Reddit
    - r/exoplanets on Reddit
    - NASA's Exoplanet Exploration forums
    - Astronomy Stack Exchange
    
    Happy planet hunting! ๐ŸŒŸ๐Ÿ”ญ
    """)

# ============================================================================
# FOOTER
# ============================================================================
# ============================================================================
# FOOTER
# ============================================================================

st.markdown("---")
footer_col1, footer_col2, footer_col3 = st.columns(3)

with footer_col1:
    st.markdown("**๐Ÿ“š Resources**")
    st.markdown("- [NASA Exoplanet Archive](https://exoplanetarchive.ipac.caltech.edu/)")
    st.markdown("- [Kepler Mission](https://www.nasa.gov/mission_pages/kepler/main/index.html)")

with footer_col2:
    st.markdown("**๐Ÿ”— Quick Links**")
    st.markdown("- Documentation")
    st.markdown("- API Reference")

with footer_col3:
    st.markdown("**โ„น๏ธ About**")
    st.markdown("Version 1.0.0")
    st.markdown("ยฉ 2024 Exoplanet Detection System")