File size: 57,328 Bytes
a39c567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3ed951
a39c567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
887cae9
a39c567
 
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
import os
import json
import pandas as pd
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
from openai import OpenAI
from datetime import datetime
from dotenv import load_dotenv

load_dotenv()
API_KEY = os.getenv("OPENAI_API_KEY")

# Page configuration
st.set_page_config(
    page_title="SoftwareGrid AI - Intelligent Software Procurement",
    page_icon="🎯",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS
st.markdown("""
<style>
    .main-header {
        font-size: 2.5rem;
        font-weight: bold;
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 1rem;
    }
    .metric-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 1.5rem;
        border-radius: 10px;
        color: white;
    }
    .software-card {
        border: 2px solid #e0e0e0;
        border-radius: 10px;
        padding: 1.5rem;
        margin: 1rem 0;
        transition: all 0.3s;
    }
    .software-card:hover {
        border-color: #667eea;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
    }
    .stButton>button {
        width: 100%;
        border-radius: 8px;
        font-weight: 600;
    }
</style>
""", unsafe_allow_html=True)

# Initialize session state
if 'api_key' not in st.session_state:
    st.session_state.api_key = API_KEY   # load from env automatically
if 'software_database' not in st.session_state:
    st.session_state.software_database = []
if 'compare_list' not in st.session_state:
    st.session_state.compare_list = []
if 'chat_history' not in st.session_state:
    st.session_state.chat_history = []
if 'user_requirements' not in st.session_state:
    st.session_state.user_requirements = {}



# Sample software database
SOFTWARE_DATABASE = [
    {
        "name": "Zoom", "category": "Video Conferencing",
        "description": "HD video conferencing and virtual meetings platform",
        "pricing_min": 0, "pricing_max": 19.99, "pricing_unit": "user/month",
        "features": ["HD Video", "Screen Sharing", "Recording", "Breakout Rooms", "Webinar Mode"],
        "users": "300M+", "rating": 4.5, "negotiable": True, "g2_score": 4.5,
        "integrations": ["Slack", "Microsoft Teams", "Salesforce", "Google Calendar"],
        "compliance": ["SOC2", "GDPR", "HIPAA"]
    },
    {
        "name": "Slack", "category": "Team Communication",
        "description": "Team messaging and collaboration platform",
        "pricing_min": 0, "pricing_max": 12.50, "pricing_unit": "user/month",
        "features": ["Channels", "Direct Messages", "File Sharing", "App Integrations", "Search"],
        "users": "50M+", "rating": 4.6, "negotiable": True, "g2_score": 4.5,
        "integrations": ["Google Drive", "Zoom", "Salesforce", "Jira"],
        "compliance": ["SOC2", "GDPR", "ISO27001"]
    },
    {
        "name": "Microsoft Teams", "category": "Video Conferencing",
        "description": "Chat, meetings, calls, and collaboration in Office 365",
        "pricing_min": 0, "pricing_max": 12.50, "pricing_unit": "user/month",
        "features": ["Video Calls", "Chat", "File Storage", "Office Integration", "Teams Channels"],
        "users": "280M+", "rating": 4.4, "negotiable": False, "g2_score": 4.3,
        "integrations": ["Office 365", "SharePoint", "OneDrive", "Power BI"],
        "compliance": ["SOC2", "GDPR", "HIPAA", "ISO27001"]
    },
    {
        "name": "Google Workspace", "category": "Email & Productivity",
        "description": "Email, docs, drive, and collaboration suite",
        "pricing_min": 6, "pricing_max": 18, "pricing_unit": "user/month",
        "features": ["Gmail", "Drive", "Docs/Sheets", "Meet", "Calendar", "Admin Console"],
        "users": "3B+", "rating": 4.7, "negotiable": False, "g2_score": 4.6,
        "integrations": ["Slack", "Zoom", "Salesforce", "Asana"],
        "compliance": ["SOC2", "GDPR", "HIPAA", "ISO27001"]
    },
    {
        "name": "Asana", "category": "Project Management",
        "description": "Work management platform for team collaboration",
        "pricing_min": 0, "pricing_max": 24.99, "pricing_unit": "user/month",
        "features": ["Task Management", "Timelines", "Workflows", "Reporting", "Portfolios"],
        "users": "150M+", "rating": 4.5, "negotiable": True, "g2_score": 4.4,
        "integrations": ["Slack", "Google Drive", "Microsoft Teams", "Salesforce"],
        "compliance": ["SOC2", "GDPR", "ISO27001"]
    },
    {
        "name": "Monday.com", "category": "Project Management",
        "description": "Work operating system for team productivity",
        "pricing_min": 8, "pricing_max": 16, "pricing_unit": "user/month",
        "features": ["Custom Workflows", "Dashboards", "Automations", "Time Tracking", "Forms"],
        "users": "180K+", "rating": 4.6, "negotiable": True, "g2_score": 4.7,
        "integrations": ["Slack", "Zoom", "Microsoft Teams", "Google Drive"],
        "compliance": ["SOC2", "GDPR", "ISO27001"]
    },
    {
        "name": "Notion", "category": "Knowledge Management",
        "description": "All-in-one workspace for notes, docs, and wikis",
        "pricing_min": 0, "pricing_max": 10, "pricing_unit": "user/month",
        "features": ["Wiki", "Docs", "Databases", "Kanban Boards", "Templates"],
        "users": "30M+", "rating": 4.7, "negotiable": False, "g2_score": 4.7,
        "integrations": ["Slack", "Google Drive", "Figma", "GitHub"],
        "compliance": ["SOC2", "GDPR"]
    },
    {
        "name": "Salesforce", "category": "CRM",
        "description": "Customer relationship management platform",
        "pricing_min": 25, "pricing_max": 300, "pricing_unit": "user/month",
        "features": ["Lead Management", "Sales Pipeline", "Analytics", "Mobile App", "Einstein AI"],
        "users": "150K+ companies", "rating": 4.4, "negotiable": True, "g2_score": 4.3,
        "integrations": ["Slack", "Google Workspace", "Microsoft 365", "Zoom"],
        "compliance": ["SOC2", "GDPR", "HIPAA", "ISO27001"]
    },
    {
        "name": "Jira", "category": "Project Management",
        "description": "Issue tracking and agile project management",
        "pricing_min": 0, "pricing_max": 14.50, "pricing_unit": "user/month",
        "features": ["Scrum Boards", "Kanban", "Roadmaps", "Reports", "Automation"],
        "users": "65K+ companies", "rating": 4.4, "negotiable": False, "g2_score": 4.2,
        "integrations": ["Confluence", "Slack", "GitHub", "Microsoft Teams"],
        "compliance": ["SOC2", "GDPR", "ISO27001"]
    },
    {
        "name": "Dropbox Business", "category": "Cloud Storage",
        "description": "Cloud storage and file sharing platform",
        "pricing_min": 12.50, "pricing_max": 20, "pricing_unit": "user/month",
        "features": ["Unlimited Storage", "Advanced Sharing", "Version History", "Admin Tools", "Paper"],
        "users": "700M+", "rating": 4.4, "negotiable": True, "g2_score": 4.4,
        "integrations": ["Slack", "Zoom", "Microsoft Office", "Google Workspace"],
        "compliance": ["SOC2", "GDPR", "HIPAA", "ISO27001"]
    },
    {
        "name": "Figma", "category": "Design Tools",
        "description": "Collaborative interface design tool",
        "pricing_min": 0, "pricing_max": 15, "pricing_unit": "user/month",
        "features": ["Design", "Prototyping", "Real-time Collaboration", "Dev Mode", "FigJam"],
        "users": "4M+", "rating": 4.8, "negotiable": False, "g2_score": 4.7,
        "integrations": ["Slack", "Jira", "Notion", "Microsoft Teams"],
        "compliance": ["SOC2", "GDPR"]
    },
    {
        "name": "GitHub Enterprise", "category": "Developer Tools",
        "description": "Code hosting and collaboration platform",
        "pricing_min": 21, "pricing_max": 21, "pricing_unit": "user/month",
        "features": ["Version Control", "CI/CD", "Code Review", "Security Scanning", "Actions"],
        "users": "100M+", "rating": 4.8, "negotiable": True, "g2_score": 4.7,
        "integrations": ["Slack", "Jira", "Microsoft Teams", "VS Code"],
        "compliance": ["SOC2", "GDPR", "ISO27001"]
    }
]

# Initialize database
if not st.session_state.software_database:
    st.session_state.software_database = SOFTWARE_DATABASE


def call_openai(prompt, system_prompt="You are an expert software procurement consultant."):
    try:
        client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
        completion = client.chat.completions.create(
            model="gpt-4o-mini",  # or "gpt-4o" if you have access
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": prompt}
            ],
            temperature=0.7,
            max_tokens=1000
        )
        return completion.choices[0].message.content
    except Exception as e:
        return f"❌ OpenAI API Error: {e}"


# Sidebar
with st.sidebar:

    st.markdown("---")
    st.markdown("### πŸ“Š Quick Stats")
    if st.session_state.compare_list:
        st.metric("Selected for Comparison", len(st.session_state.compare_list))
    st.metric("Total Software", len(st.session_state.software_database))

    st.markdown("---")
    st.markdown("### 🎯 Navigation")
    page = st.radio("Go to:", [
        "🏠 Home",
        "πŸ” AI Matching Engine",
        "πŸ“Š Compare Software",
        "πŸ’‘ Strategy Optimizer",
        "🀝 Negotiation Assistant",
        "πŸ“ˆ Usage Analytics"
    ])

# Main content
if page == "🏠 Home":
    st.markdown('<h1 class="main-header">🎯 SoftwareGrid AI</h1>', unsafe_allow_html=True)
    st.markdown("### Intelligent Software Procurement & Negotiation Platform")

    col1, col2, col3 = st.columns(3)
    with col1:
        st.info("**🎯 AI Matching**\n\nIntelligent software recommendations based on your needs")
    with col2:
        st.info("**πŸ“Š Smart Comparison**\n\nMulti-dimensional analysis of features, pricing & TCO")
    with col3:
        st.info("**🀝 Negotiation AI**\n\nGet the best deals with data-driven negotiation strategies")

    st.markdown("---")
    st.markdown("## πŸš€ Quick Start")

    col1, col2 = st.columns(2)
    with col1:
        st.markdown("### 1️⃣ Tell Us Your Needs")
        company_size = st.selectbox("Company Size", ["1-10", "11-50", "51-200", "201-1000", "1000+"])
        industry = st.selectbox("Industry", ["Technology", "Healthcare", "Finance", "Education", "Retail", "Other"])
        budget = st.selectbox("Monthly Budget", ["<$1K", "$1K-$5K", "$5K-$20K", "$20K-$50K", "$50K+"])

        if st.button("🎯 Get AI Recommendations", type="primary"):
            with st.spinner("Analyzing your requirements..."):
                prompt = f"""
You are an expert enterprise software consultant. Based on the following company profile, recommend the top 5 software tools or vendor bundles that best fit their needs.

Company Profile:
- Company Size: {company_size} employees
- Industry: {industry}
- Monthly Budget: {budget}

Available software database:
{json.dumps([
    {"name": s["name"], "category": s["category"], "pricing": f"${s['pricing_min']}-{s['pricing_max']}/{s['pricing_unit']}"}
    for s in SOFTWARE_DATABASE
], indent=2)}

Please perform a holistic evaluation, considering:
1. **Functional Coverage Efficiency** β€” Prefer software that covers multiple business needs (reduce overlap).
2. **Vendor Consolidation** β€” Recommend single-vendor bundles when one company provides multiple complementary tools.
3. **Cost Efficiency** β€” Stay within the monthly budget and note potential savings from reduced redundancy.
4. **Integration Simplicity** β€” Fewer vendors β†’ lower integration and training overhead.
5. **Scalability and Fit** β€” Match features and complexity to company size and industry-specific workflows.
Note that the overlap issue should be taken into account. It is necessary to consider the situation where many functions can be accomplished by purchasing lisence from just one company
Provide recommendations with reasoning for each.
"""

                response = call_openai(prompt)
                st.success("βœ… Recommendations Generated!")
                st.markdown(response)

    with col2:
        st.markdown("### 2️⃣ Browse Software Catalog")
        categories = ["All"] + list(set([s["category"] for s in SOFTWARE_DATABASE]))
        selected_category = st.selectbox("Category", categories)

        filtered_software = SOFTWARE_DATABASE if selected_category == "All" else [s for s in SOFTWARE_DATABASE if s["category"] == selected_category]

        st.markdown(f"**{len(filtered_software)} software found**")

        for software in filtered_software[:5]:
            with st.expander(f"**{software['name']}** - {software['category']} ⭐ {software['rating']}"):
                st.markdown(f"*{software['description']}*")
                st.markdown(f"**πŸ’° Pricing:** ${software['pricing_min']}-${software['pricing_max']}/{software['pricing_unit']}")
                st.markdown(f"**πŸ‘₯ Users:** {software['users']}")
                if st.button(f"Add to Compare", key=f"home_compare_{software['name']}"):
                    if software not in st.session_state.compare_list:
                        st.session_state.compare_list.append(software)
                        st.success(f"Added {software['name']} to comparison!")
                    else:
                        st.warning("Already in comparison list")

elif page == "πŸ” AI Matching Engine":
    st.markdown('<h1 class="main-header">🎯 AI Software Matching Engine</h1>', unsafe_allow_html=True)
    st.markdown("### Let AI help you find the perfect software for your needs")

    tab1, tab2 = st.tabs(["πŸ’¬ Conversational Analysis", "πŸ“‹ Questionnaire"])

    with tab1:
        st.markdown("#### Chat with our AI to discover your perfect software match")

        # Chat interface
        for msg in st.session_state.chat_history:
            with st.chat_message(msg["role"]):
                st.markdown(msg["content"])

        user_input = st.chat_input("Describe your software needs...")

        if user_input:
            st.session_state.chat_history.append({"role": "user", "content": user_input})

            with st.chat_message("user"):
                st.markdown(user_input)

            with st.chat_message("assistant"):
                with st.spinner("Analyzing..."):
                    system_prompt = """You are an expert software procurement consultant. Help users find the best software solutions.
                    Ask clarifying questions about:
                    - Company size and structure
                    - Industry and use cases
                    - Budget constraints
                    - Current software stack
                    - Integration requirements
                    - Compliance needs

                    Be conversational and helpful. After gathering enough information, recommend specific software from the database."""

                    context = f"""
                    Chat history: {json.dumps(st.session_state.chat_history[-5:])}

                    Available software: {json.dumps([{"name": s["name"], "category": s["category"], "features": s["features"][:3]} for s in SOFTWARE_DATABASE], indent=2)}

                    User message: {user_input}
                    """

                    response = call_openai(context, system_prompt)
                    st.markdown(response)
                    st.session_state.chat_history.append({"role": "assistant", "content": response})

    with tab2:
        st.markdown("#### Complete this questionnaire for precise recommendations")

        with st.form("requirements_form"):
            col1, col2 = st.columns(2)

            with col1:
                team_size = st.number_input("Team Size", min_value=1, value=10)
                industry = st.selectbox("Industry", ["Technology", "Healthcare", "Finance", "Education", "Retail", "Manufacturing", "Other"])
                remote_work = st.selectbox("Work Model", ["Fully Remote", "Hybrid", "In-Office"])
                budget_range = st.selectbox("Monthly Budget per User", ["<$10", "$10-$30", "$30-$50", "$50-$100", "$100+"])

            with col2:
                needs = st.multiselect("Primary Needs", [
                    "Team Communication", "Video Conferencing", "Project Management",
                    "File Storage", "CRM", "Email", "Design Tools", "Developer Tools",
                    "Knowledge Management", "Time Tracking"
                ])
                integrations = st.multiselect("Must Integrate With", [
                    "Slack", "Microsoft Teams", "Google Workspace", "Salesforce",
                    "Jira", "GitHub", "Zoom"
                ])
                compliance = st.multiselect("Compliance Requirements", [
                    "GDPR", "HIPAA", "SOC2", "ISO27001"
                ])

            submitted = st.form_submit_button("🎯 Get AI Recommendations", type="primary")

            if submitted:
                with st.spinner("Analyzing your requirements with AI..."):
                    prompt = f"""Analyze these requirements and recommend the best software solutions:

                    Company Profile:
                    - Team Size: {team_size} people
                    - Industry: {industry}
                    - Work Model: {remote_work}
                    - Budget per User: {budget_range}

                    Requirements:
                    - Primary Needs: {', '.join(needs)}
                    - Required Integrations: {', '.join(integrations)}
                    - Compliance: {', '.join(compliance)}

                    Available software database:
                    {json.dumps(SOFTWARE_DATABASE, indent=2)}

                    Provide:
                    1. Top 5 recommended software with match scores
                    2. Functional gap analysis
                    3. Estimated total cost
                    4. Integration compatibility
                    5. Compliance coverage
                    """

                    response = call_openai(prompt)
                    st.success("βœ… Analysis Complete!")
                    st.markdown("### 🎯 AI Recommendations")
                    st.markdown(response)

                    # Extract recommended software
                    st.markdown("---")
                    st.markdown("### πŸ“Š Quick Compare Recommended Software")
                    cols = st.columns(3)
                    for idx, software in enumerate(SOFTWARE_DATABASE[:3]):
                        with cols[idx]:
                            st.markdown(f"**{software['name']}**")
                            st.markdown(f"⭐ {software['rating']}")
                            st.markdown(f"πŸ’° ${software['pricing_min']}-${software['pricing_max']}")
                            if st.button(f"Add to Compare", key=f"rec_{software['name']}"):
                                if software not in st.session_state.compare_list:
                                    st.session_state.compare_list.append(software)
                                    st.success(f"Added!")

elif page == "πŸ“Š Compare Software":
    st.markdown('<h1 class="main-header">πŸ“Š Multi-Dimensional Comparison</h1>', unsafe_allow_html=True)

    col1, col2 = st.columns([3, 1])
    with col1:
        st.markdown(f"### Compare up to 4 software solutions")
    with col2:
        if st.button("πŸ—‘οΈ Clear All"):
            st.session_state.compare_list = []
            st.rerun()

    # Software selector
    st.markdown("#### Add Software to Compare")
    col1, col2, col3 = st.columns(3)
    with col1:
        selected_software = st.selectbox(
            "Select Software",
            [s["name"] for s in SOFTWARE_DATABASE if s not in st.session_state.compare_list],
            key="software_selector"
        )
    with col2:
        if st.button("βž• Add to Comparison", type="primary"):
            software = next(s for s in SOFTWARE_DATABASE if s["name"] == selected_software)
            if len(st.session_state.compare_list) < 4:
                st.session_state.compare_list.append(software)
                st.success(f"Added {selected_software}!")
                st.rerun()
            else:
                st.error("Maximum 4 software can be compared")

    if len(st.session_state.compare_list) == 0:
        st.info("πŸ‘† Add software to start comparing")
    else:
        st.markdown(f"**{len(st.session_state.compare_list)} software selected**")

        # Display comparison cards
        cols = st.columns(len(st.session_state.compare_list))
        for idx, software in enumerate(st.session_state.compare_list):
            with cols[idx]:
                st.markdown(f"""
                <div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                            padding: 1rem; border-radius: 10px; color: white; text-align: center;'>
                    <h3>{software['name']}</h3>
                    <p style='margin: 0;'>{software['category']}</p>
                </div>
                """, unsafe_allow_html=True)
                st.markdown(f"⭐ **Rating:** {software['rating']}/5.0")
                if st.button("Remove", key=f"remove_{idx}"):
                    st.session_state.compare_list.pop(idx)
                    st.rerun()

        st.markdown("---")

        # Comparison tabs
        tab1, tab2, tab3, tab4, tab5 = st.tabs([
            "πŸ’° Pricing", "✨ Features", "πŸ”— Integrations", "πŸ“Š TCO Analysis", "πŸ€– AI Insights"
        ])

        with tab1:
            st.markdown("### πŸ’° Pricing Structure Comparison")

            # Pricing comparison table
            pricing_data = []
            for software in st.session_state.compare_list:
                pricing_data.append({
                    "Software": software["name"],
                    "Min Price": f"${software['pricing_min']}",
                    "Max Price": f"${software['pricing_max']}",
                    "Unit": software["pricing_unit"],
                    "Negotiable": "βœ…" if software["negotiable"] else "❌"
                })

            df_pricing = pd.DataFrame(pricing_data)
            st.dataframe(df_pricing, use_container_width=True)

            # Pricing chart
            st.markdown("#### Price Range Comparison")
            fig = go.Figure()
            for software in st.session_state.compare_list:
                fig.add_trace(go.Bar(
                    name=software["name"],
                    x=["Min Price", "Max Price"],
                    y=[software["pricing_min"], software["pricing_max"]],
                ))
            fig.update_layout(barmode='group', height=400)
            st.plotly_chart(fig, use_container_width=True)

            # TCO Calculator
            st.markdown("#### πŸ’΅ Total Cost of Ownership Calculator")
            num_users = st.slider("Number of Users", 1, 500, 50)
            contract_length = st.selectbox("Contract Length", ["Monthly", "Annual", "Multi-year"])

            st.markdown("**Estimated Annual Cost:**")
            for software in st.session_state.compare_list:
                avg_price = (software["pricing_min"] + software["pricing_max"]) / 2
                annual_cost = avg_price * num_users * 12
                discount = 0.15 if software["negotiable"] else 0
                final_cost = annual_cost * (1 - discount)

                st.metric(
                    software["name"],
                    f"${final_cost:,.0f}/year",
                    f"-${annual_cost * discount:,.0f} (negotiable)" if discount > 0 else "Fixed pricing"
                )

        with tab2:
            st.markdown("### ✨ Feature Matrix Comparison")

            all_features = set()
            for software in st.session_state.compare_list:
                all_features.update(software["features"])

            feature_matrix = []
            for feature in sorted(all_features):
                row = {"Feature": feature}
                for software in st.session_state.compare_list:
                    row[software["name"]] = "βœ…" if feature in software["features"] else "❌"
                feature_matrix.append(row)

            df_features = pd.DataFrame(feature_matrix)
            st.dataframe(df_features, use_container_width=True, height=400)

            # Feature coverage chart
            st.markdown("#### Feature Coverage Score")
            coverage_data = []
            for software in st.session_state.compare_list:
                coverage = (len(software["features"]) / len(all_features)) * 100
                coverage_data.append({"Software": software["name"], "Coverage": coverage})

            df_coverage = pd.DataFrame(coverage_data)
            fig = px.bar(df_coverage, x="Software", y="Coverage",
                        title="Feature Coverage (%)",
                        color="Coverage",
                        color_continuous_scale="Blues")
            st.plotly_chart(fig, use_container_width=True)

        with tab3:
            st.markdown("### πŸ”— Integration Compatibility")

            all_integrations = set()
            for software in st.session_state.compare_list:
                all_integrations.update(software["integrations"])

            integration_matrix = []
            for integration in sorted(all_integrations):
                row = {"Integration": integration}
                for software in st.session_state.compare_list:
                    row[software["name"]] = "βœ…" if integration in software["integrations"] else "❌"
                integration_matrix.append(row)

            df_integrations = pd.DataFrame(integration_matrix)
            st.dataframe(df_integrations, use_container_width=True)

            # Compliance comparison
            st.markdown("#### πŸ›‘οΈ Compliance & Security")
            compliance_matrix = []
            all_compliance = set()
            for software in st.session_state.compare_list:
                all_compliance.update(software["compliance"])

            for comp in sorted(all_compliance):
                row = {"Certification": comp}
                for software in st.session_state.compare_list:
                    row[software["name"]] = "βœ…" if comp in software["compliance"] else "❌"
                compliance_matrix.append(row)

            df_compliance = pd.DataFrame(compliance_matrix)
            st.dataframe(df_compliance, use_container_width=True)

        with tab4:
            st.markdown("### πŸ“Š Total Cost of Ownership (TCO) Analysis")

            st.markdown("#### Configure Your Scenario")
            col1, col2, col3 = st.columns(3)
            with col1:
                num_users_tco = st.number_input("Number of Users", 1, 1000, 50, key="tco_users")
            with col2:
                years = st.selectbox("Time Period", [1, 2, 3, 5], key="tco_years")
            with col3:
                include_costs = st.multiselect("Include", ["Training", "Migration", "Support"], default=["Training"])

            tco_data = []
            for software in st.session_state.compare_list:
                avg_price = (software["pricing_min"] + software["pricing_max"]) / 2
                subscription_cost = avg_price * num_users_tco * 12 * years

                training_cost = 100 * num_users_tco if "Training" in include_costs else 0
                migration_cost = 5000 if "Migration" in include_costs else 0
                support_cost = subscription_cost * 0.1 * years if "Support" in include_costs else 0

                total_tco = subscription_cost + training_cost + migration_cost + support_cost

                tco_data.append({
                    "Software": software["name"],
                    "Subscription": subscription_cost,
                    "Training": training_cost,
                    "Migration": migration_cost,
                    "Support": support_cost,
                    "Total TCO": total_tco
                })

            df_tco = pd.DataFrame(tco_data)

            # TCO breakdown chart
            fig = go.Figure()
            for cost_type in ["Subscription", "Training", "Migration", "Support"]:
                fig.add_trace(go.Bar(
                    name=cost_type,
                    x=df_tco["Software"],
                    y=df_tco[cost_type]
                ))
            fig.update_layout(barmode='stack', title="TCO Breakdown", height=400)
            st.plotly_chart(fig, use_container_width=True)

            # TCO table
            st.markdown("#### Detailed TCO Breakdown")
            st.dataframe(df_tco.style.format({
                "Subscription": "${:,.0f}",
                "Training": "${:,.0f}",
                "Migration": "${:,.0f}",
                "Support": "${:,.0f}",
                "Total TCO": "${:,.0f}"
            }), use_container_width=True)

        with tab5:
            st.markdown("### πŸ€– AI-Powered Insights")

            if st.button("🧠 Generate AI Analysis", type="primary"):
                with st.spinner("AI is analyzing your comparison..."):
                    prompt = f"""Analyze this software comparison and provide insights:

                    Software being compared:
                    {json.dumps(st.session_state.compare_list, indent=2)}

                    Provide:
                    1. **Best Overall Value**: Which offers the best balance of features and price?
                    2. **Best for Specific Use Cases**: Recommend which software for different scenarios
                    3. **Cost Optimization**: How to reduce costs while maintaining functionality
                    4. **Integration Strategy**: Which combination works best together
                    5. **Risk Assessment**: Potential issues or limitations
                    6. **Negotiation Opportunities**: Which vendors are most likely to offer discounts

                    Be specific and actionable."""

                    response = call_openai(prompt)
                    st.markdown(response)

            st.markdown("---")
            st.markdown("#### πŸ“ˆ Quick Recommendation Matrix")

            cols = st.columns(len(st.session_state.compare_list))
            for idx, software in enumerate(st.session_state.compare_list):
                with cols[idx]:
                    st.markdown(f"**{software['name']}**")

                    # Calculate scores
                    price_score = 5.0 - (software["pricing_max"] / 50)  # Simple price score
                    feature_score = min(5.0, len(software["features"]) / 2)
                    integration_score = min(5.0, len(software["integrations"]))

                    st.metric("Price Score", f"{max(1, price_score):.1f}/5")
                    st.metric("Feature Score", f"{feature_score:.1f}/5")
                    st.metric("Integration", f"{integration_score:.1f}/5")

elif page == "πŸ’‘ Strategy Optimizer":
    st.markdown('<h1 class="main-header">πŸ’‘ Strategy Combination Optimizer</h1>', unsafe_allow_html=True)
    st.markdown("### Find the optimal software stack for your organization")

    # Input parameters
    st.markdown("#### 🎯 Your Requirements")
    col1, col2, col3 = st.columns(3)
    with col1:
        team_size = st.number_input("Team Size", 1, 1000, 50)
    with col2:
        monthly_budget = st.number_input("Monthly Budget ($)", 100, 100000, 5000)
    with col3:
        optimization_goal = st.selectbox("Optimization Goal", [
            "Minimize Cost",
            "Maximize Features",
            "Best Integration",
            "Balanced Approach"
        ])

    required_categories = st.multiselect("Required Software Categories", [
        "Team Communication", "Video Conferencing", "Project Management",
        "Email & Productivity", "CRM", "Cloud Storage", "Developer Tools",
        "Design Tools", "Knowledge Management"
    ])

    if st.button("πŸš€ Generate Optimization Strategies", type="primary"):
        with st.spinner("AI is optimizing your software stack..."):
            prompt = f"""Create 3 optimal software stack strategies based on these requirements:

            Requirements:
            - Team Size: {team_size} people
            - Monthly Budget: ${monthly_budget}
            - Optimization Goal: {optimization_goal}
            - Required Categories: {', '.join(required_categories)}

            Available Software:
            {json.dumps(SOFTWARE_DATABASE, indent=2)}

            Generate 3 strategies:

            1. **All-in-One Solution**: Using comprehensive platforms (Microsoft 365, Google Workspace, etc.)
            2. **Best-of-Breed Combination**: Mix of specialized best-in-class tools
            3. **Budget-Optimized Hybrid**: Balance between functionality and cost

            For each strategy provide:
            - Recommended software list
            - Total monthly cost
            - Feature coverage percentage
            - Integration difficulty score (1-10)
            - Pros and cons
            - Learning curve assessment
            - ROI timeline
            """

            response = call_openai(prompt)

            st.success("βœ… Strategies Generated!")
            st.markdown(response)

            # Visual comparison
            st.markdown("---")
            st.markdown("### πŸ“Š Strategy Comparison Dashboard")

            # Mock data for visualization
            strategies = {
                "All-in-One": {"cost": monthly_budget * 0.8, "features": 85, "integration": 9, "learning": 6},
                "Best-of-Breed": {"cost": monthly_budget * 1.1, "features": 95, "integration": 6, "learning": 7},
                "Budget-Optimized": {"cost": monthly_budget * 0.6, "features": 75, "integration": 7, "learning": 5}
            }

            col1, col2, col3 = st.columns(3)

            for idx, (strategy_name, metrics) in enumerate(strategies.items()):
                with [col1, col2, col3][idx]:
                    st.markdown(f"""
                    <div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                                padding: 1.5rem; border-radius: 10px; color: white;'>
                        <h3 style='margin: 0; color: white;'>{strategy_name}</h3>
                        <p style='margin: 0.5rem 0 0 0; opacity: 0.9;'>Strategy {idx + 1}</p>
                    </div>
                    """, unsafe_allow_html=True)

                    st.metric("Monthly Cost", f"${metrics['cost']:.0f}")
                    st.metric("Feature Coverage", f"{metrics['features']}%")
                    st.metric("Integration Score", f"{metrics['integration']}/10")
                    st.metric("Learning Curve", f"{metrics['learning']}/10")

                    st.button(f"Select {strategy_name}", key=f"select_{strategy_name}")

            # Comparison radar chart
            st.markdown("#### πŸ“ˆ Multi-Dimensional Comparison")

            fig = go.Figure()

            for strategy_name, metrics in strategies.items():
                fig.add_trace(go.Scatterpolar(
                    r=[
                        (monthly_budget - metrics['cost']) / monthly_budget * 100,  # Cost efficiency
                        metrics['features'],
                        metrics['integration'] * 10,
                        (10 - metrics['learning']) * 10,  # Ease of learning (inverted)
                    ],
                    theta=['Cost Efficiency', 'Features', 'Integration', 'Ease of Use'],
                    fill='toself',
                    name=strategy_name
                ))

            fig.update_layout(
                polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
                showlegend=True,
                height=500
            )
            st.plotly_chart(fig, use_container_width=True)

elif page == "🀝 Negotiation Assistant":
    st.markdown('<h1 class="main-header">🀝 AI Negotiation Assistant</h1>', unsafe_allow_html=True)
    st.markdown("### Get the best deals with data-driven negotiation strategies")

    tab1, tab2, tab3, tab4 = st.tabs([
        "πŸ“Š Market Benchmarks", "πŸ’¬ Script Generator", "πŸ“… Best Timing", "πŸ“„ Contract Analysis"
    ])

    with tab1:
        st.markdown("### πŸ“Š Market Price Benchmarks")

        col1, col2 = st.columns([1, 2])

        with col1:
            selected_software_nego = st.selectbox(
                "Select Software",
                [s["name"] for s in SOFTWARE_DATABASE]
            )
            company_size_nego = st.selectbox("Company Size", ["1-10", "11-50", "51-200", "201-1000", "1000+"])
            contract_term = st.selectbox("Contract Term", ["Monthly", "1 Year", "2 Years", "3 Years"])

        with col2:
            software_nego = next(s for s in SOFTWARE_DATABASE if s["name"] == selected_software_nego)

            st.markdown(f"#### {software_nego['name']} Pricing Intelligence")

            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("List Price", f"${software_nego['pricing_max']}/user/mo")
            with col2:
                discount = 0.15 if software_nego["negotiable"] else 0
                st.metric("Typical Discount", f"{discount*100:.0f}%", "Negotiable" if software_nego["negotiable"] else "Fixed")
            with col3:
                negotiated_price = software_nego['pricing_max'] * (1 - discount)
                st.metric("Target Price", f"${negotiated_price:.2f}/user/mo")

            # Benchmark chart
            st.markdown("#### πŸ’° Price by Company Size")
            benchmark_data = pd.DataFrame({
                'Company Size': ['1-10', '11-50', '51-200', '201-1000', '1000+'],
                'Average Price': [
                    software_nego['pricing_max'],
                    software_nego['pricing_max'] * 0.95,
                    software_nego['pricing_max'] * 0.90,
                    software_nego['pricing_max'] * 0.85,
                    software_nego['pricing_max'] * 0.75
                ],
                'Discount %': [0, 5, 10, 15, 25]
            })

            fig = px.bar(benchmark_data, x='Company Size', y='Average Price',
                        title='Average Negotiated Price by Company Size',
                        color='Discount %',
                        color_continuous_scale='RdYlGn')
            st.plotly_chart(fig, use_container_width=True)

            # Similar companies data
            st.markdown("#### 🏒 Similar Companies Paid")
            similar_companies = pd.DataFrame({
                'Company': [f'Company {i}' for i in range(1, 6)],
                'Size': ['45', '52', '48', '55', '50'],
                'Industry': ['Tech', 'Finance', 'Healthcare', 'Tech', 'Education'],
                'Price/User': [f'${software_nego["pricing_max"] * (0.85 + i*0.02):.2f}' for i in range(5)],
                'Contract': ['2 Year', '1 Year', '3 Year', '2 Year', '1 Year']
            })
            st.dataframe(similar_companies, use_container_width=True)

    with tab2:
        st.markdown("### πŸ’¬ AI Negotiation Script Generator")

        st.markdown("#### Your Negotiation Context")
        col1, col2 = st.columns(2)

        with col1:
            nego_software = st.selectbox("Software to Negotiate", [s["name"] for s in SOFTWARE_DATABASE], key="script_software")
            num_licenses = st.number_input("Number of Licenses", 1, 1000, 50, key="script_licenses")
            current_price = st.number_input("Current Quote (per user/month)", 0.0, 1000.0, 20.0, key="script_price")

        with col2:
            contract_length_nego = st.selectbox("Proposed Contract Length", ["1 Year", "2 Years", "3 Years"], key="script_contract")
            leverage_points = st.multiselect("Your Leverage", [
                "Multiple vendors being evaluated",
                "Existing customer",
                "Large team size",
                "Multi-year commitment",
                "Competitor offers better price",
                "Budget constraints",
                "Referral potential"
            ])
            negotiation_style = st.selectbox("Negotiation Style", ["Professional", "Friendly", "Assertive"])

        if st.button("🎯 Generate Negotiation Script", type="primary"):
            with st.spinner("Crafting your personalized negotiation strategy..."):
                prompt = f"""Create a detailed negotiation script for:

                Context:
                - Software: {nego_software}
                - Number of Licenses: {num_licenses}
                - Current Quote: ${current_price}/user/month
                - Desired Contract: {contract_length_nego}
                - Leverage Points: {', '.join(leverage_points)}
                - Style: {negotiation_style}

                Generate:
                1. **Email Template**: Initial negotiation email
                2. **Call Script**: Talking points for sales call
                3. **Counter-Offer Strategy**: Specific discount requests with justification
                4. **Fallback Positions**: Alternative asks if primary request is denied
                5. **Closing Tactics**: How to finalize the deal
                6. **Common Objections & Responses**: How to handle pushback

                Make it professional, specific, and actionable. Include actual price points and percentages."""

                response = call_openai(prompt, system_prompt="You are an expert B2B software negotiation consultant with 20 years of experience.")

                st.success("βœ… Negotiation Script Generated!")
                st.markdown(response)

                # Download button
                st.download_button(
                    label="πŸ“₯ Download Script",
                    data=response,
                    file_name=f"negotiation_script_{nego_software}.txt",
                    mime="text/plain"
                )

    with tab3:
        st.markdown("### πŸ“… Best Time to Purchase")

        col1, col2 = st.columns(2)

        with col1:
            st.markdown("#### πŸ—“οΈ Optimal Purchase Timing")

            timing_data = pd.DataFrame({
                'Period': ['Q1', 'Q2', 'Q3', 'Q4'],
                'Discount Potential': [15, 10, 12, 25],
                'Sales Pressure': ['Low', 'Medium', 'Medium', 'Very High']
            })

            fig = px.bar(timing_data, x='Period', y='Discount Potential',
                        title='Average Discount Potential by Quarter',
                        color='Discount Potential',
                        color_continuous_scale='RdYlGn')
            st.plotly_chart(fig, use_container_width=True)

            st.info("**πŸ’‘ Best Time**: End of Q4 (December) when sales teams are closing their year")

            st.markdown("#### πŸ“† Current Opportunities")
            current_month = datetime.now().strftime("%B")
            st.success(f"**Current Month**: {current_month}")

            if "December" in current_month or "June" in current_month:
                st.success("πŸŽ‰ **EXCELLENT TIME TO NEGOTIATE!** End of fiscal period for many companies.")
            elif "September" in current_month or "March" in current_month:
                st.info("βœ… **GOOD TIME** - End of quarter, moderate pressure on sales teams.")
            else:
                st.warning("⏰ Consider waiting until end of quarter for better deals.")

        with col2:
            st.markdown("#### 🎯 Timing Strategies")

            strategies = [
                {"strategy": "End of Quarter", "potential": "15-20%", "risk": "Low"},
                {"strategy": "End of Fiscal Year", "potential": "20-30%", "risk": "Low"},
                {"strategy": "During Product Launch", "potential": "10-15%", "risk": "Medium"},
                {"strategy": "Competitor Announcement", "potential": "15-25%", "risk": "Medium"},
                {"strategy": "Contract Renewal", "potential": "10-20%", "risk": "Low"}
            ]

            for strategy in strategies:
                with st.expander(f"**{strategy['strategy']}** - {strategy['potential']} discount"):
                    st.markdown(f"**Discount Potential**: {strategy['potential']}")
                    st.markdown(f"**Risk Level**: {strategy['risk']}")

            st.markdown("#### 🎁 Seasonal Promotions")
            st.markdown("""
            - **Black Friday/Cyber Monday**: Special promotions
            - **New Year**: Fresh budgets, soft launches
            - **Summer**: Mid-year deals
            - **Back to School**: Education-focused promotions
            """)

    with tab4:
        st.markdown("### πŸ“„ AI Contract Analysis")

        st.markdown("#### Upload or Paste Your Contract")

        input_method = st.radio("Input Method", ["Paste Text", "Upload File"])

        contract_text = ""
        if input_method == "Paste Text":
            contract_text = st.text_area("Paste Contract Text", height=200,
                                        placeholder="Paste your software contract or terms of service here...")
        else:
            uploaded_file = st.file_uploader("Upload Contract (PDF or TXT)", type=["pdf", "txt"])
            if uploaded_file:
                contract_text = uploaded_file.read().decode("utf-8", errors="ignore")
                st.success("Contract uploaded!")

        if st.button("πŸ” Analyze Contract", type="primary") and contract_text:
            with st.spinner("AI is analyzing your contract..."):
                prompt = f"""Analyze this software contract and identify:

                Contract Text:
                {contract_text[:4000]}  # Limit for token size

                Provide detailed analysis:

                1. **🚨 Risk Factors**:
                   - Automatic renewal clauses
                   - Price increase rights
                   - Unfavorable termination terms
                   - Data ownership issues
                   - Liability limitations

                2. **βœ… Compliance Check**:
                   - GDPR compliance
                   - SOC2/ISO27001 mentions
                   - Data privacy protections
                   - SLA commitments

                3. **πŸ’° Financial Terms**:
                   - Payment terms
                   - Refund policy
                   - Price adjustment clauses
                   - Hidden fees

                4. **βš–οΈ Legal Concerns**:
                   - Jurisdiction and governing law
                   - Dispute resolution
                   - Indemnification clauses
                   - IP rights

                5. **✍️ Recommendations**:
                   - Terms to negotiate
                   - Red flags to address
                   - Missing protections
                   - Overall risk score (1-10)

                Be specific and highlight exact problematic clauses."""

                response = call_openai(prompt, system_prompt="You are an expert software contract attorney specializing in SaaS agreements.")

                st.success("βœ… Contract Analysis Complete!")

                # Display in organized sections
                col1, col2 = st.columns(2)

                with col1:
                    st.markdown("### 🚨 Risk Assessment")
                    st.error("**High Risk Items Found**")
                    st.markdown(response[:len(response)//2])

                with col2:
                    st.markdown("### βœ… Recommendations")
                    st.info("**Action Items**")
                    st.markdown(response[len(response)//2:])

                st.download_button(
                    label="πŸ“₯ Download Full Analysis",
                    data=response,
                    file_name="contract_analysis.txt",
                    mime="text/plain"
                )

elif page == "πŸ“ˆ Usage Analytics":
    st.markdown('<h1 class="main-header">πŸ“ˆ Usage Monitoring & Optimization</h1>', unsafe_allow_html=True)
    st.markdown("### Track usage and identify cost-saving opportunities")

    # Dashboard metrics
    col1, col2, col3, col4 = st.columns(4)

    with col1:
        st.metric("Total Monthly Spend", "$45,000", "-12% vs last month", delta_color="normal")
    with col2:
        st.metric("Active Subscriptions", "23", "+2", delta_color="inverse")
    with col3:
        st.metric("Unused Licenses", "47", "-5", delta_color="normal")
    with col4:
        st.metric("Potential Savings", "$8,400", "+$1,200", delta_color="normal")

    st.markdown("---")

    tab1, tab2, tab3, tab4 = st.tabs([
        "πŸ“Š Overview", "πŸ’° Cost Analysis", "πŸ‘₯ License Utilization", "🎯 Optimization"
    ])

    with tab1:
        st.markdown("### πŸ“Š Software Portfolio Overview")

        # Mock usage data
        usage_data = []
        for software in SOFTWARE_DATABASE[:8]:
            usage_data.append({
                "Software": software["name"],
                "Licenses": 50,
                "Active Users": int(50 * (0.6 + 0.3 * (hash(software["name"]) % 10) / 10)),
                "Monthly Cost": software["pricing_max"] * 50,
                "Category": software["category"]
            })

        df_usage = pd.DataFrame(usage_data)
        df_usage["Utilization %"] = (df_usage["Active Users"] / df_usage["Licenses"] * 100).round(1)
        df_usage["Waste"] = df_usage["Monthly Cost"] * (1 - df_usage["Active Users"] / df_usage["Licenses"])

        # Usage chart
        col1, col2 = st.columns(2)

        with col1:
            fig = px.bar(df_usage, x="Software", y="Utilization %",
                        title="License Utilization by Software",
                        color="Utilization %",
                        color_continuous_scale="RdYlGn",
                        range_color=[0, 100])
            st.plotly_chart(fig, use_container_width=True)

        with col2:
            fig = px.pie(df_usage, values="Monthly Cost", names="Software",
                        title="Cost Distribution")
            st.plotly_chart(fig, use_container_width=True)

        # Detailed table
        st.markdown("#### πŸ“‹ Detailed Usage Report")
        st.dataframe(
            df_usage.style.format({
                "Monthly Cost": "${:,.0f}",
                "Waste": "${:,.0f}",
                "Utilization %": "{:.1f}%"
            }).background_gradient(subset=["Utilization %"], cmap="RdYlGn", vmin=0, vmax=100),
            use_container_width=True
        )

    with tab2:
        st.markdown("### πŸ’° Cost Analysis & Trends")

        # Monthly spend trend
        months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
        spend_data = pd.DataFrame({
            'Month': months,
            'Spend': [42000, 43500, 45000, 46000, 44500, 45000],
            'Budget': [50000] * 6
        })

        fig = go.Figure()
        fig.add_trace(go.Scatter(x=spend_data['Month'], y=spend_data['Spend'],
                                mode='lines+markers', name='Actual Spend',
                                line=dict(color='#667eea', width=3)))
        fig.add_trace(go.Scatter(x=spend_data['Month'], y=spend_data['Budget'],
                                mode='lines', name='Budget',
                                line=dict(color='red', width=2, dash='dash')))
        fig.update_layout(title='Monthly Software Spend Trend', height=400)
        st.plotly_chart(fig, use_container_width=True)

        # Cost by category
        col1, col2 = st.columns(2)

        with col1:
            category_spend = df_usage.groupby('Category')['Monthly Cost'].sum().reset_index()
            fig = px.bar(category_spend, x='Category', y='Monthly Cost',
                        title='Spend by Category',
                        color='Monthly Cost',
                        color_continuous_scale='Blues')
            st.plotly_chart(fig, use_container_width=True)

        with col2:
            st.markdown("#### πŸ’΅ Top 5 Expenses")
            top_expenses = df_usage.nlargest(5, 'Monthly Cost')[['Software', 'Monthly Cost']]
            for idx, row in top_expenses.iterrows():
                st.metric(row['Software'], f"${row['Monthly Cost']:,.0f}/mo")

    with tab3:
        st.markdown("### πŸ‘₯ License Utilization Analysis")

        # Utilization heatmap
        st.markdown("#### πŸ“Š Utilization Heatmap")

        # Mock weekly usage data
        weeks = ['Week 1', 'Week 2', 'Week 3', 'Week 4']
        software_list = df_usage['Software'].tolist()[:6]

        heatmap_data = []
        for software in software_list:
            weekly_usage = [int(50 + (hash(software + week) % 30)) for week in weeks]
            heatmap_data.append(weekly_usage)

        fig = go.Figure(data=go.Heatmap(
            z=heatmap_data,
            x=weeks,
            y=software_list,
            colorscale='RdYlGn',
            text=heatmap_data,
            texttemplate='%{text}%',
            textfont={"size": 10}
        ))
        fig.update_layout(title='Usage Patterns Over Time (%)', height=400)
        st.plotly_chart(fig, use_container_width=True)

        # Inactive users
        st.markdown("#### ⚠️ Inactive License Alert")

        inactive_data = []
        for software in SOFTWARE_DATABASE[:5]:
            inactive_count = int(50 * (0.1 + 0.2 * (hash(software["name"]) % 10) / 10))
            if inactive_count > 5:
                inactive_data.append({
                    "Software": software["name"],
                    "Inactive Licenses": inactive_count,
                    "Potential Savings": f"${inactive_count * software['pricing_max']:.0f}/mo",
                    "Last Activity": f"{hash(software['name']) % 30 + 30} days ago"
                })

        df_inactive = pd.DataFrame(inactive_data)

        for idx, row in df_inactive.iterrows():
            with st.expander(f"⚠️ **{row['Software']}** - {row['Inactive Licenses']} inactive licenses"):
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.metric("Inactive Licenses", row['Inactive Licenses'])
                with col2:
                    st.metric("Potential Savings", row['Potential Savings'])
                with col3:
                    st.metric("Last Activity", row['Last Activity'])

                if st.button(f"Review Users for {row['Software']}", key=f"review_{idx}"):
                    st.info("User review interface would open here in production")

    with tab4:
        st.markdown("### 🎯 AI-Powered Optimization Recommendations")

        if st.button("πŸ€– Generate Optimization Report", type="primary"):
            with st.spinner("AI is analyzing your usage data..."):
                prompt = f"""Analyze this software usage data and provide optimization recommendations:

                Current Software Portfolio:
                {df_usage.to_json(orient='records')}

                Total Monthly Spend: $45,000
                Unused Licenses: 47
                Average Utilization: {df_usage['Utilization %'].mean():.1f}%

                Provide:
                1. **Immediate Actions** (Quick wins for cost savings)
                2. **Consolidation Opportunities** (Software that can be replaced/combined)
                3. **Right-sizing Recommendations** (License adjustments)
                4. **Alternative Solutions** (Better value options)
                5. **Implementation Priority** (What to tackle first)
                6. **Expected Savings** (Quantify the impact)

                Be specific with dollar amounts and actionable steps."""

                response = call_openai(prompt)

                st.success("βœ… Optimization Report Generated!")
                st.markdown(response)

        st.markdown("---")
        st.markdown("#### πŸ’‘ Quick Wins")

        col1, col2 = st.columns(2)

        with col1:
            st.warning("**⚠️ Remove Unused Licenses**")
            st.markdown("47 inactive licenses detected")
            st.markdown("**Potential Savings**: $8,400/year")
            st.button("Start License Cleanup", key="cleanup")

        with col2:
            st.info("**πŸ’° Bundle Opportunity**")
            st.markdown("Consolidate 4 tools into Microsoft 365")
            st.markdown("**Potential Savings**: $3,840/year")
            st.button("Explore Bundle", key="bundle")

        # Optimization roadmap
        st.markdown("#### πŸ—ΊοΈ Optimization Roadmap")

        roadmap = [
            {"Month": "Month 1", "Action": "Remove inactive licenses", "Savings": "$700/mo"},
            {"Month": "Month 2", "Action": "Renegotiate Slack contract", "Savings": "$300/mo"},
            {"Month": "Month 3", "Action": "Switch to annual billing", "Savings": "$450/mo"},
            {"Month": "Month 4", "Action": "Consolidate to Microsoft 365", "Savings": "$320/mo"},
        ]

        for item in roadmap:
            st.success(f"**{item['Month']}**: {item['Action']} β†’ {item['Savings']} savings")

# Footer
st.markdown("---")
st.markdown("""
<div style='text-align: center; color: #666; padding: 2rem;'>
    <p><strong>SoftwareGrid AI</strong> - Intelligent Software Procurement Platform</p>
    <p>Powered by Open AI | Made with Streamlit</p>
</div>
""", unsafe_allow_html=True)