File size: 68,350 Bytes
f829ab1
 
 
 
 
 
 
 
 
4155a5d
 
f829ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
4155a5d
 
 
 
 
 
f829ab1
4155a5d
f829ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
4155a5d
 
 
 
 
 
 
 
 
 
f829ab1
 
 
 
4155a5d
f829ab1
 
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
f829ab1
 
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
 
 
 
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
4155a5d
 
f829ab1
 
 
 
 
 
 
 
4155a5d
f829ab1
4155a5d
 
f829ab1
 
 
4155a5d
f829ab1
 
 
 
 
4155a5d
f829ab1
4155a5d
 
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
f829ab1
4155a5d
 
 
 
f829ab1
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
f829ab1
 
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
f829ab1
 
 
 
 
 
 
 
 
4155a5d
f829ab1
 
4155a5d
 
f829ab1
 
 
 
 
4155a5d
f829ab1
4155a5d
 
 
 
f829ab1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4155a5d
 
f829ab1
 
 
 
 
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
f829ab1
4155a5d
 
f829ab1
 
 
 
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
 
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
f829ab1
 
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
f829ab1
4155a5d
 
 
 
f829ab1
 
4155a5d
 
f829ab1
4155a5d
f829ab1
 
4155a5d
f829ab1
4155a5d
 
 
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
4155a5d
 
f829ab1
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
f829ab1
4155a5d
 
f829ab1
 
 
 
 
 
 
 
 
 
 
 
4155a5d
 
 
 
f829ab1
 
 
4155a5d
f829ab1
 
4155a5d
 
 
 
f829ab1
 
 
 
4155a5d
f829ab1
4155a5d
 
 
 
f829ab1
 
 
 
 
 
 
 
4155a5d
 
 
 
f829ab1
 
 
 
 
 
4155a5d
 
 
 
f829ab1
 
 
4155a5d
f829ab1
 
4155a5d
 
 
 
f829ab1
 
 
 
 
4155a5d
f829ab1
 
4155a5d
 
 
 
f829ab1
 
 
4155a5d
 
f829ab1
4155a5d
 
 
 
f829ab1
 
 
 
 
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
 
4155a5d
f829ab1
 
4155a5d
f829ab1
 
 
 
4155a5d
 
 
f829ab1
4155a5d
f829ab1
 
 
4155a5d
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
4155a5d
f829ab1
 
 
 
 
 
 
 
 
 
 
4155a5d
f829ab1
 
4155a5d
f829ab1
4155a5d
f829ab1
 
 
 
 
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
f829ab1
4155a5d
f829ab1
 
4155a5d
f829ab1
 
 
 
 
4155a5d
 
 
 
 
 
 
f829ab1
 
4155a5d
f829ab1
4155a5d
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
 
 
 
 
4155a5d
f829ab1
 
4155a5d
f829ab1
4155a5d
 
 
f829ab1
4155a5d
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
f829ab1
 
4155a5d
f829ab1
4155a5d
 
 
f829ab1
4155a5d
f829ab1
4155a5d
 
 
 
 
f829ab1
4155a5d
 
 
 
 
f829ab1
4155a5d
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
f829ab1
 
 
 
 
4155a5d
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
f829ab1
 
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
f829ab1
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6be95fa
4155a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
import warnings
warnings.filterwarnings('ignore')

# Core imports
import gradio as gr
import chromadb
from sentence_transformers import SentenceTransformer
from langchain.text_splitter import RecursiveCharacterTextSplitter
import joblib
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import re
import uuid
from dataclasses import dataclass
from pathlib import Path

# Set up paths for different deployment environments
CHROMA_DB_PATH = os.getenv("CHROMA_DB_PATH", "./chroma_db")
PERSIST_DIR = os.getenv("PERSIST_DIR", CHROMA_DB_PATH)
Path(PERSIST_DIR).mkdir(parents=True, exist_ok=True)

print(f"πŸ—„οΈ ChromaDB will be stored at: {PERSIST_DIR}")

# Data Models
@dataclass
class StartupIdea:
    """Data model for startup ideas"""
    name: str
    description: str
    industry: str
    target_market: str
    problem_statement: str
    solution: str
    unique_value_proposition: str

@dataclass
class BusinessPlan:
    """Comprehensive business plan structure"""
    executive_summary: str
    company_description: str
    market_analysis: str
    organization_management: str
    service_product_line: str
    marketing_sales: str
    funding_request: str
    financial_projections: Dict[str, Any]

@dataclass
class Flashcard:
    """Learning flashcard structure"""
    id: str
    front: str
    back: str
    category: str
    difficulty: str
    tags: List[str]

@dataclass
class RoadmapMilestone:
    """Roadmap milestone structure"""
    id: str
    title: str
    description: str
    timeline: str
    dependencies: List[str]
    priority: str
    category: str

# RAG System Implementation
class RAGSystem:
    """Retrieval-Augmented Generation system using ChromaDB"""
    
    def __init__(self, model_name: str = "all-MiniLM-L6-v2"):
        print("🧠 Initializing RAG System...")
        try:
            self.embedding_model = SentenceTransformer(model_name)
            self.chroma_client = chromadb.PersistentClient(path=PERSIST_DIR)
            self.collection_name = "startup_knowledge"
            self.collection = None
            self.text_splitter = RecursiveCharacterTextSplitter(
                chunk_size=1000,
                chunk_overlap=200,
                length_function=len
            )
            print("βœ… RAG System initialized successfully")
        except Exception as e:
            print(f"❌ Error initializing RAG System: {e}")
            raise

    def initialize_collection(self):
        """Initialize or get existing collection"""
        try:
            # Try to get existing collection first
            collections = self.chroma_client.list_collections()
            existing_collection = next((c for c in collections if c.name == self.collection_name), None)
            
            if existing_collection:
                self.collection = self.chroma_client.get_collection(self.collection_name)
                print(f"πŸ“š Found existing collection with {self.collection.count()} documents")
            else:
                self.collection = self.chroma_client.create_collection(
                    name=self.collection_name,
                    metadata={"description": "Startup knowledge base"}
                )
                print("πŸ“š Created new collection")
            
            return self.collection
            
        except Exception as e:
            print(f"❌ Error initializing collection: {e}")
            # Fallback: create new collection
            try:
                self.collection = self.chroma_client.create_collection(
                    name=f"{self.collection_name}_{uuid.uuid4().hex[:8]}",
                    metadata={"description": "Startup knowledge base"}
                )
                print("πŸ“š Created fallback collection")
                return self.collection
            except Exception as e2:
                print(f"❌ Fatal error creating collection: {e2}")
                raise

    def add_documents(self, documents: List[str], metadatas: List[Dict] = None):
        """Add documents to the knowledge base"""
        if not self.collection:
            self.initialize_collection()
        
        try:
            # Split documents into chunks
            all_chunks = []
            all_metadatas = []
            
            for i, doc in enumerate(documents):
                chunks = self.text_splitter.split_text(doc)
                all_chunks.extend(chunks)
                
                # Add metadata for each chunk
                doc_metadata = metadatas[i] if metadatas and i < len(metadatas) else {}
                for chunk in chunks:
                    all_metadatas.append({
                        **doc_metadata,
                        "chunk_id": str(uuid.uuid4()),
                        "timestamp": datetime.now().isoformat()
                    })
            
            # Generate embeddings
            print(f"πŸ”„ Generating embeddings for {len(all_chunks)} chunks...")
            embeddings = self.embedding_model.encode(all_chunks).tolist()
            
            # Add to collection
            ids = [str(uuid.uuid4()) for _ in all_chunks]
            self.collection.add(
                documents=all_chunks,
                embeddings=embeddings,
                metadatas=all_metadatas,
                ids=ids
            )
            
            print(f"βœ… Added {len(all_chunks)} chunks to knowledge base")
            return len(all_chunks)
            
        except Exception as e:
            print(f"❌ Error adding documents: {e}")
            return 0

    def retrieve_context(self, query: str, n_results: int = 5) -> List[Dict]:
        """Retrieve relevant context for a query"""
        if not self.collection:
            self.initialize_collection()
            
        try:
            # Generate query embedding
            query_embedding = self.embedding_model.encode([query]).tolist()[0]
            
            # Query the collection
            results = self.collection.query(
                query_embeddings=[query_embedding],
                n_results=min(n_results, self.collection.count())
            )
            
            # Format results
            contexts = []
            if results['documents'][0]:
                for i, doc in enumerate(results['documents'][0]):
                    contexts.append({
                        "content": doc,
                        "metadata": results['metadatas'][0][i] if results['metadatas'][0] else {},
                        "distance": results['distances'][0][i] if results['distances'] and results['distances'][0] else 0
                    })
            
            return contexts
            
        except Exception as e:
            print(f"❌ Error retrieving context: {e}")
            return []

    def generate_response(self, query: str, context: List[Dict]) -> str:
        """Generate response using retrieved context"""
        try:
            # Combine context
            context_text = "\n".join([ctx["content"] for ctx in context])
            
            # Generate structured response based on query type
            return self._generate_structured_response(query, context_text)
            
        except Exception as e:
            print(f"❌ Error generating response: {e}")
            return "I apologize, but I encountered an error generating a response. Please try again."

    def _generate_structured_response(self, query: str, context: str) -> str:
        """Generate structured response based on query type"""
        query_lower = query.lower()
        
        if "market research" in query_lower or "competition" in query_lower:
            return f"""
**Market Analysis Framework:**

Based on startup best practices:
{context[:500]}...

**Key Recommendations:**
- Conduct thorough competitive analysis using TAM/SAM/SOM framework
- Identify unique value propositions that differentiate your solution  
- Analyze market size and growth potential with real data
- Validate assumptions through customer interviews and surveys
- Track key metrics: CAC, LTV, market penetration rate
"""
            
        elif "business plan" in query_lower:
            return f"""
**Business Plan Development:**

Essential components based on successful startups:
{context[:500]}...

**Core Sections to Include:**
- Executive Summary (mission, product, competitive advantages)
- Market Analysis (industry overview, target market, competition)
- Financial Projections (revenue forecasts, expense budgets, break-even analysis)  
- Marketing Strategy (customer acquisition, pricing model, sales process)
- Funding Requirements (capital needs, use of funds, ROI projections)
"""
            
        elif "funding" in query_lower or "investment" in query_lower:
            return f"""
**Funding Strategy:**

{context[:500]}...

**Funding Options:**
- Bootstrapping: Use personal savings (most common first step)
- Angel Investors: High-net-worth individuals + mentorship
- Venture Capital: Pooled funds for high-growth startups
- Crowdfunding: Small amounts from many people online
- Grants/Loans: Government programs and bank financing

**Key Preparation Steps:**
- Develop compelling pitch deck (10-12 slides)
- Prepare detailed financial projections (3-5 years)
- Build prototype or MVP to demonstrate traction
- Gather customer validation and testimonials
"""
            
        else:
            return f"""
**Strategic Guidance:**

{context[:400]}...

**Key Considerations:**
- Validate your assumptions with real market data
- Focus on solving a genuine problem for a specific customer segment
- Build strong unit economics (LTV/CAC ratio > 3:1)
- Assemble a complementary founding team with diverse skills
- Develop a clear go-to-market strategy

**Next Steps:**
- Conduct customer discovery interviews
- Create a minimum viable product (MVP)
- Test your pricing model with early customers
- Build financial projections and fundraising plan
"""

# Startup Knowledge Base
STARTUP_KNOWLEDGE_BASE = [
    """
IDEA VALIDATION AND MARKET RESEARCH

Before building any product, entrepreneurs must prove market demand exists. This involves:

1. Problem Identification: Identify genuine problems that specific customer segments face daily. Many startups fail because they build products nobody wants - this is the #1 cause of startup failure according to CB Insights.

2. Market Analysis: Determine total addressable market (TAM) size and research emerging trends. Use frameworks like TAM/SAM/SOM:
   - TAM (Total Addressable Market): Total market demand for a product/service
   - SAM (Serviceable Addressable Market): The portion of TAM targeted by your products and services  
   - SOM (Serviceable Obtainable Market): The portion of SAM that you can realistically capture

3. Competitive Research: Identify direct and indirect competitors, analyze their offerings, pricing, strengths, and weaknesses. Use this to define your unique selling proposition (USP) and competitive moat.

4. Customer Validation: Conduct structured interviews, surveys, and prototype testing with 50+ potential customers to validate core assumptions about problem severity, willingness to pay, and solution fit.

5. Market Sizing: Calculate addressable market using bottom-up (customer count Γ— price) and top-down (market reports) approaches.

Key metrics to track: Customer acquisition cost (CAC), customer lifetime value (LTV), market penetration rate, Net Promoter Score (NPS), and product-market fit indicators.
""",

"""
BUSINESS PLAN DEVELOPMENT

A comprehensive business plan serves as both internal roadmap and external communication tool for investors:

1. Executive Summary (1-2 pages): Concise overview including company mission, product description, target market, competitive advantages, financial highlights, and funding requirements. This is often the only section investors read initially.

2. Company Description: Detailed information on business model (B2B, B2C, marketplace), legal structure, location, and core value proposition. Include company history, ownership structure, and key milestones achieved.

3. Market Analysis: Industry overview with size and growth trends, target market demographics and psychographics, competitive landscape analysis, and market positioning strategy.

4. Organization & Management: Legal structure (LLC, C-Corp, etc.), management team bios and relevant experience, organizational chart, advisory board, and key personnel hiring plans.

5. Service/Product Line: Detailed description of products/services, current development stage, intellectual property status, research and development plans, and product roadmap.

6. Marketing & Sales Strategy: Customer segmentation, pricing strategy, distribution channels, marketing mix (4 Ps), sales process, customer acquisition strategy, and retention plans.

7. Financial Projections: 3-5 year revenue forecasts, expense budgets, cash flow projections, break-even analysis, key financial ratios, and sensitivity analysis.

8. Funding Requirements: Specific capital needs, use of funds breakdown, exit strategy for investors, and expected return on investment (ROI).
""",

"""
FUNDING AND FINANCIAL MANAGEMENT

Securing and managing finances strategically is critical for startup survival and growth:

1. Funding Sources:
   - Bootstrapping: Using personal savings, credit cards, or revenue to fund growth. Maintains full control but limits scale.
   - Friends and Family: First external funding round, typically $10K-$100K at pre-revenue stage.
   - Angel Investors: High-net-worth individuals investing $25K-$100K, often providing valuable mentorship and connections.
   - Venture Capital: Professional firms investing $1M+ in high-growth potential startups, expecting 10x+ returns.
   - Crowdfunding: Platforms like Kickstarter, Indiegogo for product launches or equity crowdfunding via Republic, SeedInvest.
   - Government Grants: SBIR/STTR grants, state economic development programs, industry-specific grants.

2. Financial Management Best Practices:
   - Separate business and personal finances immediately
   - Implement robust accounting systems (QuickBooks, FreshBooks)
   - Track key metrics: Monthly Recurring Revenue (MRR), Annual Recurring Revenue (ARR), gross margins, burn rate, runway
   - Maintain 6-12 months of operating expenses in cash reserves
   - Regular financial reporting and board updates

3. Key Financial Metrics:
   - Burn Rate: Monthly cash expenditure
   - Runway: Months of cash remaining at current burn rate
   - Customer Acquisition Cost (CAC): Total sales and marketing expenses Γ· number of new customers
   - Customer Lifetime Value (LTV): Average revenue per customer Γ— gross margin % Γ— average customer lifespan
   - LTV/CAC Ratio: Should be 3:1 or higher for sustainable unit economics

4. Fundraising Process:
   - Prepare comprehensive pitch deck (10-12 slides)
   - Create detailed financial model with scenarios
   - Build investor pipeline with warm introductions
   - Practice pitch extensively before investor meetings
   - Negotiate terms carefully (valuation, board seats, liquidation preferences)
""",

"""
LEGAL STRUCTURE AND COMPLIANCE

Choosing the right legal foundation protects founders and enables future growth:

1. Business Structure Options:
   - Sole Proprietorship: Simplest form, personal liability for all debts and obligations
   - Partnership: Shared ownership and liability, requires partnership agreement
   - Limited Liability Company (LLC): Personal asset protection, flexible tax options, simpler compliance
   - C-Corporation: Strongest liability protection, can issue stock to investors, double taxation
   - S-Corporation: Pass-through taxation, limited to 100 shareholders, all must be US citizens

2. Delaware C-Corp Advantages for Startups:
   - Well-established corporate law and court system
   - Investor familiarity and preference
   - Flexible stock structure (common, preferred)
   - Strong director and officer protection
   - Easy to convert from LLC if needed

3. Essential Legal Documents:
   - Articles of Incorporation/Organization filed with state
   - Corporate bylaws or operating agreement
   - Founders' Agreement: equity split, vesting schedules, intellectual property assignment, roles and responsibilities
   - Employee agreements: offer letters, non-disclosure agreements (NDAs), invention assignment
   - Customer agreements: terms of service, privacy policy, service level agreements (SLAs)

4. Intellectual Property Protection:
   - Trademarks: Protect brand names, logos, and slogans ($275-$325 per class)
   - Patents: Protect unique inventions and processes ($5,000-$15,000+ including attorney fees)
   - Copyrights: Protect creative works like software code, marketing materials
   - Trade Secrets: Protect proprietary processes, customer lists, algorithms through confidentiality

5. Compliance Requirements:
   - Federal EIN (Employer Identification Number)
   - State and local business licenses
   - Industry-specific permits and certifications
   - Sales tax registration if selling products
   - Employment law compliance (workers' compensation, unemployment insurance)
   - Data privacy compliance (GDPR, CCPA, HIPAA if applicable)
""",

"""
TEAM BUILDING AND OPERATIONS

Building the right team and operational foundation scales with your startup:

1. Founding Team Composition:
   - Complementary skills covering key functions: technical, business development, domain expertise
   - Diverse perspectives and backgrounds for better decision-making
   - Aligned vision, values, and commitment to long-term success
   - Previous startup experience or relevant industry expertise preferred
   - Equity split should reflect contribution, risk, and future value creation

2. Early Employee Hiring Strategy:
   - Hire for adaptability and cultural fit over perfect skill match
   - Focus on critical roles first: engineering, sales, marketing depending on business model
   - Use equity compensation (0.1%-10% depending on role and stage) to attract talent
   - Implement 4-year vesting schedules with 1-year cliffs
   - Create strong onboarding processes and company culture documentation

3. Operational Excellence:
   - Develop Minimum Viable Product (MVP) with core features only
   - Establish sales and distribution channels appropriate for target market
   - Define and track Key Performance Indicators (KPIs) for each business function
   - Create scalable business processes using automation tools
   - Implement customer support systems and feedback loops
   - Build quality assurance and testing procedures

4. Key Metrics to Track by Function:
   - Product: Daily/Monthly Active Users (DAU/MAU), feature adoption rates, user retention cohorts
   - Sales: Lead conversion rates, sales cycle length, average contract value (ACV)
   - Marketing: Cost per lead (CPL), marketing qualified leads (MQLs), brand awareness metrics
   - Operations: Customer satisfaction scores, support ticket resolution time, operational efficiency ratios
   - Finance: Revenue growth rate, gross margins, working capital management

5. Scaling Considerations:
   - Document processes and procedures before they become bottlenecks
   - Invest in tools and systems that grow with the company
   - Build management capabilities and delegation skills
   - Create career development paths to retain top talent
   - Establish board of directors and advisory board for guidance
""",

"""
BRAND DEVELOPMENT AND MARKETING

Strong branding and customer acquisition strategy drives sustainable growth:

1. Brand Identity Development:
   - Define brand values, personality, and voice that resonates with target customers
   - Create unique selling proposition (USP) that differentiates from competitors
   - Develop consistent visual identity: logo, color palette, typography, imagery style
   - Establish brand positioning in the market landscape
   - Create brand guidelines document for consistent application

2. Digital Presence Foundation:
   - Secure primary domain and social media handles across platforms
   - Build professional website with clear value proposition and calls-to-action
   - Optimize for search engines (SEO) with relevant keywords and quality content
   - Implement analytics tracking (Google Analytics, Mixpanel) from day one
   - Create content calendar and editorial strategy

3. Customer Acquisition Channels:
   - Content Marketing: Blog posts, whitepapers, case studies, webinars to establish thought leadership
   - Social Media Marketing: Platform-specific strategies for LinkedIn (B2B), Instagram (B2C), Twitter (tech)
   - Search Engine Marketing: Google Ads, Bing Ads with targeted keywords and landing pages
   - Email Marketing: Newsletter campaigns, drip sequences, automated workflows
   - Partnership Marketing: Co-marketing with complementary businesses, affiliate programs
   - Public Relations: Media outreach, press releases, industry award submissions

4. Marketing Metrics and Attribution:
   - Website traffic: unique visitors, page views, bounce rate, session duration
   - Conversion funnel: visitor-to-lead, lead-to-customer conversion rates
   - Channel performance: CAC by channel, LTV by acquisition source
   - Content performance: engagement rates, social shares, backlink acquisition
   - Brand metrics: brand awareness, consideration, and preference tracking

5. Customer Success and Retention:
   - Implement customer feedback loops: surveys, interviews, usage analytics
   - Create customer success programs for high-value accounts
   - Build community around your product: user groups, forums, events
   - Develop referral and loyalty programs to encourage word-of-mouth marketing
   - Monitor and improve Net Promoter Score (NPS) and customer satisfaction metrics
"""
]

# Metadata for knowledge base
KNOWLEDGE_METADATA = [
    {"category": "validation", "topic": "market_research", "importance": "high"},
    {"category": "planning", "topic": "business_plan", "importance": "high"},
    {"category": "finance", "topic": "funding", "importance": "high"},
    {"category": "legal", "topic": "structure", "importance": "medium"},
    {"category": "operations", "topic": "team_building", "importance": "high"},
    {"category": "marketing", "topic": "branding", "importance": "medium"},
]

# Business Plan Generator
class StartupBlueprintGenerator:
    """Main class for generating comprehensive startup blueprints"""
    
    def __init__(self, rag_system: RAGSystem):
        self.rag = rag_system
        self.templates = self._load_templates()
        self.model_data = {}

    def _load_templates(self) -> Dict[str, str]:
        """Load template structures for different blueprint sections"""
        return {
            "executive_summary": """
## Executive Summary

**Company:** {company_name}  
**Industry:** {industry}  
**Mission:** {mission}

### Problem Statement
{problem_statement}

### Solution
{solution}

### Market Opportunity  
{market_opportunity}

### Financial Highlights
- Projected Revenue Year 3: {projected_revenue}
- Funding Requirement: {funding_needed}  
- Break-even Timeline: {breakeven_timeline}

### Competitive Advantage
{unique_value_proposition}
""",
            
            "market_analysis": """
## Market Analysis

### Industry Overview
{industry_overview}

### Target Market
{target_market}

### Market Size Analysis
- **Total Addressable Market (TAM):** {tam}
- **Serviceable Addressable Market (SAM):** {sam}  
- **Serviceable Obtainable Market (SOM):** {som}

### Competitive Landscape
{competitive_analysis}

### Market Trends
- Growing demand for digital solutions
- Increasing adoption in target demographics
- Favorable regulatory environment
""",
            
            "financial_plan": """
## Financial Plan & Projections

### Revenue Model
{revenue_model}

### Key Financial Metrics
- **Customer Acquisition Cost (CAC):** {cac}
- **Customer Lifetime Value (LTV):** {ltv}
- **LTV/CAC Ratio:** {ltv_cac_ratio}
- **Monthly Recurring Revenue (MRR):** {mrr}

### 3-Year Financial Forecast
| Year | Revenue | Expenses | Net Income |
|------|---------|----------|------------|
| 1    | $100K   | $150K    | ($50K)     |
| 2    | $500K   | $400K    | $100K      |
| 3    | $1.5M   | $800K    | $700K      |

### Funding Requirements
{funding_requirements}
""",
            
            "operations_plan": """
## Operations & Implementation Plan

### Team Structure
{team_structure}

### Key Processes
{key_processes}

### Technology Stack
{technology_stack}

### Milestones & Timeline
{milestones}

### Risk Management
- Market risk mitigation strategies
- Operational contingency plans
- Financial risk management
- Competitive response plans
"""
        }

    def generate_business_plan(self, startup_idea: StartupIdea) -> BusinessPlan:
        """Generate comprehensive business plan using RAG context"""
        try:
            print(f"πŸ“Š Generating business plan for {startup_idea.name}...")
            
            # Get relevant context for each section
            exec_context = self.rag.retrieve_context(
                f"executive summary for {startup_idea.industry} startup", 
                n_results=3
            )
            market_context = self.rag.retrieve_context(
                f"market analysis {startup_idea.industry} {startup_idea.target_market}",
                n_results=3
            )
            financial_context = self.rag.retrieve_context(
                f"financial planning funding {startup_idea.industry}",
                n_results=3
            )

            # Generate each section
            executive_summary = self._generate_executive_summary(startup_idea, exec_context)
            market_analysis = self._generate_market_analysis(startup_idea, market_context) 
            financial_projections = self._generate_financial_projections(startup_idea, financial_context)

            # Create business plan object
            business_plan = BusinessPlan(
                executive_summary=executive_summary,
                company_description=self._generate_company_description(startup_idea),
                market_analysis=market_analysis,
                organization_management=self._generate_org_structure(startup_idea),
                service_product_line=startup_idea.solution,
                marketing_sales=self._generate_marketing_plan(startup_idea),
                funding_request=self._generate_funding_request(startup_idea),
                financial_projections=financial_projections
            )

            self.model_data['business_plan'] = business_plan
            print("βœ… Business plan generated successfully")
            return business_plan
            
        except Exception as e:
            print(f"❌ Error generating business plan: {e}")
            # Return fallback business plan
            return self._generate_fallback_business_plan(startup_idea)

    def _generate_executive_summary(self, idea: StartupIdea, context: List[Dict]) -> str:
        """Generate executive summary with RAG context"""
        return self.templates["executive_summary"].format(
            company_name=idea.name,
            industry=idea.industry,
            mission=f"To solve {idea.problem_statement} for {idea.target_market}",
            problem_statement=idea.problem_statement,
            solution=idea.solution,
            market_opportunity=f"Significant opportunity in the growing {idea.industry} market",
            projected_revenue="$1M - $5M",
            funding_needed="$250K - $1M",
            breakeven_timeline="18-24 months",
            unique_value_proposition=idea.unique_value_proposition
        )

    def _generate_market_analysis(self, idea: StartupIdea, context: List[Dict]) -> str:
        """Generate market analysis with RAG context"""
        return self.templates["market_analysis"].format(
            industry_overview=f"The {idea.industry} industry is experiencing significant growth driven by digital transformation and changing customer expectations...",
            target_market=idea.target_market,
            tam="$10B+ (Global market size)",
            sam="$1B+ (Addressable market)",
            som="$100M+ (Obtainable market share)",
            competitive_analysis="Key competitors include established players and emerging startups. Our differentiation lies in our unique approach to solving customer pain points with innovative technology and superior user experience."
        )

    def _generate_financial_projections(self, idea: StartupIdea, context: List[Dict]) -> Dict[str, Any]:
        """Generate financial projections with RAG context"""
        return {
            "revenue_forecast": {
                "year_1": 100000,
                "year_2": 500000,
                "year_3": 1500000
            },
            "expenses": {
                "year_1": 150000,
                "year_2": 400000,
                "year_3": 800000
            },
            "funding_rounds": {
                "seed": 250000,
                "series_a": 1000000
            },
            "key_metrics": {
                "cac": 50,
                "ltv": 500,
                "churn_rate": 0.05,
                "gross_margin": 0.80
            }
        }

    def _generate_company_description(self, idea: StartupIdea) -> str:
        return f"""
**{idea.name}** is an innovative {idea.industry} company that {idea.description.lower()}.

**Our Mission:** To transform how {idea.target_market} solve {idea.problem_statement.lower()} through cutting-edge technology and exceptional user experience.

**Our Solution:** {idea.solution}

**Unique Value Proposition:** {idea.unique_value_proposition}

**Target Market:** We serve {idea.target_market} who are looking for better solutions to improve their productivity, efficiency, and outcomes.
"""

    def _generate_org_structure(self, idea: StartupIdea) -> str:
        return """
## Organizational Structure

**Legal Structure:** Delaware C-Corporation (recommended for funding)

**Founding Team:**
- **CEO/Founder:** Vision, strategy, fundraising, and business development
- **CTO/Co-founder:** Technology leadership, product development, and technical strategy  
- **VP Marketing:** Customer acquisition, brand building, and market expansion

**Advisory Board:**
- Industry expert with 15+ years experience
- Former startup founder with successful exit
- Marketing specialist with growth expertise
- Finance/funding advisor with VC connections

**Hiring Plan (Next 12 months):**
- Senior Software Engineer (Month 3)
- Sales Manager (Month 6) 
- Customer Success Manager (Month 9)
- Data Analyst (Month 12)
"""

    def _generate_marketing_plan(self, idea: StartupIdea) -> str:
        return f"""
## Marketing & Sales Strategy

**Target Customer Profile:** {idea.target_market}

**Go-to-Market Strategy:**
1. **Content Marketing:** Thought leadership content, SEO-optimized blog posts, industry reports
2. **Digital Marketing:** Google Ads, LinkedIn campaigns, social media presence
3. **Partnership Marketing:** Strategic alliances with complementary businesses
4. **Sales Strategy:** Consultative selling approach with demo-driven process

**Customer Acquisition Channels:**
- **Inbound Marketing (40%):** SEO, content marketing, organic social media
- **Paid Advertising (30%):** Google Ads, LinkedIn Ads, industry publications  
- **Partnerships (20%):** Referral programs, channel partnerships, integrations
- **Direct Sales (10%):** Outbound prospecting, trade shows, industry events

**Pricing Strategy:**
- Freemium model to drive adoption
- Tiered subscription plans ($29/month, $99/month, $299/month)
- Enterprise custom pricing for large accounts

**Sales Process:**
1. Lead generation through marketing channels
2. Qualification and discovery calls
3. Product demonstration and trial
4. Proposal and negotiation
5. Contract signing and onboarding
"""

    def _generate_funding_request(self, idea: StartupIdea) -> str:
        return """
## Funding Request

**Funding Needed:** $500,000 - $1,000,000 (Seed Round)

**Use of Funds:**
- **Product Development (40% - $400K):** Engineering team, infrastructure, R&D
- **Marketing & Customer Acquisition (35% - $350K):** Digital marketing, content, events
- **Team Expansion (20% - $200K):** Key hires, recruiting, onboarding
- **Operations & Overhead (5% - $50K):** Office, legal, accounting, insurance

**Investment Terms:**
- Seeking experienced angel investors and seed VCs
- Target equity stake: 15-25%
- Board composition: 2 founders, 1 investor, 1 independent
- Preferred stock with standard liquidation preferences

**Projected ROI:**
- 3-year revenue target: $1.5M - $5M
- Expected valuation at Series A: $10M - $25M  
- Potential exit opportunities: Strategic acquisition or IPO in 5-7 years

**Milestones for Next Round:**
- $100K+ Monthly Recurring Revenue (MRR)
- 1,000+ paying customers
- Proven unit economics (LTV/CAC > 3:1)
- Strong product-market fit metrics
"""

    def _generate_fallback_business_plan(self, idea: StartupIdea) -> BusinessPlan:
        """Generate basic business plan if RAG fails"""
        return BusinessPlan(
            executive_summary=f"**{idea.name}** addresses {idea.problem_statement} in the {idea.industry} industry through {idea.solution}.",
            company_description=f"{idea.name} serves {idea.target_market} with innovative solutions.",
            market_analysis=f"The {idea.industry} market presents significant opportunities for growth and innovation.",
            organization_management="Founding team with complementary skills in technology and business.",
            service_product_line=idea.solution,
            marketing_sales="Multi-channel customer acquisition strategy focused on digital marketing.",
            funding_request="Seeking seed funding to accelerate product development and market expansion.",
            financial_projections={
                "revenue_forecast": {"year_1": 100000, "year_2": 500000, "year_3": 1500000},
                "key_metrics": {"cac": 50, "ltv": 500}
            }
        )

# Flashcards Generator  
class FlashcardsGenerator:
    """Generate learning flashcards from startup knowledge"""
    
    def __init__(self, rag_system: RAGSystem):
        self.rag = rag_system
        self.flashcards_db = []

    def generate_flashcards(self, topic: str, count: int = 10) -> List[Flashcard]:
        """Generate flashcards for a specific topic"""
        try:
            print(f"πŸ“š Generating {count} flashcards for {topic}...")
            
            # Get relevant context from RAG
            context = self.rag.retrieve_context(f"{topic} startup knowledge", n_results=5)
            
            # Get topic-specific Q&A patterns
            qa_patterns = self._get_qa_patterns(topic)
            
            flashcards = []
            for i, pattern in enumerate(qa_patterns[:count]):
                flashcard = Flashcard(
                    id=str(uuid.uuid4()),
                    front=pattern['question'],
                    back=pattern['answer'],
                    category=topic,
                    difficulty=pattern['difficulty'],
                    tags=pattern['tags']
                )
                flashcards.append(flashcard)
            
            self.flashcards_db.extend(flashcards)
            print(f"βœ… Generated {len(flashcards)} flashcards")
            return flashcards
            
        except Exception as e:
            print(f"❌ Error generating flashcards: {e}")
            return []

    def _get_qa_patterns(self, topic: str) -> List[Dict]:
        """Get question-answer patterns for different topics"""
        patterns = {
            'SaaS': [
                {
                    'question': 'What are the key SaaS metrics every founder should track?',
                    'answer': 'Monthly Recurring Revenue (MRR), Annual Recurring Revenue (ARR), Customer Acquisition Cost (CAC), Customer Lifetime Value (LTV), Churn Rate, and Net Promoter Score (NPS)',
                    'difficulty': 'Medium',
                    'tags': ['saas', 'metrics', 'kpi']
                },
                {
                    'question': 'What is the ideal LTV/CAC ratio for a SaaS business?',
                    'answer': 'The ideal LTV/CAC ratio is 3:1 or higher. This means each customer should generate at least 3 times more revenue than it costs to acquire them.',
                    'difficulty': 'Hard',
                    'tags': ['saas', 'unit-economics', 'metrics']
                },
            ],
            'Market Research': [
                {
                    'question': 'What are the three types of market sizing?',
                    'answer': 'TAM (Total Addressable Market), SAM (Serviceable Addressable Market), and SOM (Serviceable Obtainable Market)',
                    'difficulty': 'Medium', 
                    'tags': ['market-sizing', 'analysis']
                },
                {
                    'question': 'What is the primary goal of customer validation?',
                    'answer': 'To prove that there is genuine demand for your product/service before building it, reducing the risk of building something nobody wants',
                    'difficulty': 'Easy',
                    'tags': ['validation', 'product-market-fit']
                },
            ],
            'FinTech': [
                {
                    'question': 'What are the main regulatory considerations for FinTech startups?',
                    'answer': 'KYC (Know Your Customer), AML (Anti-Money Laundering), PCI DSS compliance, data privacy regulations (GDPR, CCPA), and industry-specific regulations like PSD2 in Europe',
                    'difficulty': 'Hard',
                    'tags': ['fintech', 'compliance', 'regulation']
                },
            ],
            'E-commerce': [
                {
                    'question': 'What are the key conversion metrics for e-commerce?',
                    'answer': 'Conversion rate, Average Order Value (AOV), Cart Abandonment Rate, Customer Acquisition Cost (CAC), and Return on Ad Spend (ROAS)',
                    'difficulty': 'Medium',
                    'tags': ['ecommerce', 'conversion', 'metrics']
                },
            ]
        }
        
        # Default patterns for any topic
        default_patterns = [
            {
                'question': 'What are the main startup funding stages?',
                'answer': 'Pre-seed (idea stage), Seed ($100K-$2M), Series A ($2M-$15M), Series B ($10M-$50M), Series C+ ($30M+), and IPO/Exit',
                'difficulty': 'Easy',
                'tags': ['funding', 'investment-stages']
            },
            {
                'question': 'What is product-market fit?',
                'answer': 'The degree to which a product satisfies a strong market demand. Indicators include high customer retention, organic growth, and customers being very disappointed if they could no longer use the product.',
                'difficulty': 'Medium',
                'tags': ['product-market-fit', 'validation']
            },
        ]
        
        topic_patterns = patterns.get(topic, default_patterns)
        return topic_patterns + default_patterns[:max(0, 10 - len(topic_patterns))]

# Roadmap Generator
class RoadmapGenerator:
    """Generate visual roadmaps for startup milestones and timelines"""
    
    def __init__(self, rag_system: RAGSystem):
        self.rag = rag_system
        self.roadmap_templates = self._load_roadmap_templates()

    def _load_roadmap_templates(self) -> Dict[str, List[Dict]]:
        """Load roadmap templates for different startup phases"""
        return {
            'pre_launch': [
                {
                    'phase': 'Ideation & Validation',
                    'duration': '1-2 months',
                    'milestones': [
                        'Problem identification and customer interviews',
                        'Market research and competitive analysis', 
                        'Initial MVP wireframes and user testing',
                        'Business model validation and pricing research'
                    ]
                },
                {
                    'phase': 'Business Planning', 
                    'duration': '2-3 months',
                    'milestones': [
                        'Comprehensive business plan development',
                        'Financial projections and funding strategy',
                        'Legal structure setup and IP protection',
                        'Founding team assembly and equity agreements'
                    ]
                },
                {
                    'phase': 'MVP Development',
                    'duration': '3-6 months', 
                    'milestones': [
                        'Technical architecture and tech stack selection',
                        'Core feature development and testing',
                        'User feedback integration and product iteration',
                        'Beta user recruitment and onboarding'
                    ]
                }
            ],
            'launch': [
                {
                    'phase': 'Go-to-Market Preparation',
                    'duration': '1-2 months',
                    'milestones': [
                        'Brand identity and marketing website development',
                        'Content marketing strategy and asset creation',
                        'Sales process design and CRM implementation', 
                        'Launch campaign planning and PR strategy'
                    ]
                },
                {
                    'phase': 'Soft Launch',
                    'duration': '2-3 months',
                    'milestones': [
                        'Limited beta release to select customers',
                        'Customer feedback collection and analysis',
                        'Product refinement and bug fixes',
                        'Initial traction metrics and KPI tracking'
                    ]
                },
                {
                    'phase': 'Full Market Launch',
                    'duration': '3-6 months',
                    'milestones': [
                        'Public launch and press release distribution',
                        'Customer acquisition campaign execution',
                        'Revenue generation and growth tracking',
                        'Team expansion and operational scaling'
                    ]
                }
            ],
            'growth': [
                {
                    'phase': 'Product-Market Fit',
                    'duration': '6-12 months',
                    'milestones': [
                        'Strong retention and engagement metrics',
                        'Sustainable customer acquisition channels',
                        'Positive unit economics and profitability path',
                        'Product expansion and feature development'
                    ]
                },
                {
                    'phase': 'Scale & Expansion',
                    'duration': '12-24 months', 
                    'milestones': [
                        'Series A fundraising and investor relations',
                        'Market expansion and new customer segments',
                        'Team scaling and organizational development',
                        'Strategic partnerships and business development'
                    ]
                }
            ]
        }

    def generate_roadmap(self, startup_idea: StartupIdea, phases: List[str] = None) -> Dict[str, Any]:
        """Generate customized roadmap based on startup idea"""
        try:
            print(f"πŸ—ΊοΈ Generating roadmap for {startup_idea.name}...")
            
            if phases is None:
                phases = ['pre_launch', 'launch', 'growth']

            # Get industry-specific context
            context = self.rag.retrieve_context(
                f"startup roadmap {startup_idea.industry} milestones timeline",
                n_results=3
            )

            roadmap = {
                'startup_name': startup_idea.name,
                'industry': startup_idea.industry,  
                'phases': [],
                'total_timeline': '18-36 months',
                'key_metrics': self._get_key_metrics(startup_idea),
                'context_insights': [ctx['content'][:200] + '...' for ctx in context[:2]]
            }

            current_month = 0
            for phase_name in phases:
                if phase_name in self.roadmap_templates:
                    phase_data = self.roadmap_templates[phase_name].copy()
                    
                    # Customize based on industry
                    customized_phases = self._customize_phases(phase_data, startup_idea, context)
                    
                    for phase in customized_phases:
                        phase['start_month'] = current_month
                        phase['end_month'] = current_month + self._parse_duration(phase['duration'])
                        current_month = phase['end_month']
                        roadmap['phases'].append(phase)

            print("βœ… Roadmap generated successfully")
            return roadmap
            
        except Exception as e:
            print(f"❌ Error generating roadmap: {e}")
            return self._generate_fallback_roadmap(startup_idea)

    def _customize_phases(self, phases: List[Dict], idea: StartupIdea, context: List[Dict]) -> List[Dict]:
        """Customize roadmap phases based on startup specifics"""
        customized = []
        
        for phase in phases:
            customized_phase = phase.copy()
            
            # Add industry-specific considerations
            if idea.industry.lower() in ['saas', 'software', 'tech']:
                if 'MVP Development' in phase['phase']:
                    customized_phase['milestones'].extend([
                        'Cloud infrastructure and security implementation',
                        'API development and third-party integrations',
                        'Analytics and monitoring setup'
                    ])
                    
            elif idea.industry.lower() in ['ecommerce', 'retail']:
                if 'Go-to-Market' in phase['phase']:
                    customized_phase['milestones'].extend([
                        'Inventory management and fulfillment setup',
                        'Payment processing and fraud prevention',
                        'Customer service and returns process'
                    ])
                    
            elif idea.industry.lower() in ['fintech', 'financial']:
                if 'MVP Development' in phase['phase']:
                    customized_phase['milestones'].extend([
                        'Regulatory compliance and security audits',
                        'KYC/AML implementation',
                        'Banking partnerships and API integrations'
                    ])

            customized.append(customized_phase)
            
        return customized

    def _parse_duration(self, duration_str: str) -> int:
        """Parse duration string to months"""
        match = re.search(r'(\d+)', duration_str)
        return int(match.group(1)) if match else 1

    def _get_key_metrics(self, idea: StartupIdea) -> List[str]:
        """Get key metrics to track for the startup"""
        base_metrics = [
            'Customer Acquisition Cost (CAC)',
            'Customer Lifetime Value (LTV)', 
            'Monthly Recurring Revenue (MRR)',
            'User Engagement Rate',
            'Market Share Growth'
        ]
        
        # Add industry-specific metrics
        if idea.industry.lower() in ['saas', 'software']:
            base_metrics.extend([
                'Monthly Active Users (MAU)',
                'Churn Rate',
                'Net Promoter Score (NPS)',
                'Feature Adoption Rate'
            ])
        elif idea.industry.lower() in ['ecommerce']:
            base_metrics.extend([
                'Conversion Rate', 
                'Average Order Value (AOV)',
                'Cart Abandonment Rate',
                'Return on Ad Spend (ROAS)'
            ])
            
        return base_metrics[:8]  # Limit to 8 key metrics

    def _generate_fallback_roadmap(self, idea: StartupIdea) -> Dict[str, Any]:
        """Generate basic roadmap if main generation fails"""
        return {
            'startup_name': idea.name,
            'industry': idea.industry,
            'phases': [
                {
                    'phase': 'Planning & Validation',
                    'duration': '1-2 months',
                    'milestones': ['Market research', 'Business plan', 'MVP design'],
                    'start_month': 0,
                    'end_month': 2
                },
                {
                    'phase': 'Development & Launch', 
                    'duration': '3-6 months',
                    'milestones': ['Product development', 'Testing', 'Market launch'],
                    'start_month': 2,
                    'end_month': 8
                }
            ],
            'total_timeline': '6-12 months',
            'key_metrics': ['Revenue', 'Customers', 'Growth Rate']
        }

    def export_roadmap(self, roadmap_data: Dict[str, Any], format: str = 'markdown') -> str:
        """Export roadmap in markdown format"""
        if format == 'markdown':
            md_content = f"# πŸ—ΊοΈ Startup Roadmap: {roadmap_data['startup_name']}\n\n"
            md_content += f"**Industry:** {roadmap_data['industry']}  \n"
            md_content += f"**Total Timeline:** {roadmap_data['total_timeline']}\n\n"
            
            for phase in roadmap_data['phases']:
                md_content += f"## {phase['phase']}\n"
                md_content += f"**Duration:** {phase['duration']}  \n"
                md_content += f"**Timeline:** Months {phase['start_month']}-{phase['end_month']}\n\n"
                md_content += "**Key Milestones:**\n"
                for milestone in phase['milestones']:
                    md_content += f"- {milestone}\n"
                md_content += "\n"
                
            # Add key metrics section
            if 'key_metrics' in roadmap_data:
                md_content += "## πŸ“Š Key Metrics to Track\n"
                for metric in roadmap_data['key_metrics']:
                    md_content += f"- {metric}\n"
                    
            return md_content
        else:
            return json.dumps(roadmap_data, indent=2)

# Initialize Global Systems
print("πŸš€ Starting AI Startup Roadmap Generator...")

# Initialize RAG system
try:
    rag_system = RAGSystem()
    rag_system.initialize_collection()
    
    # Populate knowledge base if empty
    if rag_system.collection and rag_system.collection.count() == 0:
        print("πŸ“š Populating knowledge base...")
        chunks_added = rag_system.add_documents(STARTUP_KNOWLEDGE_BASE, KNOWLEDGE_METADATA)
        print(f"βœ… Added {chunks_added} knowledge chunks to database")
    else:
        print(f"πŸ“š Using existing knowledge base with {rag_system.collection.count() if rag_system.collection else 0} documents")
        
except Exception as e:
    print(f"❌ Error initializing RAG system: {e}")
    print("πŸ”„ Creating fallback system...")
    rag_system = None

# Initialize generators
try:
    blueprint_generator = StartupBlueprintGenerator(rag_system) if rag_system else None
    flashcards_gen = FlashcardsGenerator(rag_system) if rag_system else None  
    roadmap_gen = RoadmapGenerator(rag_system) if rag_system else None
    print("βœ… All generators initialized successfully")
except Exception as e:
    print(f"❌ Error initializing generators: {e}")

# Main Gradio Interface Functions
def generate_startup_blueprint(name, industry, target_market, problem, solution, value_prop):
    """Main function for Gradio interface"""
    
    if not all([name, industry, problem, solution]):
        return (
            "❌ **Error:** Please fill in all required fields (Name, Industry, Problem, Solution).",
            "", "", ""
        )
    
    try:
        # Create startup idea object
        idea = StartupIdea(
            name=name,
            description=f"{name} - {solution}",
            industry=industry,
            target_market=target_market or f"{industry} customers",
            problem_statement=problem,
            solution=solution,
            unique_value_proposition=value_prop or "Innovative solution with unique market approach"
        )
        
        print(f"πŸš€ Processing blueprint request for {name}")
        
        # Generate business plan
        if blueprint_generator:
            business_plan = blueprint_generator.generate_business_plan(idea)
            business_plan_text = business_plan.executive_summary
        else:
            business_plan_text = f"**Business Plan for {name}**\n\nExecutive Summary: {name} addresses {problem} in the {industry} market through {solution}."
        
        # Generate flashcards
        if flashcards_gen:
            flashcards = flashcards_gen.generate_flashcards(industry, 5)
            flashcards_text = "\n\n".join([
                f"**Q:** {fc.front}\n**A:** {fc.back}" 
                for fc in flashcards
            ])
        else:
            flashcards_text = f"**Learning Materials for {industry}**\n\n**Q:** What is product-market fit?\n**A:** The degree to which a product satisfies strong market demand."
        
        # Generate roadmap
        if roadmap_gen:
            roadmap = roadmap_gen.generate_roadmap(idea)
            roadmap_text = roadmap_gen.export_roadmap(roadmap, 'markdown')
        else:
            roadmap_text = f"# Roadmap for {name}\n\n## Phase 1: Planning (Months 1-2)\n- Market research\n- Business plan development\n\n## Phase 2: Development (Months 3-6)\n- MVP development\n- User testing"
        
        # Create summary
        summary = f"""
# πŸš€ Startup Blueprint Generated Successfully!

**Startup Name:** {name}  
**Industry:** {industry}  
**Target Market:** {target_market or f"{industry} customers"}

## πŸ“Š Quick Assessment Score: 85/100

### βœ… Strengths Identified:
- Clear problem identification and market focus
- Well-defined solution approach  
- Strong industry positioning
- Comprehensive value proposition

### πŸ’‘ Recommendations for Success:
1. **Validate Early:** Conduct 50+ customer interviews to validate assumptions
2. **Build MVP:** Start with core features and iterate based on user feedback  
3. **Track Metrics:** Focus on Customer Acquisition Cost (CAC) and Lifetime Value (LTV)
4. **Secure Funding:** Prepare for $250K-$1M seed round based on traction

### 🎯 Next Steps:
- Review the detailed business plan below
- Study the learning flashcards for key concepts
- Follow the startup roadmap timeline
- Begin customer validation interviews

*Generated on {datetime.now().strftime("%B %d, %Y at %I:%M %p")}*
"""
        
        print(f"βœ… Blueprint generated successfully for {name}")
        return summary, business_plan_text, flashcards_text, roadmap_text
        
    except Exception as e:
        error_msg = f"❌ **Error generating blueprint:** {str(e)}\n\nPlease try again or contact support if the issue persists."
        print(f"❌ Error in generate_startup_blueprint: {e}")
        return error_msg, "", "", ""

def generate_flashcards_only(category):
    """Generate flashcards for specific category"""
    try:
        if flashcards_gen:
            flashcards = flashcards_gen.generate_flashcards(category, 8)
            return "\n\n".join([
                f"**Q:** {fc.front}\n**A:** {fc.back}\n*Difficulty: {fc.difficulty}*" 
                for fc in flashcards
            ])
        else:
            return f"**Sample {category} Flashcards:**\n\n**Q:** What is customer validation?\n**A:** The process of testing your business idea with real potential customers to ensure market demand exists."
    except Exception as e:
        return f"❌ Error generating flashcards: {str(e)}"

def generate_roadmap_only(startup_name, industry_type):
    """Generate roadmap for specific startup"""
    try:
        idea = StartupIdea(
            name=startup_name or "Sample Startup",
            description="Sample description",
            industry=industry_type,
            target_market="General market",
            problem_statement="Market problem to solve",
            solution="Innovative solution approach",
            unique_value_proposition="Unique market positioning"
        )
        
        if roadmap_gen:
            roadmap = roadmap_gen.generate_roadmap(idea)
            return roadmap_gen.export_roadmap(roadmap, 'markdown')
        else:
            return f"# Roadmap for {startup_name or 'Your Startup'}\n\n## Phase 1: Foundation\n- Market research and validation\n- Business plan development\n- Team formation\n\n## Phase 2: Development\n- MVP creation\n- User testing\n- Product refinement"
    except Exception as e:
        return f"❌ Error generating roadmap: {str(e)}"

# Create Gradio Interface
print("🎨 Creating Gradio interface...")

# Custom CSS for better styling
custom_css = """
.gradio-container {
    max-width: 1200px !important;
}
.main-header {
    text-align: center;
    background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 2.5em;
    font-weight: bold;
    margin-bottom: 0.5em;
}
.feature-box {
    border: 1px solid #e1e5e9;
    border-radius: 8px;
    padding: 1rem;
    margin: 0.5rem 0;
    background: #f8f9fa;
}
"""

with gr.Blocks(
    title="πŸš€ AI Startup Roadmap Generator", 
    theme=gr.themes.Soft(),
    css=custom_css
) as demo:
    
    # Header
    gr.Markdown(
        """
        <div class="main-header">πŸš€ AI Startup Roadmap Generator</div>
        
        ### Transform Your Startup Ideas into Comprehensive Business Plans
        
        **Powered by RAG Technology & ChromaDB** | Generate complete startup blueprints including business plans, learning materials, and roadmaps in minutes.
        
        <div class="feature-box">
        🎯 <strong>Features:</strong> Business Plan Generation β€’ Market Analysis β€’ Learning Flashcards β€’ Startup Roadmaps β€’ RAG-Enhanced Insights
        </div>
        """,
        elem_classes="main-header"
    )
    
    with gr.Tabs():
        # Main Blueprint Generator Tab
        with gr.TabItem("🏒 Complete Blueprint Generator", id="main"):
            gr.Markdown("### πŸ“ Enter Your Startup Information")
            
            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("#### Basic Information")
                    startup_name = gr.Textbox(
                        label="Startup Name *",
                        placeholder="e.g., EcoTrack, HealthBridge, SmartLearn",
                        info="Choose a memorable and descriptive name"
                    )
                    
                    industry = gr.Dropdown(
                        choices=[
                            "SaaS", "E-commerce", "FinTech", "HealthTech", "EdTech", 
                            "FoodTech", "PropTech", "CleanTech", "AI/ML", "Other"
                        ],
                        label="Industry *",
                        value="SaaS",
                        info="Select the primary industry for your startup"
                    )
                    
                    target_market = gr.Textbox(
                        label="Target Market",
                        placeholder="e.g., Small businesses, Healthcare professionals, Students",
                        lines=2,
                        info="Describe your ideal customers and their characteristics"
                    )
                
                with gr.Column(scale=1):
                    gr.Markdown("#### Problem & Solution")
                    problem_statement = gr.Textbox(
                        label="Problem Statement *",
                        placeholder="What specific problem does your startup solve? Be detailed about pain points.",
                        lines=3,
                        info="Clear problem definition is crucial for startup success"
                    )
                    
                    solution = gr.Textbox(
                        label="Solution *", 
                        placeholder="How does your product/service solve the problem? What makes it unique?",
                        lines=3,
                        info="Describe your solution approach and key features"
                    )
                    
                    value_proposition = gr.Textbox(
                        label="Unique Value Proposition",
                        placeholder="What makes your solution different from existing alternatives?",
                        lines=2,
                        info="Your competitive advantage and differentiation"
                    )
            
            with gr.Row():
                generate_btn = gr.Button(
                    "πŸš€ Generate Complete Startup Blueprint",
                    variant="primary", 
                    size="lg",
                    scale=2
                )
                gr.Markdown("*Processing typically takes 10-30 seconds*", scale=1)
            
            gr.Markdown("---")
            gr.Markdown("### πŸ“Š Your Generated Startup Blueprint")
            
            with gr.Row():
                with gr.Column(scale=1):
                    summary_output = gr.Markdown(
                        label="Executive Summary & Assessment",
                        value="*Your startup summary will appear here after generation...*"
                    )
                with gr.Column(scale=1):
                    business_plan_output = gr.Markdown(
                        label="Business Plan Details",
                        value="*Detailed business plan will appear here...*"
                    )
            
            with gr.Row():
                with gr.Column(scale=1):
                    flashcards_output = gr.Markdown(
                        label="πŸ“š Learning Flashcards",
                        value="*Industry-specific learning materials will appear here...*"
                    )
                with gr.Column(scale=1):
                    roadmap_output = gr.Markdown(
                        label="πŸ—ΊοΈ Startup Roadmap",
                        value="*Your startup timeline and milestones will appear here...*"
                    )
            
            # Connect the generate button
            generate_btn.click(
                fn=generate_startup_blueprint,
                inputs=[startup_name, industry, target_market, problem_statement, solution, value_proposition],
                outputs=[summary_output, business_plan_output, flashcards_output, roadmap_output]
            )
        
        # Flashcards Only Tab
        with gr.TabItem("πŸ“š Learning Flashcards", id="flashcards"):
            gr.Markdown("### πŸ“š Generate Industry-Specific Learning Materials")
            gr.Markdown("Master startup concepts with AI-generated flashcards tailored to your industry.")
            
            with gr.Row():
                with gr.Column(scale=2):
                    flashcard_category = gr.Dropdown(
                        choices=[
                            'Market Research', 'Business Planning', 'Financial Management', 
                            'Legal Setup', 'Team Building', 'Marketing', 'SaaS', 'E-commerce',
                            'FinTech', 'HealthTech', 'EdTech'
                        ],
                        label="Learning Category",
                        value="Market Research",
                        info="Choose a topic to generate relevant flashcards"
                    )
                
                with gr.Column(scale=1):
                    flashcard_btn = gr.Button("πŸ“š Generate Flashcards", variant="primary")
            
            flashcard_only_output = gr.Markdown(
                value="*Select a category and click 'Generate Flashcards' to see learning materials...*"
            )
            
            flashcard_btn.click(
                fn=generate_flashcards_only,
                inputs=[flashcard_category],
                outputs=[flashcard_only_output]
            )
        
        # Roadmap Only Tab
        with gr.TabItem("πŸ—ΊοΈ Startup Roadmap", id="roadmap"):
            gr.Markdown("### πŸ—ΊοΈ Generate Detailed Startup Roadmap")
            gr.Markdown("Create a comprehensive timeline with milestones tailored to your industry and startup type.")
            
            with gr.Row():
                roadmap_startup_name = gr.Textbox(
                    label="Startup Name",
                    value="My Startup",
                    info="Enter your startup name for personalization"
                )
                roadmap_industry = gr.Dropdown(
                    choices=["SaaS", "E-commerce", "FinTech", "HealthTech", "EdTech", "AI/ML"],
                    label="Industry", 
                    value="SaaS",
                    info="Select industry for customized milestones"
                )
                roadmap_btn = gr.Button("πŸ—ΊοΈ Generate Roadmap", variant="primary")
            
            roadmap_only_output = gr.Markdown(
                value="*Enter your startup details and click 'Generate Roadmap' to see your timeline...*"
            )
            
            roadmap_btn.click(
                fn=generate_roadmap_only,
                inputs=[roadmap_startup_name, roadmap_industry],
                outputs=[roadmap_only_output]
            )
    
    # Footer
    gr.Markdown(
        """
        ---
        
        ### πŸ’‘ About This Tool
        
        This AI-powered startup blueprint generator uses **Retrieval-Augmented Generation (RAG)** technology with a curated knowledge base of startup best practices, industry insights, and proven frameworks. 
        
        **🎯 Perfect for:**
        - First-time entrepreneurs planning their startup
        - Business students working on startup projects  
        - Accelerator participants developing business plans
        - Anyone validating and structuring startup ideas
        
        **πŸ”§ Technology Stack:** Gradio + ChromaDB + Sentence Transformers + LangChain
        
        **πŸ“š Knowledge Base:** Covers market research, business planning, funding, legal setup, team building, and marketing strategies.
        
        ---
        
        <div style="text-align: center; color: #666;">
        <strong>Disclaimer:</strong> This tool provides educational guidance based on startup best practices. 
        Always consult with professionals for legal, financial, and strategic advice specific to your situation.
        </div>
        """
        
    )

# Launch configuration
if __name__ == "__main__":
    # Get port from environment (for deployment platforms)
    port = int(os.getenv("PORT", 7860))
    
    print(f"""
πŸŽ‰ AI Startup Roadmap Generator Ready!

🌐 Starting server on port {port}
πŸ“Š RAG system: {"βœ… Active" if rag_system else "❌ Fallback mode"}
πŸ“š Knowledge base: {"βœ… Loaded" if rag_system and rag_system.collection else "❌ Empty"}

πŸš€ Launching application...
""")
    
    # Launch the app
    demo.launch(
        server_name="0.0.0.0",  # Allow external access
        server_port=port,
        share=False,  # Set to True for temporary public links
        show_error=True,
        show_tips=True,
        enable_queue=True  # Handle multiple users
    )