File size: 54,344 Bytes
46b1c24
 
 
 
 
 
 
 
 
 
 
 
698de3d
46b1c24
 
698de3d
46b1c24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698de3d
 
 
 
 
 
 
 
46b1c24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698de3d
46b1c24
 
 
 
 
 
 
698de3d
46b1c24
 
698de3d
 
46b1c24
 
698de3d
46b1c24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698de3d
46b1c24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698de3d
 
 
 
46b1c24
 
 
 
698de3d
 
 
 
 
 
46b1c24
 
 
 
 
 
 
 
 
 
 
 
 
 
698de3d
46b1c24
 
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
 
698de3d
46b1c24
 
 
698de3d
46b1c24
 
698de3d
 
46b1c24
 
698de3d
 
 
 
 
 
 
46b1c24
 
 
698de3d
46b1c24
698de3d
 
 
 
46b1c24
 
698de3d
 
 
46b1c24
 
 
 
 
 
698de3d
46b1c24
 
f22c171
46b1c24
 
698de3d
 
 
 
 
 
 
 
46b1c24
698de3d
46b1c24
 
 
 
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
 
 
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
 
 
 
 
 
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
 
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
46b1c24
698de3d
 
 
 
 
46b1c24
 
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
 
698de3d
 
 
 
 
 
46b1c24
698de3d
 
 
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b1c24
 
698de3d
46b1c24
 
 
 
 
 
 
 
 
 
 
 
698de3d
 
46b1c24
698de3d
 
 
 
 
 
 
 
 
46b1c24
698de3d
46b1c24
 
 
 
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
# pyright: reportMissingImports=false, reportMissingTypeStubs=false, reportExplicitAny=false, reportAny=false, reportUnknownVariableType=false, reportUnknownArgumentType=false, reportUnknownMemberType=false, reportUnusedCallResult=false
import json
import os
import time
from typing import Any, Optional

import pandas as pd
import requests
import streamlit as st


APP_TITLE = "AI Prototype Planner"
CAPABILITY_DESCRIPTION = "End to End Applied AI Prototyping — Rapid prototyping of full AI experiences. Connect data sources with model layers and interfaces for validation and experimentation."
RATE_LIMIT_REQUESTS = 8
RATE_LIMIT_WINDOW_SECONDS = 60
GEMINI_MODEL = "gemini-2.5-flash"

PRIMARY_CAPABILITIES = [
    "Text Generation",
    "Image/Video",
    "Speech/Audio",
    "Structured Data/Analytics",
    "Multi-modal",
    "Agents/Automation",
]

TARGET_USERS = [
    "Internal team",
    "B2B customers",
    "B2C consumers",
    "Developer API",
]

ARCHITECTURE_STAGES = [
    "Data Sources",
    "Processing",
    "Model Layer",
    "API Layer",
    "Frontend",
]


def model_catalog() -> dict[str, list[dict[str, str]]]:
    return {
        "Text Generation": [
            {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "Strong reasoning + tools", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "High quality + mature ecosystem", "cons": "Premium pricing"},
            {"model": "Claude 3.5 Sonnet", "provider": "Anthropic", "capability_match": "Long-context instruction following", "cost_1k_requests": "$22.00", "latency": "Medium", "pros": "Reliable complex writing", "cons": "Tier-dependent limits"},
            {"model": "Gemini 1.5 Pro", "provider": "Google", "capability_match": "Large context + multimodal", "cost_1k_requests": "$18.00", "latency": "Medium", "pros": "Great context/cost balance", "cons": "May require strict prompting"},
        ],
        "Image/Video": [
            {"model": "SDXL", "provider": "Stability AI", "capability_match": "Image generation and editing", "cost_1k_requests": "$8.00", "latency": "Medium", "pros": "Flexible and open workflow", "cons": "Prompt tuning overhead"},
            {"model": "GPT-4o mini vision", "provider": "OpenAI", "capability_match": "Visual understanding", "cost_1k_requests": "$10.00", "latency": "Low", "pros": "Fast image analysis", "cons": "Not specialized for generation"},
            {"model": "Gemini 1.5 Flash", "provider": "Google", "capability_match": "Video-aware extraction", "cost_1k_requests": "$9.00", "latency": "Low", "pros": "Fast and cost-efficient", "cons": "Lower quality than premium tiers"},
        ],
        "Speech/Audio": [
            {"model": "Whisper-large-v3", "provider": "OpenAI", "capability_match": "Speech-to-text baseline", "cost_1k_requests": "$6.00", "latency": "Low", "pros": "High transcription accuracy", "cons": "Needs downstream NLU layer"},
            {"model": "Gemini 1.5 Pro", "provider": "Google", "capability_match": "Audio + text reasoning", "cost_1k_requests": "$18.00", "latency": "Medium", "pros": "Unified multimodal pipeline", "cons": "High cost for always-on streams"},
            {"model": "Llama 3.1 70B Instruct", "provider": "Meta / Hosted", "capability_match": "Post-ASR intent handling", "cost_1k_requests": "$7.00", "latency": "Medium", "pros": "Self-host flexibility", "cons": "MLOps complexity"},
        ],
        "Structured Data/Analytics": [
            {"model": "Claude 3 Haiku", "provider": "Anthropic", "capability_match": "Fast BI commentary", "cost_1k_requests": "$5.00", "latency": "Low", "pros": "Low-latency narrative insights", "cons": "Less deep reasoning"},
            {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "Executive reporting", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "Best-in-class summaries", "cons": "Can be expensive at scale"},
            {"model": "Llama 3.1 8B Instruct", "provider": "Meta / Hosted", "capability_match": "Private analytics copilot", "cost_1k_requests": "$3.00", "latency": "Low", "pros": "Low marginal cost", "cons": "Requires quality tuning"},
        ],
        "Multi-modal": [
            {"model": "Gemini 1.5 Pro", "provider": "Google", "capability_match": "Cross-modal context fusion", "cost_1k_requests": "$18.00", "latency": "Medium", "pros": "Native multimodal input", "cons": "Prompt format discipline required"},
            {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "High quality multimodal responses", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "Great tool ecosystem", "cons": "Higher cost"},
            {"model": "Claude 3.5 Sonnet", "provider": "Anthropic", "capability_match": "Document + visual reasoning", "cost_1k_requests": "$22.00", "latency": "Medium", "pros": "Strong reliability", "cons": "Fewer native media workflows"},
        ],
        "Agents/Automation": [
            {"model": "GPT-4o", "provider": "OpenAI", "capability_match": "Function/tool orchestration", "cost_1k_requests": "$28.00", "latency": "Medium", "pros": "Excellent function calling", "cons": "Costs climb with chain depth"},
            {"model": "Claude 3.5 Sonnet", "provider": "Anthropic", "capability_match": "Long-horizon planning", "cost_1k_requests": "$22.00", "latency": "Medium", "pros": "Strong consistency", "cons": "Schema-control needed"},
            {"model": "Llama 3.1 70B Instruct", "provider": "Meta / Hosted", "capability_match": "On-prem orchestration", "cost_1k_requests": "$7.00", "latency": "Medium", "pros": "Deployment control", "cons": "Ops burden"},
        ],
    }


def template_library() -> dict[str, dict[str, Any]]:
    return {
        "Text Generation": {"sources": ["Knowledge Base", "Support Tickets", "Product Docs"], "ingestion": "Batch sync + webhook deltas", "preprocessing": "Chunking, dedupe, metadata, embeddings", "storage": "Object store + vector DB", "serving": "RAG API + moderation", "frontend": "Chat assistant with handoff", "team": "1 PM, 1 AI, 1 Backend, 1 Frontend"},
        "Image/Video": {"sources": ["Uploads", "Media feeds", "Moderation queue"], "ingestion": "Event-driven media workers", "preprocessing": "Frame extraction, resizing, safety features", "storage": "Object store + metadata index", "serving": "Async inference gateway", "frontend": "Ops moderation dashboard", "team": "1 PM, 1 CV, 1 Backend, 1 Trust/Safety"},
        "Speech/Audio": {"sources": ["Call recordings", "Mobile streams", "CRM logs"], "ingestion": "Realtime collector + batch import", "preprocessing": "Noise reduction, diarization, transcript cleanup", "storage": "Audio lake + transcript warehouse", "serving": "Realtime intent API", "frontend": "Voice-enabled workflow app", "team": "1 PM, 1 Speech, 1 Mobile, 1 Backend"},
        "Structured Data/Analytics": {"sources": ["Warehouse", "SaaS exports", "Event tracking"], "ingestion": "Daily ETL + KPI stream", "preprocessing": "Validation, feature derivation, null handling", "storage": "Warehouse mart + feature cache", "serving": "Analytics API + insight jobs", "frontend": "KPI dashboard", "team": "1 PM, 1 Data Engineer, 1 Backend, 1 BI/Frontend"},
        "Multi-modal": {"sources": ["Documents", "Images", "Audio", "App events"], "ingestion": "Unified ingest bus + parsers", "preprocessing": "OCR, ASR, segmentation, embeddings", "storage": "Object + vector + metadata DB", "serving": "Multimodal orchestrator", "frontend": "Unified analyst workspace", "team": "1 PM, 2 AI, 1 Platform, 1 Frontend"},
        "Agents/Automation": {"sources": ["SOP docs", "System APIs", "Task events"], "ingestion": "Connector framework", "preprocessing": "Tool schema normalization + policy tags", "storage": "Knowledge store + run-history DB", "serving": "Agent runtime + guardrails", "frontend": "Automation cockpit", "team": "1 PM, 1 Agent Eng, 1 Backend, 1 Security"},
    }


@st.cache_data
def load_sample_concepts() -> list[dict[str, Any]]:
    path = "data/sample_concepts.jsonl"
    records: list[dict[str, Any]] = []
    try:
        with open(path, "r", encoding="utf-8") as handle:
            for line in handle:
                line = line.strip()
                if not line:
                    continue
                try:
                    obj = json.loads(line)
                except json.JSONDecodeError:
                    continue
                if isinstance(obj, dict):
                    records.append(obj)
    except OSError:
        return []
    return records


def complexity_weight(capability: str) -> float:
    return {
        "Text Generation": 1.0,
        "Image/Video": 1.25,
        "Speech/Audio": 1.2,
        "Structured Data/Analytics": 0.9,
        "Multi-modal": 1.45,
        "Agents/Automation": 1.35,
    }.get(capability, 1.0)


def risk_note(target_users: str) -> str:
    if target_users == "Internal team":
        return "Access controls, SSO, and audit logs."
    if target_users == "B2B customers":
        return "Tenant isolation, SLOs, and support runbook."
    if target_users == "B2C consumers":
        return "Safety, abuse detection, and high-traffic reliability."
    return "Versioned APIs, quotas, and auth hardening."


def estimate_monthly_requests(target_users: str, budget: int) -> int:
    baseline = {
        "Internal team": 90000,
        "B2B customers": 220000,
        "B2C consumers": 850000,
        "Developer API": 500000,
    }.get(target_users, 100000)
    scale = max(0.35, min(2.2, budget / 100000))
    return int(baseline * scale)


def architecture_template(capability: str, target_users: str) -> list[dict[str, str]]:
    profile = template_library().get(capability, template_library()["Text Generation"])
    api_layer = {
        "Internal team": "Internal API gateway + SSO",
        "B2B customers": "Tenant-aware API gateway + RBAC",
        "B2C consumers": "Public API + anti-abuse checks",
        "Developer API": "Versioned API gateway + key management",
    }.get(target_users, "API gateway")
    return [
        {"stage": "Data Sources", "tech": ", ".join(profile["sources"]), "details": "Primary data systems feeding context and events."},
        {"stage": "Processing", "tech": profile["preprocessing"], "details": "Normalize, enrich, and filter input signals."},
        {"stage": "Model Layer", "tech": "Hybrid routing across fast + premium models", "details": "Use quality/cost-aware model switching."},
        {"stage": "API Layer", "tech": api_layer, "details": "Authentication, observability, policy checks, and versioning."},
        {"stage": "Frontend", "tech": profile["frontend"], "details": "User-facing interface with feedback collection."},
    ]


def weekly_plan(capability: str, timeline_weeks: int, target_users: str) -> list[dict[str, str]]:
    phases = [
        "Discovery + scope lock",
        "Data integration",
        "Model baseline + evaluations",
        "API and orchestration",
        "UX integration + user tests",
        "Hardening + observability",
        "Pilot launch",
    ]
    team = template_library().get(capability, template_library()["Text Generation"]).get("team", "Cross-functional AI team")
    stride = max(1, int(round(max(2, timeline_weeks) / 6)))
    rows: list[dict[str, str]] = []
    for wk in range(1, timeline_weeks + 1):
        phase = phases[min((wk - 1) // stride, len(phases) - 1)]
        deliverable = f"Week {wk} delivery for {phase.lower()}"
        if wk == 1:
            deliverable = "Problem framing, KPI targets, and architecture brief"
        if wk == timeline_weeks:
            deliverable = "Pilot release, handover docs, and support plan"
        rows.append(
            {
                "Week": str(wk),
                "Milestone": phase,
                "Deliverables": deliverable,
                "Team Allocation": team,
                "Risk Control": risk_note(target_users),
            }
        )
    return rows


def estimate_costs(capability: str, target_users: str, budget: int, timeline_weeks: int) -> dict[str, Any]:
    weight = complexity_weight(capability)
    req = estimate_monthly_requests(target_users, budget)
    compute = int((budget * 0.18 * weight) + (timeline_weeks * 1100))
    storage = int((budget * 0.05) + (timeline_weeks * 320))
    model_api = int((req / 1000) * (8 + (weight * 4)))
    development = int((budget * 0.52) + (timeline_weeks * 2100 * weight))
    security = int((budget * 0.08) + (timeline_weeks * 420))
    subtotal = compute + storage + model_api + development + security
    contingency = int(subtotal * 0.15)
    total = subtotal + contingency
    fit = "Within target" if total <= budget * 1.1 else "Above target"
    return {
        "compute": compute,
        "storage": storage,
        "model_api": model_api,
        "development": development,
        "security": security,
        "contingency": contingency,
        "subtotal": subtotal,
        "total": total,
        "fit": fit,
    }


def parse_json_object(text: str) -> Optional[dict[str, Any]]:
    if not text:
        return None
    start = text.find("{")
    end = text.rfind("}")
    if start == -1 or end == -1 or end <= start:
        return None
    try:
        data = json.loads(text[start : end + 1])
    except json.JSONDecodeError:
        return None
    if isinstance(data, dict):
        return data
    return None


def check_rate_limit() -> tuple[bool, int]:
    now = time.time()
    current = [ts for ts in st.session_state.get("request_timestamps", []) if (now - ts) <= RATE_LIMIT_WINDOW_SECONDS]
    st.session_state["request_timestamps"] = current
    if len(current) >= RATE_LIMIT_REQUESTS:
        retry = int(RATE_LIMIT_WINDOW_SECONDS - (now - current[0]))
        return False, max(retry, 1)
    current.append(now)
    st.session_state["request_timestamps"] = current
    return True, 0


def init_state() -> None:
    defaults: dict[str, Any] = {
        "concept_description": "",
        "primary_capability": PRIMARY_CAPABILITIES[0],
        "target_users": TARGET_USERS[1],
        "budget": 75000,
        "timeline_weeks": 12,
        "unlocked_step": 1,
        "request_timestamps": [],
        "architecture_rows": [],
        "data_pipeline": {},
        "model_options": [],
        "selected_model_name": "",
        "build_plan_rows": [],
        "cost_inputs": {},
        "cost_summary": {},
        "ai_strategy_note": "",
        "ai_architecture_text": "",
        "final_plan": None,
        "final_plan_source": "",
        "sample_cursor": 0,
    }
    for key, value in defaults.items():
        if key not in st.session_state:
            st.session_state[key] = value


def clear_dynamic_widget_keys() -> None:
    keys = list(st.session_state.keys())
    for key in keys:
        if isinstance(key, str) and (key.startswith("arch_tech_") or key.startswith("arch_details_")):
            del st.session_state[key]
        if isinstance(key, str) and key.startswith("pipeline_"):
            del st.session_state[key]
    for transient in ["build_plan_editor", "move_week_pick"]:
        if transient in st.session_state:
            del st.session_state[transient]


def apply_sample(samples: list[dict[str, Any]]) -> None:
    if not samples:
        return
    index = int(st.session_state.get("sample_cursor", 0)) % len(samples)
    sample = samples[index]
    st.session_state["sample_cursor"] = (index + 1) % len(samples)
    st.session_state["concept_description"] = str(sample.get("description", ""))
    st.session_state["primary_capability"] = str(sample.get("primary_capability", PRIMARY_CAPABILITIES[0]))
    st.session_state["target_users"] = str(sample.get("target_users", TARGET_USERS[0]))
    st.session_state["budget"] = int(sample.get("budget", 75000))
    st.session_state["timeline_weeks"] = int(sample.get("timeline_weeks", 12))
    st.session_state["unlocked_step"] = 1
    st.session_state["final_plan"] = None
    st.session_state["final_plan_source"] = ""
    clear_dynamic_widget_keys()
    seed_step_two_state(reset_models=True)
    seed_step_three_state()


def seed_step_two_state(reset_models: bool) -> None:
    capability = str(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0]))
    target = str(st.session_state.get("target_users", TARGET_USERS[0]))
    arch = architecture_template(capability, target)
    pipeline_profile = template_library().get(capability, template_library()["Text Generation"])
    pipeline = {
        "sources": list(pipeline_profile.get("sources", [])),
        "ingestion": str(pipeline_profile.get("ingestion", "")),
        "preprocessing": str(pipeline_profile.get("preprocessing", "")),
        "storage": str(pipeline_profile.get("storage", "")),
        "serving": str(pipeline_profile.get("serving", "")),
    }
    st.session_state["architecture_rows"] = arch
    st.session_state["data_pipeline"] = pipeline
    if reset_models:
        options = [dict(row) for row in model_catalog().get(capability, model_catalog()["Text Generation"])]
        st.session_state["model_options"] = options
        st.session_state["selected_model_name"] = options[0]["model"] if options else ""
    clear_dynamic_widget_keys()


def seed_step_three_state() -> None:
    capability = str(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0]))
    target = str(st.session_state.get("target_users", TARGET_USERS[0]))
    budget = int(st.session_state.get("budget", 75000))
    timeline = int(st.session_state.get("timeline_weeks", 12))
    st.session_state["build_plan_rows"] = weekly_plan(capability, timeline, target)
    costs = estimate_costs(capability, target, budget, timeline)
    st.session_state["cost_inputs"] = {
        "compute": costs["compute"],
        "storage": costs["storage"],
        "model_api": costs["model_api"],
        "development": costs["development"],
        "security": costs["security"],
    }
    recalculate_cost_summary()


def recalculate_cost_summary() -> None:
    cost_inputs = st.session_state.get("cost_inputs", {})
    budget = int(st.session_state.get("budget", 0))
    compute = int(cost_inputs.get("compute", 0))
    storage = int(cost_inputs.get("storage", 0))
    model_api = int(cost_inputs.get("model_api", 0))
    development = int(cost_inputs.get("development", 0))
    security = int(cost_inputs.get("security", 0))
    subtotal = compute + storage + model_api + development + security
    contingency = int(subtotal * 0.15)
    total = subtotal + contingency
    fit = "Within target" if total <= budget * 1.1 else "Above target"
    st.session_state["cost_summary"] = {
        "line_items": [
            {"category": "Compute", "estimate_usd": compute, "notes": "Inference + orchestration resources"},
            {"category": "Storage", "estimate_usd": storage, "notes": "Object, metadata, and vector storage"},
            {"category": "Model API", "estimate_usd": model_api, "notes": "Primary model inference and retries"},
            {"category": "Development", "estimate_usd": development, "notes": "Product + engineering implementation effort"},
            {"category": "Security", "estimate_usd": security, "notes": "Guardrails, logging, monitoring, compliance"},
            {"category": "Contingency (15%)", "estimate_usd": contingency, "notes": "Scope and traffic variance"},
        ],
        "subtotal": subtotal,
        "contingency": contingency,
        "total": total,
        "budget": budget,
        "fit": fit,
    }


def ensure_architecture_widget_defaults() -> None:
    rows = st.session_state.get("architecture_rows", [])
    for idx, row in enumerate(rows):
        tech_key = f"arch_tech_{idx}"
        detail_key = f"arch_details_{idx}"
        if tech_key not in st.session_state:
            st.session_state[tech_key] = str(row.get("tech", ""))
        if detail_key not in st.session_state:
            st.session_state[detail_key] = str(row.get("details", ""))


def sync_architecture_from_widgets() -> None:
    rows = st.session_state.get("architecture_rows", [])
    updated: list[dict[str, str]] = []
    for idx, row in enumerate(rows):
        updated.append(
            {
                "stage": str(row.get("stage", ARCHITECTURE_STAGES[idx] if idx < len(ARCHITECTURE_STAGES) else "Stage")),
                "tech": str(st.session_state.get(f"arch_tech_{idx}", row.get("tech", ""))),
                "details": str(st.session_state.get(f"arch_details_{idx}", row.get("details", ""))),
            }
        )
    st.session_state["architecture_rows"] = updated


def ensure_pipeline_widget_defaults() -> None:
    pipeline = st.session_state.get("data_pipeline", {})
    sources = pipeline.get("sources", [])
    if not isinstance(sources, list):
        sources = []
    if "pipeline_sources" not in st.session_state:
        st.session_state["pipeline_sources"] = ", ".join([str(item) for item in sources])
    for key in ["ingestion", "preprocessing", "storage", "serving"]:
        widget_key = f"pipeline_{key}"
        if widget_key not in st.session_state:
            st.session_state[widget_key] = str(pipeline.get(key, ""))


def sync_pipeline_from_widgets() -> None:
    source_text = str(st.session_state.get("pipeline_sources", ""))
    sources = [part.strip() for part in source_text.split(",") if part.strip()]
    st.session_state["data_pipeline"] = {
        "sources": sources,
        "ingestion": str(st.session_state.get("pipeline_ingestion", "")),
        "preprocessing": str(st.session_state.get("pipeline_preprocessing", "")),
        "storage": str(st.session_state.get("pipeline_storage", "")),
        "serving": str(st.session_state.get("pipeline_serving", "")),
    }


def build_architecture_diagram_text(architecture_rows: list[dict[str, str]]) -> str:
    segments: list[str] = []
    for row in architecture_rows:
        stage = str(row.get("stage", "Stage"))
        tech = str(row.get("tech", ""))
        segments.append(f"[{stage}] {tech}")
    return "\n  -> ".join(segments)


def heuristic_strategy_note(inputs: dict[str, Any], selected_model: str) -> str:
    return (
        f"Design around a modular API-first stack for {inputs['target_users']} so the prototype can validate outcomes quickly. "
        f"Use {selected_model} as the primary model path while keeping routing abstraction in place for cost and quality tuning."
    )


def gemini_strategy(inputs: dict[str, Any], architecture_text: str) -> Optional[dict[str, Any]]:
    api_key = os.getenv("GEMINI_API_KEY")
    if not api_key:
        return None
    endpoint = f"https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent"
    schema = {
        "strategy_note": "string",
        "architecture_diagram": "string",
        "execution_focus": ["string"],
    }
    prompt = f"""
You are a principal AI product architect.
Return only valid JSON.

Draft a concise but actionable strategy output for this prototype planning workflow.

Concept:
{inputs['concept_description']}

Primary capability: {inputs['primary_capability']}
Target users: {inputs['target_users']}
Budget: {inputs['budget']}
Timeline weeks: {inputs['timeline_weeks']}
Selected model: {inputs['selected_model']}

Current architecture draft:
{architecture_text}

Rules:
- strategy_note should be 2-4 sentences, practical and specific.
- architecture_diagram should preserve 5-stage order: Data Sources -> Processing -> Model Layer -> API Layer -> Frontend.
- execution_focus should include exactly 3 bullet-ready phrases.

Schema:
{json.dumps(schema)}
""".strip()
    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"temperature": 0.2, "maxOutputTokens": 1500, "responseMimeType": "application/json"},
    }
    try:
        response = requests.post(f"{endpoint}?key={api_key}", json=payload, timeout=45)
        if response.status_code != 200:
            return None
        data = response.json()
        candidates = data.get("candidates", [])
        if not candidates:
            return None
        parts = candidates[0].get("content", {}).get("parts", [])
        text = "\n".join([str(part.get("text", "")) for part in parts if isinstance(part, dict)]).strip()
        parsed = parse_json_object(text)
        if not parsed:
            return None
        return parsed
    except Exception:
        return None


def assemble_final_plan(strategy_source: str) -> dict[str, Any]:
    concept = str(st.session_state.get("concept_description", "")).strip()
    capability = str(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0]))
    target = str(st.session_state.get("target_users", TARGET_USERS[0]))
    budget = int(st.session_state.get("budget", 0))
    timeline = int(st.session_state.get("timeline_weeks", 0))
    selected_model_name = str(st.session_state.get("selected_model_name", ""))
    model_options = st.session_state.get("model_options", [])
    architecture_rows = st.session_state.get("architecture_rows", [])
    pipeline = st.session_state.get("data_pipeline", {})
    build_rows = st.session_state.get("build_plan_rows", [])
    cost_summary = st.session_state.get("cost_summary", {})
    selected_model = {}
    for model in model_options:
        if str(model.get("model", "")) == selected_model_name:
            selected_model = model
            break
    if not selected_model and model_options:
        selected_model = model_options[0]
    strategy_note = str(st.session_state.get("ai_strategy_note", "")).strip()
    architecture_diagram = str(st.session_state.get("ai_architecture_text", "")).strip()
    if not strategy_note:
        strategy_note = heuristic_strategy_note(
            {
                "concept_description": concept,
                "primary_capability": capability,
                "target_users": target,
                "budget": budget,
                "timeline_weeks": timeline,
            },
            str(selected_model.get("model", "Primary model")),
        )
    if not architecture_diagram:
        architecture_diagram = build_architecture_diagram_text(architecture_rows)
    return {
        "capability_description": CAPABILITY_DESCRIPTION,
        "concept": concept,
        "primary_capability": capability,
        "target_users": target,
        "budget": budget,
        "timeline_weeks": timeline,
        "strategy_note": strategy_note,
        "architecture_diagram": architecture_diagram,
        "architecture": architecture_rows,
        "selected_model": selected_model,
        "model_options": model_options,
        "data_pipeline": pipeline,
        "build_plan": build_rows,
        "cost_estimate": cost_summary,
        "source": strategy_source,
    }


def plan_tab_labels(unlocked_step: int) -> list[str]:
    labels = [
        "1. Define Your Concept",
        "2. Architecture & Model Selection",
        "3. Build Plan & Timeline",
        "4. Prototype Plan",
    ]
    output: list[str] = []
    for idx, label in enumerate(labels, start=1):
        if idx > unlocked_step:
            output.append(f"{label}  LOCKED")
        else:
            output.append(label)
    return output


def tab_lock_css(unlocked_step: int) -> str:
    if unlocked_step <= 1:
        lock_selector = "button:nth-child(n+2)"
    elif unlocked_step == 2:
        lock_selector = "button:nth-child(n+3)"
    elif unlocked_step == 3:
        lock_selector = "button:nth-child(4)"
    else:
        lock_selector = ""
    if not lock_selector:
        return ""
    return f"""
    .stTabs [data-baseweb=\"tab-list\"] {lock_selector} {{
        opacity: 0.42;
        pointer-events: none;
        filter: grayscale(1);
        border-color: rgba(117, 126, 145, 0.35) !important;
    }}
    """


def apply_theme(unlocked_step: int) -> None:
    st.markdown(
        f"""
        <style>
        @import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500;600;700&family=DM+Sans:wght@400;500;700&display=swap');
        :root {{
            --bg-0: #070b12;
            --bg-1: #0d131f;
            --bg-2: #121b2b;
            --line-soft: rgba(98, 123, 160, 0.42);
            --line-hard: rgba(112, 171, 233, 0.55);
            --text-main: #e5edf8;
            --text-soft: #9db1cb;
            --accent: #7bc8ff;
            --accent-warm: #f4bc69;
            --ok: #8ada91;
            --warn: #ff8f8f;
        }}
        .stApp {{
            background:
                radial-gradient(circle at 85% -5%, rgba(42, 77, 119, 0.32), transparent 34%),
                radial-gradient(circle at -10% 15%, rgba(151, 95, 31, 0.16), transparent 28%),
                linear-gradient(165deg, var(--bg-0), var(--bg-1) 58%, var(--bg-2));
            color: var(--text-main);
            font-family: "DM Sans", sans-serif;
        }}
        h1, h2, h3 {{
            font-family: "Cormorant Garamond", serif !important;
            letter-spacing: 0.02em;
        }}
        .hero-shell {{
            border: 1px solid var(--line-soft);
            background: linear-gradient(160deg, rgba(16, 27, 45, 0.94), rgba(8, 14, 24, 0.94));
            border-radius: 16px;
            padding: 1.0rem 1.2rem 1.2rem 1.2rem;
            box-shadow: 0 18px 42px rgba(3, 8, 20, 0.52);
            margin-bottom: 0.8rem;
            animation: riseIn 420ms ease-out;
        }}
        .hero-kicker {{
            text-transform: uppercase;
            letter-spacing: 0.15em;
            color: var(--accent);
            font-size: 0.72rem;
            opacity: 0.9;
        }}
        .hero-title {{
            color: #f3f8ff;
            font-size: 2.25rem;
            line-height: 1.0;
            margin: 0.25rem 0 0.55rem 0;
        }}
        .hero-copy {{
            color: var(--text-soft);
            font-size: 0.98rem;
            max-width: 74ch;
            line-height: 1.45;
        }}
        .chipline {{
            display: flex;
            flex-wrap: wrap;
            gap: 0.4rem;
            margin-top: 0.6rem;
        }}
        .chip {{
            border: 1px solid rgba(116, 176, 232, 0.42);
            border-radius: 999px;
            padding: 0.16rem 0.62rem;
            font-size: 0.73rem;
            color: #c3daf2;
            background: rgba(19, 31, 51, 0.78);
        }}
        .step-note {{
            border: 1px solid rgba(84, 102, 132, 0.45);
            border-left: 3px solid var(--accent);
            border-radius: 12px;
            background: rgba(15, 23, 36, 0.72);
            padding: 0.78rem 0.95rem;
            margin-bottom: 0.95rem;
            color: #b3c6de;
            line-height: 1.35;
        }}
        .locked-hint {{
            border: 1px dashed rgba(118, 132, 154, 0.45);
            background: rgba(13, 20, 31, 0.65);
            border-radius: 12px;
            padding: 0.95rem;
            color: #9db0c8;
        }}
        .arch-flow {{
            display: flex;
            gap: 0.55rem;
            overflow-x: auto;
            padding-bottom: 0.6rem;
        }}
        .arch-node {{
            min-width: 180px;
            max-width: 220px;
            border: 1px solid var(--line-soft);
            border-radius: 13px;
            background: linear-gradient(150deg, rgba(16, 26, 43, 0.94), rgba(9, 15, 24, 0.88));
            padding: 0.7rem;
        }}
        .arch-stage {{
            text-transform: uppercase;
            letter-spacing: 0.09em;
            color: var(--accent);
            font-size: 0.66rem;
            margin-bottom: 0.28rem;
        }}
        .arch-tech {{
            color: #dde8f6;
            font-size: 0.84rem;
            line-height: 1.32;
        }}
        .arch-arrow {{
            font-size: 1.3rem;
            color: #98aec8;
            margin-top: 2.0rem;
        }}
        .cost-box {{
            border: 1px solid var(--line-soft);
            border-radius: 12px;
            padding: 0.7rem 0.9rem;
            background: rgba(14, 22, 36, 0.76);
            margin-top: 0.4rem;
        }}
        .status-ok {{ color: var(--ok); font-weight: 700; }}
        .status-warn {{ color: var(--warn); font-weight: 700; }}
        .linkish button {{
            border: none !important;
            background: transparent !important;
            color: #82cdfd !important;
            text-decoration: underline;
            padding-left: 0 !important;
            padding-right: 0 !important;
            min-height: auto !important;
            height: auto !important;
            font-size: 0.85rem !important;
        }}
        .stTabs [data-baseweb="tab-list"] button {{
            background: rgba(14, 22, 34, 0.75);
            border: 1px solid rgba(102, 135, 177, 0.33);
            border-radius: 9px 9px 0 0;
            margin-right: 0.3rem;
            color: #cfdef2;
            transition: transform 180ms ease, opacity 180ms ease;
        }}
        .stTabs [data-baseweb="tab-list"] button[aria-selected="true"] {{
            border-color: var(--line-hard);
            color: #f0f6ff;
            transform: translateY(-1px);
            background: linear-gradient(180deg, rgba(20, 34, 55, 0.95), rgba(12, 21, 34, 0.95));
        }}
        {tab_lock_css(unlocked_step)}
        @keyframes riseIn {{
            0% {{ opacity: 0; transform: translateY(6px); }}
            100% {{ opacity: 1; transform: translateY(0); }}
        }}
        </style>
        """,
        unsafe_allow_html=True,
    )


def render_header() -> None:
    st.markdown(
        f"""
        <div class="hero-shell">
            <div class="hero-kicker">Applied AI Planning Studio</div>
            <div class="hero-title">End to End Applied AI Prototyping</div>
            <div class="hero-copy">{CAPABILITY_DESCRIPTION}</div>
            <div class="chipline">
                <span class="chip">4-Step Workflow</span>
                <span class="chip">Architecture + Model Planning</span>
                <span class="chip">Timeline + Cost Controls</span>
                <span class="chip">JSON Export</span>
            </div>
        </div>
        """,
        unsafe_allow_html=True,
    )


def render_architecture_preview() -> None:
    rows = st.session_state.get("architecture_rows", [])
    if not rows:
        return
    blocks: list[str] = []
    for idx, row in enumerate(rows[:5]):
        stage = str(row.get("stage", "Stage"))
        tech = str(row.get("tech", ""))
        blocks.append(f"<div class='arch-node'><div class='arch-stage'>{stage}</div><div class='arch-tech'>{tech}</div></div>")
        if idx < 4:
            blocks.append("<div class='arch-arrow'>→</div>")
    st.markdown(f"<div class='arch-flow'>{''.join(blocks)}</div>", unsafe_allow_html=True)


def render_locked_step(step_name: str, required_step: int) -> None:
    st.markdown(
        f"<div class='locked-hint'><strong>{step_name}</strong> unlocks after completing Step {required_step - 1}. Continue the workflow in order.</div>",
        unsafe_allow_html=True,
    )


def render_step_one(samples: list[dict[str, Any]]) -> None:
    st.markdown("<div class='step-note'><strong>Step 1</strong>: Define your concept, audience, budget envelope, and delivery timeline. Then unlock architecture design.</div>", unsafe_allow_html=True)
    link_col, _ = st.columns([1.2, 4.8])
    with link_col:
        st.markdown("<div class='linkish'>", unsafe_allow_html=True)
        if st.button("Try with sample", key="step1_try_sample"):
            apply_sample(samples)
            st.rerun()
        st.markdown("</div>", unsafe_allow_html=True)

    st.text_area(
        "Describe the AI product or experience you want to prototype",
        key="concept_description",
        height=180,
        placeholder="Start from zero: problem, expected behavior, user journey, constraints, and what success looks like.",
    )

    c1, c2 = st.columns(2)
    with c1:
        st.selectbox("Primary capability", PRIMARY_CAPABILITIES, key="primary_capability")
        st.selectbox("Target users", TARGET_USERS, key="target_users")
    with c2:
        st.slider("Budget constraint (USD)", min_value=5000, max_value=500000, step=5000, key="budget", format="$%d")
        st.slider("Timeline (weeks)", min_value=2, max_value=24, step=1, key="timeline_weeks")

    if st.button("Design Architecture →", type="primary", use_container_width=True, key="step1_next"):
        if not str(st.session_state.get("concept_description", "")).strip():
            st.warning("Add a concept description to continue.")
            return
        seed_step_two_state(reset_models=True)
        seed_step_three_state()
        st.session_state["unlocked_step"] = max(2, int(st.session_state.get("unlocked_step", 1)))
        st.session_state["final_plan"] = None
        st.session_state["final_plan_source"] = ""
        st.success("Step 2 unlocked: architecture and model selection ready.")


def render_step_two() -> None:
    unlocked = int(st.session_state.get("unlocked_step", 1))
    if unlocked < 2:
        render_locked_step("Step 2: Architecture & Model Selection", 2)
        return
    st.markdown("<div class='step-note'><strong>Step 2</strong>: Tune each architecture stage, compare model choices, and shape the data pipeline before planning build execution.</div>", unsafe_allow_html=True)
    ensure_architecture_widget_defaults()
    ensure_pipeline_widget_defaults()

    st.markdown("#### Proposed 5-stage architecture")
    render_architecture_preview()

    for idx, row in enumerate(st.session_state.get("architecture_rows", [])[:5]):
        stage = str(row.get("stage", ARCHITECTURE_STAGES[idx]))
        with st.container(border=True):
            st.markdown(f"**{stage}**")
            st.text_input("Tech choice", key=f"arch_tech_{idx}")
            st.text_area("Implementation focus", key=f"arch_details_{idx}", height=78)
    sync_architecture_from_widgets()

    st.markdown("#### Model comparison")
    options = st.session_state.get("model_options", [])
    if not isinstance(options, list):
        options = []
    if options:
        st.dataframe(pd.DataFrame(options), use_container_width=True, hide_index=True)
    else:
        st.warning("No model options available.")

    model_names = [str(item.get("model", "")) for item in options if str(item.get("model", "")).strip()]
    if model_names:
        current = str(st.session_state.get("selected_model_name", ""))
        if current not in model_names:
            st.session_state["selected_model_name"] = model_names[0]
        st.selectbox("Select primary model", model_names, key="selected_model_name")

    with st.expander("Add custom model entry"):
        m1, m2 = st.columns(2)
        with m1:
            custom_model = st.text_input("Model name", key="custom_model_name")
            custom_provider = st.text_input("Provider", key="custom_model_provider")
            custom_cost = st.text_input("Cost per 1k requests", key="custom_model_cost", placeholder="$12.00")
        with m2:
            custom_match = st.text_input("Capability match", key="custom_model_match")
            custom_latency = st.selectbox("Latency", ["Low", "Medium", "High"], key="custom_model_latency")
            custom_pros = st.text_input("Pros", key="custom_model_pros")
            custom_cons = st.text_input("Cons", key="custom_model_cons")
        if st.button("Add model", key="add_custom_model"):
            name = str(custom_model).strip()
            if not name:
                st.warning("Model name is required.")
            else:
                new_entry = {
                    "model": name,
                    "provider": str(custom_provider).strip() or "Custom",
                    "capability_match": str(custom_match).strip() or "Custom fit",
                    "cost_1k_requests": str(custom_cost).strip() or "$0.00",
                    "latency": str(custom_latency),
                    "pros": str(custom_pros).strip() or "Custom option",
                    "cons": str(custom_cons).strip() or "Needs validation",
                }
                updated_models = [dict(item) for item in options]
                updated_models.append(new_entry)
                st.session_state["model_options"] = updated_models
                st.session_state["selected_model_name"] = name
                st.success(f"Added model option: {name}")
                st.rerun()

    st.markdown("#### Data pipeline overview")
    st.text_input("Sources (comma separated)", key="pipeline_sources")
    p1, p2 = st.columns(2)
    with p1:
        st.text_area("Ingestion", key="pipeline_ingestion", height=88)
        st.text_area("Preprocessing", key="pipeline_preprocessing", height=88)
    with p2:
        st.text_area("Storage", key="pipeline_storage", height=88)
        st.text_area("Serving", key="pipeline_serving", height=88)
    sync_pipeline_from_widgets()

    if st.button("Plan Build →", type="primary", use_container_width=True, key="step2_next"):
        sync_architecture_from_widgets()
        sync_pipeline_from_widgets()
        if not st.session_state.get("build_plan_rows"):
            seed_step_three_state()
        st.session_state["unlocked_step"] = max(3, int(st.session_state.get("unlocked_step", 1)))
        st.success("Step 3 unlocked: build planning and budget controls ready.")


def move_week(direction: str) -> None:
    rows = [dict(item) for item in st.session_state.get("build_plan_rows", [])]
    if not rows:
        return
    pick = str(st.session_state.get("move_week_pick", "")).strip()
    idx = -1
    for i, row in enumerate(rows):
        if str(row.get("Week", "")).strip() == pick:
            idx = i
            break
    if idx == -1:
        return
    if direction == "up" and idx > 0:
        rows[idx - 1], rows[idx] = rows[idx], rows[idx - 1]
    if direction == "down" and idx < len(rows) - 1:
        rows[idx + 1], rows[idx] = rows[idx], rows[idx + 1]
    for i, row in enumerate(rows, start=1):
        row["Week"] = str(i)
    st.session_state["build_plan_rows"] = rows


def add_week_row() -> None:
    rows = [dict(item) for item in st.session_state.get("build_plan_rows", [])]
    next_week = len(rows) + 1
    team = template_library().get(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0]), template_library()["Text Generation"]).get("team", "Cross-functional team")
    rows.append(
        {
            "Week": str(next_week),
            "Milestone": f"Phase {next_week}",
            "Deliverables": "Define delivery output",
            "Team Allocation": str(team),
            "Risk Control": risk_note(str(st.session_state.get("target_users", TARGET_USERS[0]))),
        }
    )
    st.session_state["build_plan_rows"] = rows
    st.session_state["timeline_weeks"] = len(rows)


def remove_week_row() -> None:
    rows = [dict(item) for item in st.session_state.get("build_plan_rows", [])]
    if len(rows) <= 1:
        return
    rows = rows[:-1]
    for i, row in enumerate(rows, start=1):
        row["Week"] = str(i)
    st.session_state["build_plan_rows"] = rows
    st.session_state["timeline_weeks"] = len(rows)


def render_step_three() -> None:
    unlocked = int(st.session_state.get("unlocked_step", 1))
    if unlocked < 3:
        render_locked_step("Step 3: Build Plan & Timeline", 3)
        return
    st.markdown("<div class='step-note'><strong>Step 3</strong>: Edit weekly milestones, reorder phases, refine team allocations, and tune cost assumptions with live budget fit.</div>", unsafe_allow_html=True)

    rows = st.session_state.get("build_plan_rows", [])
    if not rows:
        seed_step_three_state()
        rows = st.session_state.get("build_plan_rows", [])

    top1, top2, top3, top4 = st.columns([1.2, 1.2, 1.6, 2.0])
    with top1:
        if st.button("Add Week", key="add_week_btn"):
            add_week_row()
            st.rerun()
    with top2:
        if st.button("Remove Week", key="remove_week_btn"):
            remove_week_row()
            st.rerun()
    with top3:
        week_options = [str(item.get("Week", "")) for item in st.session_state.get("build_plan_rows", [])]
        if week_options:
            st.selectbox("Move week", week_options, key="move_week_pick")
    with top4:
        b1, b2 = st.columns(2)
        with b1:
            if st.button("Move Up", key="move_up_btn"):
                move_week("up")
                st.rerun()
        with b2:
            if st.button("Move Down", key="move_down_btn"):
                move_week("down")
                st.rerun()

    edited = st.data_editor(
        pd.DataFrame(st.session_state.get("build_plan_rows", [])),
        key="build_plan_editor",
        use_container_width=True,
        hide_index=True,
        num_rows="dynamic",
        column_config={
            "Week": st.column_config.TextColumn(width="small"),
            "Milestone": st.column_config.TextColumn(width="medium"),
            "Deliverables": st.column_config.TextColumn(width="large"),
            "Team Allocation": st.column_config.TextColumn(width="large"),
            "Risk Control": st.column_config.TextColumn(width="large"),
        },
    )
    edited_rows = edited.fillna("").to_dict("records")
    normalized: list[dict[str, str]] = []
    for i, row in enumerate(edited_rows, start=1):
        normalized.append(
            {
                "Week": str(i),
                "Milestone": str(row.get("Milestone", "")).strip() or f"Phase {i}",
                "Deliverables": str(row.get("Deliverables", "")).strip() or "Define delivery output",
                "Team Allocation": str(row.get("Team Allocation", "")).strip() or "Cross-functional team",
                "Risk Control": str(row.get("Risk Control", "")).strip() or risk_note(str(st.session_state.get("target_users", TARGET_USERS[0]))),
            }
        )
    st.session_state["build_plan_rows"] = normalized
    st.session_state["timeline_weeks"] = len(normalized)

    st.markdown("#### Cost breakdown")
    cost_inputs = st.session_state.get("cost_inputs", {})
    c1, c2, c3, c4, c5 = st.columns(5)
    with c1:
        compute = st.number_input("Compute", min_value=0, step=500, value=int(cost_inputs.get("compute", 0)), key="cost_compute")
    with c2:
        storage = st.number_input("Storage", min_value=0, step=500, value=int(cost_inputs.get("storage", 0)), key="cost_storage")
    with c3:
        model_api = st.number_input("Model API", min_value=0, step=500, value=int(cost_inputs.get("model_api", 0)), key="cost_model_api")
    with c4:
        development = st.number_input("Development", min_value=0, step=500, value=int(cost_inputs.get("development", 0)), key="cost_development")
    with c5:
        security = st.number_input("Security", min_value=0, step=500, value=int(cost_inputs.get("security", 0)), key="cost_security")

    st.session_state["cost_inputs"] = {
        "compute": int(compute),
        "storage": int(storage),
        "model_api": int(model_api),
        "development": int(development),
        "security": int(security),
    }
    recalculate_cost_summary()

    summary = st.session_state.get("cost_summary", {})
    fit = str(summary.get("fit", "Unknown"))
    status_class = "status-ok" if fit == "Within target" else "status-warn"
    st.markdown(
        f"""
        <div class='cost-box'>
            <div><strong>Subtotal:</strong> ${int(summary.get('subtotal', 0)):,}</div>
            <div><strong>Contingency (15%):</strong> ${int(summary.get('contingency', 0)):,}</div>
            <div><strong>Running Total:</strong> ${int(summary.get('total', 0)):,}</div>
            <div><strong>Budget Target:</strong> ${int(summary.get('budget', 0)):,}</div>
            <div><strong>Status:</strong> <span class='{status_class}'>{fit}</span></div>
        </div>
        """,
        unsafe_allow_html=True,
    )

    if st.button("Generate Full Plan →", type="primary", use_container_width=True, key="step3_next"):
        allowed, retry = check_rate_limit()
        if not allowed:
            st.error(f"Rate limit reached. Try again in {retry}s ({RATE_LIMIT_REQUESTS}/{RATE_LIMIT_WINDOW_SECONDS}s).")
            return
        sync_architecture_from_widgets()
        sync_pipeline_from_widgets()
        architecture_text = build_architecture_diagram_text(st.session_state.get("architecture_rows", []))
        selected_model_name = str(st.session_state.get("selected_model_name", ""))
        ai_input = {
            "concept_description": str(st.session_state.get("concept_description", "")).strip(),
            "primary_capability": str(st.session_state.get("primary_capability", PRIMARY_CAPABILITIES[0])),
            "target_users": str(st.session_state.get("target_users", TARGET_USERS[0])),
            "budget": int(st.session_state.get("budget", 0)),
            "timeline_weeks": int(st.session_state.get("timeline_weeks", 0)),
            "selected_model": selected_model_name,
        }
        with st.spinner("Synthesizing final strategy and validating full plan..."):
            ai_result = gemini_strategy(ai_input, architecture_text)
        if ai_result:
            st.session_state["ai_strategy_note"] = str(ai_result.get("strategy_note", "")).strip()
            ai_arch = str(ai_result.get("architecture_diagram", "")).strip()
            st.session_state["ai_architecture_text"] = ai_arch if ai_arch else architecture_text
            source = f"Gemini ({GEMINI_MODEL})"
        else:
            st.session_state["ai_strategy_note"] = ""
            st.session_state["ai_architecture_text"] = architecture_text
            source = "Heuristic fallback"
        st.session_state["final_plan"] = assemble_final_plan(source)
        st.session_state["final_plan_source"] = source
        st.session_state["unlocked_step"] = max(4, int(st.session_state.get("unlocked_step", 1)))
        st.success("Step 4 unlocked: final prototype plan generated.")


def reset_workflow_state() -> None:
    keep_timestamps = list(st.session_state.get("request_timestamps", []))
    for key in list(st.session_state.keys()):
        del st.session_state[key]
    init_state()
    st.session_state["request_timestamps"] = keep_timestamps
    clear_dynamic_widget_keys()


def render_step_four() -> None:
    unlocked = int(st.session_state.get("unlocked_step", 1))
    if unlocked < 4:
        render_locked_step("Step 4: Prototype Plan", 4)
        return
    st.markdown("<div class='step-note'><strong>Step 4</strong>: Consolidated strategy, architecture, selected model, pipeline, timeline, and budget estimates with export-ready JSON.</div>", unsafe_allow_html=True)

    plan = st.session_state.get("final_plan")
    if not isinstance(plan, dict):
        plan = assemble_final_plan("Heuristic fallback")
        st.session_state["final_plan"] = plan

    source = str(plan.get("source", st.session_state.get("final_plan_source", "Heuristic fallback")))
    if source.startswith("Gemini"):
        st.success(f"Plan source: {source}")
    else:
        st.info(f"Plan source: {source}")

    st.markdown("#### Strategy note")
    st.write(str(plan.get("strategy_note", "")))

    st.markdown("#### Architecture diagram")
    st.code(str(plan.get("architecture_diagram", "")), language="text")

    st.markdown("#### Model choices")
    selected = plan.get("selected_model", {})
    selected_name = str(selected.get("model", ""))
    if selected_name:
        st.markdown(f"**Selected model:** `{selected_name}`")
    model_options = plan.get("model_options", [])
    if isinstance(model_options, list) and model_options:
        st.dataframe(pd.DataFrame(model_options), use_container_width=True, hide_index=True)

    st.markdown("#### Data pipeline")
    pipeline = plan.get("data_pipeline", {}) if isinstance(plan.get("data_pipeline", {}), dict) else {}
    p_sources = pipeline.get("sources", [])
    if isinstance(p_sources, list) and p_sources:
        st.markdown(", ".join([f"`{str(item)}`" for item in p_sources]))
    st.write(f"Ingestion: {pipeline.get('ingestion', '-')}")
    st.write(f"Preprocessing: {pipeline.get('preprocessing', '-')}")
    st.write(f"Storage: {pipeline.get('storage', '-')}")
    st.write(f"Serving: {pipeline.get('serving', '-')}")

    st.markdown("#### Build timeline")
    build_plan = plan.get("build_plan", [])
    if isinstance(build_plan, list) and build_plan:
        st.dataframe(pd.DataFrame(build_plan), use_container_width=True, hide_index=True)

    st.markdown("#### Cost estimate")
    cost = plan.get("cost_estimate", {}) if isinstance(plan.get("cost_estimate", {}), dict) else {}
    c1, c2, c3 = st.columns(3)
    with c1:
        st.metric("Target budget", f"${int(cost.get('budget', 0)):,}")
    with c2:
        st.metric("Estimated total", f"${int(cost.get('total', 0)):,}")
    with c3:
        st.metric("Budget fit", str(cost.get("fit", "Unknown")))
    line_items = cost.get("line_items", [])
    if isinstance(line_items, list) and line_items:
        st.dataframe(pd.DataFrame(line_items), use_container_width=True, hide_index=True)

    payload = json.dumps(plan, indent=2)
    d1, d2 = st.columns(2)
    with d1:
        st.download_button(
            "Download as JSON",
            data=payload,
            file_name="prototype_plan.json",
            mime="application/json",
            use_container_width=True,
        )
    with d2:
        if st.button("Plan New Prototype", use_container_width=True, key="plan_new_prototype"):
            reset_workflow_state()
            st.rerun()


def render_dataset_expander(samples: list[dict[str, Any]]) -> None:
    st.divider()
    with st.expander("Sample concept dataset"):
        if samples:
            st.dataframe(pd.DataFrame(samples), use_container_width=True, hide_index=True)
        else:
            st.write("No records found in data/sample_concepts.jsonl")


def main() -> None:
    st.set_page_config(page_title=APP_TITLE, page_icon="🧪", layout="wide")
    init_state()
    samples = load_sample_concepts()
    apply_theme(int(st.session_state.get("unlocked_step", 1)))
    render_header()

    tabs = st.tabs(plan_tab_labels(int(st.session_state.get("unlocked_step", 1))))
    with tabs[0]:
        render_step_one(samples)
    with tabs[1]:
        render_step_two()
    with tabs[2]:
        render_step_three()
    with tabs[3]:
        render_step_four()

    render_dataset_expander(samples)


if __name__ == "__main__":
    main()