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
 
 
 
 
 
 
 
 
 
 
ea1c770
 
 
 
 
 
 
 
 
0caeb0d
 
 
 
 
 
ea1c770
 
 
 
a87ed52
 
 
 
 
 
 
 
 
ea1c770
 
 
 
0caeb0d
ea1c770
0caeb0d
 
 
f800176
ea1c770
0caeb0d
ea1c770
 
 
f800176
ea1c770
0caeb0d
ea1c770
 
 
f800176
ea1c770
0caeb0d
ea1c770
 
0caeb0d
ea1c770
 
0caeb0d
ea1c770
 
0caeb0d
ea1c770
 
 
 
 
0caeb0d
f800176
0caeb0d
ea1c770
 
 
f800176
ea1c770
0caeb0d
 
f800176
 
 
 
0caeb0d
ea1c770
0caeb0d
f800176
 
0caeb0d
f800176
ea1c770
f800176
ea1c770
0caeb0d
ea1c770
 
0caeb0d
ea1c770
f800176
 
ea1c770
0caeb0d
ea1c770
0caeb0d
 
f800176
ea1c770
 
9e49eef
ea1c770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad06818
 
ea1c770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f800176
ea1c770
 
f800176
ea1c770
9e49eef
ea1c770
f800176
ea1c770
f800176
ea1c770
9e49eef
ea1c770
f800176
ea1c770
f800176
ea1c770
9e49eef
ea1c770
f800176
ea1c770
f800176
ea1c770
9e49eef
ea1c770
f800176
ea1c770
f800176
ea1c770
 
 
f800176
 
ea1c770
 
 
 
 
 
 
 
 
 
 
f800176
0caeb0d
ea1c770
 
 
 
 
 
 
 
 
f800176
ea1c770
 
 
0caeb0d
ea1c770
 
f800176
ea1c770
 
0caeb0d
ea1c770
 
f800176
ea1c770
 
ad06818
 
 
 
 
 
ea1c770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
AI Project Planner - Agentic Workflow for Technical Project Management

A professional Gradio application that transforms product specifications into
comprehensive project plans using orchestrated AI agents.

Author: AI Workflow Architect
License: MIT
"""

import gradio as gr
import json
import time
from openai import OpenAI
from datetime import datetime
from typing import Generator, Tuple, Dict, Any, List
import os


def test_api_connection(api_key: str) -> str:
    """Test if the API key works."""
    if not api_key or len(api_key) < 20:
        return "❌ No API key provided"

    try:
        # Detect provider
        if api_key.startswith("sk-ant-"):
            provider = "Anthropic"
            import anthropic
            client = anthropic.Anthropic(api_key=api_key)
            response = client.messages.create(
                model="claude-3-haiku-20240307",
                max_tokens=50,
                messages=[{"role": "user", "content": "Say 'API working' in 2 words"}]
            )
            result = response.content[0].text
        elif api_key.startswith("voc-"):
            provider = "Vocareum"
            client = OpenAI(
                api_key=api_key,
                base_url="https://openai.vocareum.com/v1"
            )
            response = client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[{"role": "user", "content": "Say 'API working' in 2 words"}],
                max_tokens=50
            )
            result = response.choices[0].message.content
        else:
            provider = "OpenAI"
            client = OpenAI(api_key=api_key)
            response = client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[{"role": "user", "content": "Say 'API working' in 2 words"}],
                max_tokens=50
            )
            result = response.choices[0].message.content

        return f"βœ… {provider} API connected successfully! Response: {result}"

    except Exception as e:
        return f"❌ Connection failed: {str(e)}"

# Import the agent library
from base_agents import (
    ActionPlanningAgent,
    KnowledgeAugmentedPromptAgent,
    EvaluationAgent,
    RoutingAgent
)

# ============================================================================
# CUSTOM CSS FOR PROFESSIONAL STYLING
# ============================================================================

CUSTOM_CSS = """
/* Import Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');

/* Root Variables */
:root {
    --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    --success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    --card-border: #2d2d44;
    --accent-purple: #667eea;
    --accent-pink: #f093fb;
    --accent-cyan: #00f2fe;
}

/* Global Styles */
.gradio-container {
    font-family: 'Space Grotesk', sans-serif !important;
    background: #f8f9fa !important;
    max-width: 1400px !important;
}

/* Header Styling */
.header-container {
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
    border: 1px solid var(--card-border);
    border-radius: 20px;
    padding: 2rem;
    margin-bottom: 1.5rem;
    position: relative;
    overflow: hidden;
}

.header-container::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: var(--primary-gradient);
}

.header-title {
    font-size: 2.5rem;
    font-weight: 700;
    background: var(--primary-gradient);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin-bottom: 0.5rem;
}

.header-subtitle {
    color: var(--text-secondary);
    font-size: 1.1rem;
    font-weight: 400;
}

/* Card Styling */
.input-card, .output-card, .workflow-card {
    background: var(--card-bg) !important;
    border: 1px solid var(--card-border) !important;
    border-radius: 16px !important;
    padding: 1.5rem !important;
}

/* Workflow Progress */
.workflow-step {
    display: flex;
    align-items: center;
    padding: 1rem;
    margin: 0.5rem 0;
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid transparent;
    transition: all 0.3s ease;
}

.workflow-step.active {
    background: rgba(102, 126, 234, 0.1);
    border-color: var(--accent-purple);
}

.workflow-step.completed {
    background: rgba(0, 242, 254, 0.1);
    border-color: var(--accent-cyan);
}

.step-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
    font-size: 1.2rem;
}

.step-icon.waiting {
    background: rgba(255, 255, 255, 0.1);
}

.step-icon.active {
    background: var(--primary-gradient);
    animation: pulse 2s infinite;
}

.step-icon.completed {
    background: var(--success-gradient);
}

@keyframes pulse {
    0%, 100% { transform: scale(1); opacity: 1; }
    50% { transform: scale(1.05); opacity: 0.8; }
}

/* Button Styling */
.primary-btn {
    background: var(--primary-gradient) !important;
    border: none !important;
    border-radius: 12px !important;
    padding: 1rem 2rem !important;
    font-weight: 600 !important;
    font-size: 1rem !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important;
}

.primary-btn:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
}

.secondary-btn {
    background: transparent !important;
    border: 1px solid var(--card-border) !important;
    border-radius: 12px !important;
    color: var(--text-secondary) !important;
    transition: all 0.3s ease !important;
}

.secondary-btn:hover {
    border-color: var(--accent-purple) !important;
    color: var(--accent-purple) !important;
}

/* Tab Styling */
.tabs {
    border: none !important;
}

.tab-nav {
    background: transparent !important;
    border-bottom: 1px solid var(--card-border) !important;
    gap: 0.5rem !important;
}

.tab-nav button {
    background: transparent !important;
    border: none !important;
    border-radius: 8px 8px 0 0 !important;
    color: var(--text-secondary) !important;
    padding: 0.75rem 1.5rem !important;
    font-weight: 500 !important;
    transition: all 0.3s ease !important;
}

.tab-nav button.selected {
    background: rgba(102, 126, 234, 0.2) !important;
    color: var(--accent-purple) !important;
    border-bottom: 2px solid var(--accent-purple) !important;
}

/* Textbox Styling */
.textbox textarea {
    background: rgba(0, 0, 0, 0.3) !important;
    border: 1px solid var(--card-border) !important;
    border-radius: 12px !important;
    color: var(--text-primary) !important;
    font-family: 'JetBrains Mono', monospace !important;
    font-size: 0.9rem !important;
    padding: 1rem !important;
}

.textbox textarea:focus {
    border-color: var(--accent-purple) !important;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2) !important;
}

/* Markdown Styling */
.markdown-text {
    color: var(--text-primary) !important;
}

.markdown-text h1, .markdown-text h2, .markdown-text h3 {
    color: var(--text-primary) !important;
    font-weight: 600 !important;
}

.markdown-text code {
    background: rgba(102, 126, 234, 0.2) !important;
    color: var(--accent-cyan) !important;
    padding: 0.2rem 0.5rem !important;
    border-radius: 4px !important;
    font-family: 'JetBrains Mono', monospace !important;
}

/* Stats Card */
.stats-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
    margin-top: 1rem;
}

.stat-card {
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid var(--card-border);
    border-radius: 12px;
    padding: 1rem;
    text-align: center;
}

.stat-value {
    font-size: 1.5rem;
    font-weight: 700;
    background: var(--primary-gradient);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.stat-label {
    font-size: 0.85rem;
    color: var(--text-secondary);
    margin-top: 0.25rem;
}

/* Agent Badge */
.agent-badge {
    display: inline-flex;
    align-items: center;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 500;
    margin-right: 0.5rem;
}

.agent-badge.product-manager {
    background: rgba(102, 126, 234, 0.2);
    color: #667eea;
}

.agent-badge.program-manager {
    background: rgba(240, 147, 251, 0.2);
    color: #f093fb;
}

.agent-badge.dev-engineer {
    background: rgba(0, 242, 254, 0.2);
    color: #00f2fe;
}

/* Accordion Styling */
.accordion {
    border: 1px solid var(--card-border) !important;
    border-radius: 12px !important;
    background: var(--card-bg) !important;
    margin-bottom: 0.5rem !important;
}

/* File Upload */
.file-upload {
    border: 2px dashed var(--card-border) !important;
    border-radius: 12px !important;
    background: rgba(0, 0, 0, 0.2) !important;
    transition: all 0.3s ease !important;
}

.file-upload:hover {
    border-color: var(--accent-purple) !important;
    background: rgba(102, 126, 234, 0.05) !important;
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: var(--dark-bg);
}

::-webkit-scrollbar-thumb {
    background: var(--card-border);
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: var(--accent-purple);
}

/* Loading Animation */
.loading-dots {
    display: inline-flex;
    gap: 4px;
}

.loading-dots span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--accent-purple);
    animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
}

/* Progress Bar */
.progress-bar {
    height: 4px;
    background: var(--card-border);
    border-radius: 2px;
    overflow: hidden;
    margin-top: 0.5rem;
}

.progress-bar-fill {
    height: 100%;
    background: var(--primary-gradient);
    border-radius: 2px;
    transition: width 0.5s ease;
}

/* Example Card */
.example-card {
    background: rgba(255, 255, 255, 0.02);
    border: 1px solid var(--card-border);
    border-radius: 12px;
    padding: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
}

.example-card:hover {
    border-color: var(--accent-purple);
    transform: translateY(-2px);
}

.example-title {
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 0.5rem;
}

.example-desc {
    font-size: 0.85rem;
    color: var(--text-secondary);
}
"""

# ============================================================================
# EXAMPLE PRODUCT SPECIFICATIONS
# ============================================================================

EXAMPLE_SPECS = {
    "Email Router": """# Email Router Product Specification

## Executive Summary
The Email Router is an intelligent email management system designed to automatically classify, route, and respond to incoming emails using advanced NLP and machine learning capabilities.

## Target Users
- Customer Support Representatives
- IT Administrators  
- Subject Matter Experts (SMEs)
- Business Operations Teams

## Core Features

### 1. Intelligent Email Classification
- Automatic categorization of incoming emails by intent, urgency, and topic
- Support for custom classification rules and machine learning models
- Real-time processing with sub-second latency requirements

### 2. Smart Routing Engine
- Rule-based routing to appropriate departments or individuals
- Load balancing across support teams
- Escalation workflows for high-priority items
- Integration with existing ticketing systems

### 3. Automated Response System
- Template-based auto-replies for common inquiries
- AI-generated response suggestions for complex queries
- Sentiment analysis to adjust tone appropriately
- Multi-language support

### 4. Analytics Dashboard
- Real-time metrics on email volume, response times, and resolution rates
- Historical trend analysis and forecasting
- Agent performance tracking
- Customer satisfaction scoring

### 5. Administration Console
- User and role management
- Routing rule configuration
- Knowledge base management
- System health monitoring

## Technical Requirements
- Process 10,000+ emails per hour
- 99.9% uptime SLA
- Integration via SMTP, IMAP, and REST APIs
- SOC 2 Type II compliance
- GDPR and CCPA data handling

## Success Metrics
- 70% reduction in manual email triage time
- 50% improvement in first-response time
- 90% customer satisfaction score
- 95% routing accuracy
""",
    
    "Task Management App": """# Task Management Application Specification

## Product Vision
A modern, collaborative task management platform that helps teams organize work, track progress, and meet deadlines efficiently.

## Target Users
- Project Managers
- Team Members
- Executives/Stakeholders
- Remote Teams

## Core Features

### 1. Task Creation & Organization
- Create tasks with titles, descriptions, due dates, and priorities
- Organize tasks into projects and workspaces
- Support for subtasks and checklists
- File attachments and rich text descriptions

### 2. Collaboration Tools
- Assign tasks to team members
- Comment threads on tasks
- @mentions and notifications
- Real-time updates and sync

### 3. Views & Visualization
- List view for detailed task management
- Kanban board for workflow visualization
- Calendar view for deadline tracking
- Gantt chart for project timeline

### 4. Automation
- Recurring task creation
- Due date reminders
- Status change triggers
- Integration webhooks

### 5. Reporting & Analytics
- Project progress dashboards
- Team workload distribution
- Time tracking and estimates
- Custom report generation

## Technical Requirements
- Web, iOS, and Android applications
- Real-time synchronization
- Offline mode support
- Third-party integrations (Slack, GitHub, Google Calendar)
- Enterprise SSO support

## Success Metrics
- 30% improvement in project delivery time
- 50% reduction in missed deadlines
- 85% daily active user rate
- 4.5+ app store rating
""",

    "E-Commerce Platform": """# E-Commerce Platform Specification

## Product Overview
A scalable e-commerce platform enabling businesses to create online stores, manage inventory, process payments, and fulfill orders.

## Target Users
- Small Business Owners
- E-commerce Managers
- Warehouse Staff
- Customer Service Teams

## Core Features

### 1. Store Management
- Customizable storefront templates
- Product catalog management
- Category and collection organization
- SEO optimization tools

### 2. Inventory System
- Real-time stock tracking
- Multi-warehouse support
- Low stock alerts
- Supplier management

### 3. Order Processing
- Shopping cart functionality
- Multiple payment gateways
- Order status tracking
- Return and refund handling

### 4. Customer Management
- Customer accounts and profiles
- Order history
- Wishlist functionality
- Loyalty program support

### 5. Analytics & Reports
- Sales dashboards
- Customer behavior analytics
- Inventory reports
- Financial summaries

## Technical Requirements
- Support 100,000+ concurrent users
- PCI DSS compliance
- Mobile-responsive design
- API for third-party integrations
- Multi-currency and multi-language

## Success Metrics
- 99.99% checkout availability
- <2 second page load time
- 3% conversion rate
- <1% cart abandonment from technical issues
"""
}

# ============================================================================
# WORKFLOW KNOWLEDGE DEFINITIONS
# ============================================================================

KNOWLEDGE_ACTION_PLANNING = """
Stories are defined from a product spec by identifying a persona, an action, and a desired outcome for each story. 
Each story represents a specific functionality of the product described in the specification.
Features are defined by grouping related user stories into cohesive capabilities.
Tasks are defined for each story and represent the engineering work required to develop the product.
A development Plan for a product contains all these components organized in a logical structure.
"""

PERSONA_PRODUCT_MANAGER = "You are a Product Manager responsible for defining user stories for a product."
PERSONA_PROGRAM_MANAGER = "You are a Program Manager responsible for defining product features."
PERSONA_DEV_ENGINEER = "You are a Development Engineer responsible for defining engineering tasks."

EVALUATION_CRITERIA_USER_STORIES = (
    "The answer should be stories that follow the following structure: "
    "As a [type of user], I want [an action or feature] so that [benefit/value]."
)

EVALUATION_CRITERIA_FEATURES = (
    "The answer should be product features that follow the following structure: "
    "Feature Name: A clear, concise title that identifies the capability\n"
    "Description: A brief explanation of what the feature does and its purpose\n"
    "Key Functionality: The specific capabilities or actions the feature provides\n"
    "User Benefit: How this feature creates value for the user"
)

EVALUATION_CRITERIA_TASKS = (
    "The answer should be tasks following this exact structure: "
    "Task ID: A unique identifier for tracking purposes\n"
    "Task Title: Brief description of the specific development work\n"
    "Related User Story: Reference to the parent user story\n"
    "Description: Detailed explanation of the technical work required\n"
    "Acceptance Criteria: Specific requirements that must be met for completion\n"
    "Estimated Effort: Time or complexity estimation\n"
    "Dependencies: Any tasks that must be completed first"
)

# ============================================================================
# WORKFLOW ENGINE
# ============================================================================

class ProjectPlannerWorkflow:
    """
    Orchestrates the multi-agent workflow for generating project plans.
    """
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.agents_initialized = False
        self.workflow_log = []
        self.stats = {
            "user_stories": 0,
            "features": 0,
            "tasks": 0,
            "iterations": 0
        }
        
    def log(self, message: str, level: str = "info"):
        """Add a message to the workflow log."""
        timestamp = datetime.now().strftime("%H:%M:%S")
        self.workflow_log.append({
            "timestamp": timestamp,
            "level": level,
            "message": message
        })
        
    def initialize_agents(self, product_spec: str):
        """Initialize all agents with the product specification."""
        self.log("Initializing AI agents...")
        
        # Action Planning Agent
        self.action_planning_agent = ActionPlanningAgent(
            self.api_key, 
            KNOWLEDGE_ACTION_PLANNING
        )
        
        # Product Manager Team
        knowledge_pm = (
            "Stories are defined by writing sentences with a persona, an action, and a desired outcome. "
            "The sentences always start with: As a "
            "Write several stories for the product spec below, where the personas are the different users of the product. "
            f"\n\nProduct Specification:\n{product_spec}"
        )
        
        self.product_manager_agent = KnowledgeAugmentedPromptAgent(
            self.api_key,
            PERSONA_PRODUCT_MANAGER,
            knowledge_pm
        )
        
        self.product_manager_evaluator = EvaluationAgent(
            openai_api_key=self.api_key,
            persona="You are an evaluation agent that checks the answers of other worker agents",
            evaluation_criteria=EVALUATION_CRITERIA_USER_STORIES,
            worker_agent=self.product_manager_agent,
            max_interactions=5
        )
        
        # Program Manager Team
        knowledge_pgm = (
            "Features of a product are defined by organizing similar user stories into cohesive groups. "
            f"\n\nProduct Specification:\n{product_spec}"
        )
        
        self.program_manager_agent = KnowledgeAugmentedPromptAgent(
            self.api_key,
            PERSONA_PROGRAM_MANAGER,
            knowledge_pgm
        )
        
        self.program_manager_evaluator = EvaluationAgent(
            openai_api_key=self.api_key,
            persona="You are an evaluation agent that checks the answers of other worker agents",
            evaluation_criteria=EVALUATION_CRITERIA_FEATURES,
            worker_agent=self.program_manager_agent,
            max_interactions=5
        )
        
        # Development Engineer Team
        knowledge_dev = (
            "Development tasks are defined by identifying what needs to be built to implement each user story. "
            f"\n\nProduct Specification:\n{product_spec}"
        )
        
        self.dev_engineer_agent = KnowledgeAugmentedPromptAgent(
            self.api_key,
            PERSONA_DEV_ENGINEER,
            knowledge_dev
        )
        
        self.dev_engineer_evaluator = EvaluationAgent(
            openai_api_key=self.api_key,
            persona="You are an evaluation agent that checks the answers of other worker agents",
            evaluation_criteria=EVALUATION_CRITERIA_TASKS,
            worker_agent=self.dev_engineer_agent,
            max_interactions=5
        )
        
        # Routing Agent
        routes = [
            {
                "name": "Product Manager",
                "description": "Responsible for defining product personas and user stories only.",
                "func": self._product_manager_handler
            },
            {
                "name": "Program Manager", 
                "description": "Responsible for defining product features by grouping related user stories.",
                "func": self._program_manager_handler
            },
            {
                "name": "Development Engineer",
                "description": "Responsible for defining development tasks and engineering work.",
                "func": self._dev_engineer_handler
            }
        ]
        
        self.routing_agent = RoutingAgent(self.api_key, routes)
        
        self.agents_initialized = True
        self.log("All agents initialized successfully", "success")
        
    def _product_manager_handler(self, query: str) -> str:
        """Handle Product Manager routing."""
        self.log("Product Manager generating user stories...")
        response = self.product_manager_agent.respond(query)
        result = self.product_manager_evaluator.evaluate(response)
        self.stats["iterations"] += result.get("iterations", 1)
        return result["final_response"]
    
    def _program_manager_handler(self, query: str) -> str:
        """Handle Program Manager routing."""
        self.log("Program Manager defining features...")
        response = self.program_manager_agent.respond(query)
        result = self.program_manager_evaluator.evaluate(response)
        self.stats["iterations"] += result.get("iterations", 1)
        return result["final_response"]
    
    def _dev_engineer_handler(self, query: str) -> str:
        """Handle Development Engineer routing."""
        self.log("Development Engineer creating tasks...")
        response = self.dev_engineer_agent.respond(query)
        result = self.dev_engineer_evaluator.evaluate(response)
        self.stats["iterations"] += result.get("iterations", 1)
        return result["final_response"]
    
    def run_workflow(self, product_spec: str) -> Generator[Tuple[str, str, str, str, str], None, None]:
        """
        Execute the full workflow and yield progress updates.
        
        Yields tuples of:
        (workflow_status, user_stories, features, tasks, full_plan)
        """
        self.workflow_log = []
        self.stats = {"user_stories": 0, "features": 0, "tasks": 0, "iterations": 0}
        
        # Initialize agents
        yield ("⏳ Initializing agents...", "", "", "", "")
        self.initialize_agents(product_spec)
        
        # Extract workflow steps
        yield ("πŸ” Planning workflow steps...", "", "", "", "")
        self.log("Action Planning Agent analyzing product specification...")
        
        workflow_prompt = (
            "Create a comprehensive project plan including: "
            "1) User stories for all personas, "
            "2) Key product features grouped logically, "
            "3) Development tasks for implementation"
        )
        
        steps = self.action_planning_agent.extract_steps_from_prompt(workflow_prompt)
        self.log(f"Identified {len(steps)} workflow steps", "success")
        
        # Process each step
        user_stories = ""
        features = ""
        tasks = ""
        
        # Generate User Stories
        yield ("πŸ‘€ Generating user stories...", "", "", "", "")
        self.log("Routing to Product Manager team...")
        
        user_stories_prompt = "Define comprehensive user stories for all personas in the product specification"
        user_stories = self._product_manager_handler(user_stories_prompt)
        self.stats["user_stories"] = user_stories.count("As a")
        self.log(f"Generated {self.stats['user_stories']} user stories", "success")
        
        yield ("βœ… User stories complete", user_stories, "", "", "")
        
        # Generate Features
        yield ("πŸ“¦ Defining product features...", user_stories, "", "", "")
        self.log("Routing to Program Manager team...")
        
        features_prompt = f"Based on these user stories, define the key product features:\n\n{user_stories}"
        features = self._program_manager_handler(features_prompt)
        self.stats["features"] = max(
            features.lower().count("feature name"),
            features.count("##"),
            features.count("**") // 2,
            len([line for line in features.split('\n') if
                 line.strip().startswith(('1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.'))])
        )
        self.log(f"Defined {self.stats['features']} product features", "success")
        
        yield ("βœ… Features complete", user_stories, features, "", "")
        
        # Generate Tasks
        yield ("πŸ”§ Creating engineering tasks...", user_stories, features, "", "")
        self.log("Routing to Development Engineer team...")
        
        tasks_prompt = f"Create detailed engineering tasks to implement these features:\n\n{features}"
        tasks = self._dev_engineer_handler(tasks_prompt)
        self.stats["tasks"] = tasks.lower().count("task id")
        self.log(f"Created {self.stats['tasks']} engineering tasks", "success")
        
        yield ("βœ… Tasks complete", user_stories, features, tasks, "")
        
        # Generate Full Plan
        yield ("πŸ“‹ Compiling final plan...", user_stories, features, tasks, "")
        
        full_plan = self._compile_full_plan(user_stories, features, tasks)
        self.log("Project plan compilation complete!", "success")
        
        yield ("βœ… Project plan ready!", user_stories, features, tasks, full_plan)

    def _compile_full_plan(self, user_stories: str, features: str, tasks: str) -> str:
        """Compile all outputs into a formatted project plan."""

        # Recalculate stats with better detection
        self.stats["user_stories"] = max(
            user_stories.lower().count("as a"),
            len([line for line in user_stories.split('\n') if line.strip().startswith(('1.', '2.', '3.', '4.', '5.'))])
        )

        self.stats["features"] = max(
            features.lower().count("feature name"),
            features.lower().count("feature:"),
            len([line for line in features.split('\n') if
                 line.strip() and line.strip()[0].isdigit() and '.' in line[:3]]),
            features.count("**") // 2 if "**" in features else 0
        )

        self.stats["tasks"] = max(
            tasks.lower().count("task id"),
            tasks.lower().count("task title"),
            len([line for line in tasks.split('\n') if "task id" in line.lower()])
        )

        # Build workflow log table rows first
        log_rows = []
        for log_entry in self.workflow_log:
            message = log_entry['message'].replace('|', '-')
            log_rows.append(f"| {log_entry['timestamp']} | {log_entry['level']} | {message} |")

        workflow_log_table = "\n".join(log_rows)

        # Build the plan document - NO INDENTATION in the string
        plan = f"""# πŸ“‹ Project Plan

    **Generated:** {datetime.now().strftime("%Y-%m-%d %H:%M")}

    ---

    ## πŸ“Š Summary Statistics

    | Metric | Count |
    |--------|-------|
    | User Stories | {self.stats['user_stories']} |
    | Product Features | {self.stats['features']} |
    | Engineering Tasks | {self.stats['tasks']} |
    | Evaluation Iterations | {self.stats['iterations']} |

    ---

    ## πŸ‘€ User Stories

    {user_stories}

    ---

    ## πŸ“¦ Product Features

    {features}

    ---

    ## πŸ”§ Engineering Tasks

    {tasks}

    ---

    ## πŸ“ Workflow Log

    | Time | Level | Message |
    |------|-------|---------|
    {workflow_log_table}

    ---

    ## βœ… Next Steps

    1. Review and prioritize the user stories with stakeholders
    2. Validate feature groupings with the product team
    3. Estimate engineering tasks with the development team
    4. Create sprint plan based on dependencies
    5. Set up project tracking in your preferred tool (Jira, Linear, etc.)

    ---

    *Generated by AI Project Planner | Powered by GPT-3.5*
    """

        return plan

# ============================================================================
# GRADIO INTERFACE
# ============================================================================

def create_interface():
    """Create the Gradio interface."""
    
    workflow = None

    # Add these state variables
    stored_stories = gr.State("")
    stored_features = gr.State("")
    stored_tasks = gr.State("")

    def validate_api_key(api_key: str) -> str:
        """Validate the API key format."""
        if not api_key or len(api_key) < 20:
            return "❌ Please enter a valid API key"

        if api_key.startswith("sk-ant-"):
            return "βœ… Anthropic Claude key detected"
        elif api_key.startswith("voc-"):
            return "βœ… Vocareum key detected (requires Vocareum network)"
        elif api_key.startswith("sk-"):
            return "βœ… OpenAI key detected"
        else:
            return "⚠️ Unknown key format - will try OpenAI"
    
    def load_example(example_name: str) -> str:
        """Load an example product specification."""
        return EXAMPLE_SPECS.get(example_name, "")

    def run_planner(
            api_key: str,
            product_spec: str,
            progress=gr.Progress()
    ) -> Tuple[str, str, str, str, str]:
        """Run the project planner workflow."""

        if not api_key or len(api_key) < 20:
            return (
                "❌ Error: Please enter a valid OpenAI API key",
                "", "", "", ""
            )

        if not product_spec or len(product_spec) < 100:
            return (
                "❌ Error: Please provide a product specification (minimum 100 characters)",
                "", "", "", ""
            )

        try:
            planner = ProjectPlannerWorkflow(api_key)

            results = ("", "", "", "", "")
            progress(0, desc="Starting workflow...")

            step_progress = [0.1, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0]
            step_idx = 0

            for status, stories, features, tasks, plan in planner.run_workflow(product_spec):
                if step_idx < len(step_progress):
                    progress(step_progress[step_idx], desc=status)
                    step_idx += 1
                results = (status, stories, features, tasks, plan)

            return results

        except Exception as e:
            return (
                f"❌ Error: {str(e)}",
                "", "", "", ""
            )


    def export_markdown(plan: str):
        """Export full plan as markdown."""
        if not plan or len(plan) < 50:
            return None

        filename = f"project_plan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
        with open(filename, "w", encoding="utf-8") as f:
            f.write(plan)
        return filename

    def export_json(stories: str, features: str, tasks: str, plan: str):
        """Export results as JSON."""
        if not plan or len(plan) < 50:
            return None

        data = {
            "generated_at": datetime.now().isoformat(),
            "user_stories": stories,
            "features": features,
            "tasks": tasks,
            "full_plan": plan
        }

        filename = f"project_plan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        return filename

    # Build the interface
    with gr.Blocks(title="AI Project Planner") as app:
        
        # Header
        gr.HTML("""
        <div class="header-container">
            <div class="header-title">πŸš€ AI Project Planner</div>
            <div class="header-subtitle">
                Transform product specifications into comprehensive project plans using orchestrated AI agents
            </div>
        </div>
        """)
        
        with gr.Row():
            # Left Column - Input
            with gr.Column(scale=1):
                gr.Markdown("### βš™οΈ Configuration")
                
                api_key_input = gr.Textbox(
                    label="OpenAI API Key",
                    placeholder="sk-...",
                    type="password",
                    info="Your API key is not stored and only used for this session"
                )
                
                api_status = gr.Markdown("Enter your API key to begin")

                test_btn = gr.Button("πŸ”Œ Test Connection", variant="secondary", size="sm")
                
                api_key_input.change(
                    fn=validate_api_key,
                    inputs=[api_key_input],
                    outputs=[api_status]
                )
                
                gr.Markdown("### πŸ“„ Product Specification")
                
                with gr.Accordion("πŸ“š Load Example", open=False):
                    example_dropdown = gr.Dropdown(
                        choices=list(EXAMPLE_SPECS.keys()),
                        label="Select Example",
                        value="Email Router"
                    )
                    load_example_btn = gr.Button("Load Example", variant="secondary")
                
                spec_input = gr.Textbox(
                    label="Product Specification",
                    placeholder="Paste your product specification here...",
                    lines=15,
                    max_lines=30
                )
                
                load_example_btn.click(
                    fn=load_example,
                    inputs=[example_dropdown],
                    outputs=[spec_input]
                )
                
                generate_btn = gr.Button(
                    "🎯 Generate Project Plan",
                    variant="primary",
                    elem_classes=["primary-btn"]
                )
            
            # Right Column - Output
            with gr.Column(scale=2):
                gr.Markdown("### πŸ“Š Results")
                
                workflow_status = gr.Markdown("Ready to generate project plan")

                with gr.Tabs():
                    with gr.Tab("πŸ‘€ User Stories"):
                        user_stories_output = gr.Textbox(
                            label="User Stories",
                            lines=15
                        )

                    with gr.Tab("πŸ“¦ Features"):
                        features_output = gr.Textbox(
                            label="Product Features",
                            lines=15
                        )

                    with gr.Tab("πŸ”§ Tasks"):
                        tasks_output = gr.Textbox(
                            label="Engineering Tasks",
                            lines=15
                        )

                    with gr.Tab("πŸ“‹ Full Plan"):
                        full_plan_output = gr.Textbox(
                            label="Complete Project Plan",
                            lines=20
                        )

                gr.Markdown("### πŸ“₯ Export")

                with gr.Row():
                    export_md_btn = gr.Button("πŸ“„ Download Markdown", variant="secondary")
                    export_json_btn = gr.Button("πŸ“Š Download JSON", variant="secondary")

                export_file = gr.File(label="Download", interactive=False)
        
        # Footer
        gr.HTML("""
        <div style="text-align: center; margin-top: 2rem; padding: 1rem; border-top: 1px solid #2d2d44;">
            <p style="color: #a0a0b0; font-size: 0.9rem;">
                Built with ❀️ using Gradio β€’ Powered by OpenAI GPT-3.5 β€’ 
                <a href="https://github.com" style="color: #667eea;">View on GitHub</a>
            </p>
        </div>
        """)
        
        # Event handlers
        # Event handlers
        # Event handlers
        generate_btn.click(
            fn=run_planner,
            inputs=[api_key_input, spec_input],
            outputs=[
                workflow_status,
                user_stories_output,
                features_output,
                tasks_output,
                full_plan_output
            ],
            show_progress=True
        )

        export_md_btn.click(
            fn=export_markdown,
            inputs=[full_plan_output],
            outputs=[export_file]
        )

        export_json_btn.click(
            fn=export_json,
            inputs=[user_stories_output, features_output, tasks_output, full_plan_output],
            outputs=[export_file]
        )
        # Add this event handler with the others at the bottom
        test_btn.click(
            fn=test_api_connection,
            inputs=[api_key_input],
            outputs=[api_status]
        )
    
    return app


# ============================================================================
# MAIN ENTRY POINT
# ============================================================================

if __name__ == "__main__":
    app = create_interface()
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )