File size: 120,015 Bytes
a11bfee
e9fdc7c
a11bfee
 
3f5fadf
 
a86e220
 
 
 
 
 
 
49293a6
a86e220
 
7f3d172
a86e220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf68103
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf68103
 
 
 
a11bfee
bf68103
 
 
 
 
 
 
 
 
 
a11bfee
 
 
 
 
bf68103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
 
 
bf68103
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
 
 
 
bf68103
 
bd96870
8882332
bd96870
 
8882332
 
bd96870
 
 
 
 
 
 
 
8882332
 
 
 
 
 
a11bfee
bd96870
 
 
 
 
8882332
 
 
 
a11bfee
 
bd96870
5570429
bd96870
bf68103
bd96870
 
bf68103
bd96870
 
dddbaa5
bd96870
 
 
a11bfee
 
5570429
bd96870
5570429
49293a6
a11bfee
49293a6
a11bfee
 
9a7698c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
9a7698c
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
 
 
 
9a7698c
 
a11bfee
 
 
9a7698c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
 
9a7698c
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7698c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
 
 
 
9a7698c
 
a11bfee
 
 
9a7698c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
 
9a7698c
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7698c
 
 
a11bfee
 
9a7698c
a11bfee
9a7698c
 
a11bfee
9a7698c
a11bfee
 
 
 
 
9a7698c
 
 
a11bfee
9a7698c
a11bfee
 
 
 
 
 
9a7698c
 
 
 
a11bfee
9a7698c
 
 
 
 
a11bfee
 
 
9a7698c
 
a11bfee
 
9a7698c
 
 
 
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7698c
49293a6
a11bfee
 
49293a6
 
 
 
 
 
a11bfee
 
 
 
 
 
 
 
 
49293a6
a11bfee
49293a6
 
 
 
 
 
a11bfee
49293a6
 
 
 
 
 
8882332
a11bfee
a86e220
8882332
9a7698c
8882332
 
fc65cce
 
a11bfee
8882332
 
a86e220
fc65cce
 
8882332
fc65cce
 
 
 
 
 
 
8882332
fc65cce
 
 
 
 
 
 
 
 
 
9a7698c
fc65cce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a11bfee
 
fc65cce
a11bfee
 
 
 
 
 
 
 
 
fc65cce
 
 
 
 
a11bfee
 
 
 
 
fc65cce
 
9a7698c
bd96870
5570429
8882332
fc65cce
bd96870
bf68103
a11bfee
bf68103
 
 
 
 
 
 
 
a11bfee
 
bf68103
 
a86e220
fc65cce
3713e64
 
 
 
 
fc65cce
 
3713e64
 
 
fc65cce
3713e64
fc65cce
a11bfee
3713e64
 
 
fc65cce
 
a11bfee
 
 
 
 
 
 
 
3713e64
 
 
fc65cce
 
a11bfee
 
 
3713e64
 
a11bfee
8882332
9a7698c
a86e220
fc65cce
 
 
 
 
 
 
 
5570429
fc65cce
8882332
bd96870
 
 
 
 
 
 
 
 
a11bfee
 
 
 
bd96870
8882332
a11bfee
a86e220
a11bfee
a86e220
fc65cce
 
 
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc65cce
 
5570429
fc65cce
8882332
a11bfee
 
8882332
a11bfee
 
8882332
a11bfee
 
8882332
a11bfee
 
 
8882332
a11bfee
a86e220
8882332
 
a11bfee
a86e220
bd96870
5570429
 
8882332
 
fc65cce
a11bfee
fc65cce
 
 
 
 
 
bf68103
a11bfee
bf68103
 
 
 
 
a11bfee
 
bf68103
 
8882332
 
a86e220
8882332
 
 
 
 
a86e220
8882332
 
 
 
 
 
a86e220
 
a11bfee
a86e220
 
a11bfee
a86e220
 
 
 
a11bfee
 
445884d
a11bfee
 
 
a86e220
 
 
 
 
5570429
a11bfee
 
a86e220
 
a11bfee
 
 
 
 
 
 
 
 
 
a86e220
 
a11bfee
 
 
a86e220
 
 
 
8882332
a11bfee
 
a86e220
 
 
44e7696
5570429
a11bfee
a86e220
a11bfee
 
a86e220
 
 
5570429
a11bfee
a86e220
a11bfee
 
a86e220
 
5570429
a11bfee
 
 
 
 
 
 
 
5570429
 
 
 
a11bfee
a86e220
8882332
 
 
 
 
 
 
a86e220
a11bfee
a86e220
 
 
 
 
 
 
 
 
 
 
 
ca25698
a86e220
5570429
a86e220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5570429
 
9779701
a11bfee
9779701
a11bfee
445884d
8882332
a11bfee
 
8882332
 
a11bfee
445884d
a11bfee
445884d
8882332
a11bfee
 
8882332
 
a11bfee
445884d
a11bfee
445884d
8882332
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8882332
 
a11bfee
9779701
4bedbf4
a11bfee
4bedbf4
bd96870
49293a6
8882332
445884d
9f1b72c
445884d
a11bfee
 
 
 
 
 
445884d
bd96870
 
 
 
445884d
bd96870
 
 
 
445884d
bd96870
 
 
445884d
bd96870
 
 
445884d
bd96870
 
 
445884d
bd96870
8882332
bd96870
a11bfee
 
 
 
 
 
 
445884d
 
 
 
 
a11bfee
 
 
 
 
445884d
0dc832b
 
 
 
 
 
4bedbf4
5570429
a11bfee
5570429
bd96870
dddbaa5
 
8882332
dddbaa5
8882332
 
 
 
 
 
a11bfee
ecfa053
 
a11bfee
ecfa053
bf68103
 
8882332
 
 
 
 
 
 
a11bfee
 
 
 
 
 
8882332
 
 
 
dddbaa5
bf68103
 
dddbaa5
 
00b0f0f
dddbaa5
 
00b0f0f
dddbaa5
 
 
 
 
 
 
 
 
 
 
 
00b0f0f
 
dddbaa5
 
 
 
 
 
 
 
00b0f0f
 
dddbaa5
00b0f0f
dddbaa5
 
00b0f0f
8882332
00b0f0f
 
 
a11bfee
 
00b0f0f
 
 
49293a6
dddbaa5
a11bfee
 
00b0f0f
 
 
 
 
dddbaa5
 
00b0f0f
a11bfee
 
00b0f0f
 
dddbaa5
 
 
 
 
 
 
 
 
 
 
 
00b0f0f
ecfa053
00b0f0f
 
 
 
a11bfee
 
00b0f0f
49293a6
00b0f0f
49293a6
 
a11bfee
 
00b0f0f
 
 
 
dddbaa5
a11bfee
 
00b0f0f
49293a6
a11bfee
 
00b0f0f
8882332
a11bfee
 
ecfa053
 
a11bfee
 
ecfa053
49293a6
a11bfee
ecfa053
 
a11bfee
 
ecfa053
49293a6
a11bfee
ecfa053
 
a11bfee
 
ecfa053
8882332
bf68103
8882332
 
 
 
 
 
00b0f0f
8882332
a11bfee
 
 
 
 
 
 
 
 
8882332
 
 
 
 
a11bfee
 
8882332
 
 
 
 
 
5570429
00b0f0f
a11bfee
00b0f0f
 
a11bfee
bf68103
a24bd74
bf68103
a11bfee
00b0f0f
 
 
dddbaa5
 
a11bfee
 
 
 
 
 
 
a24bd74
a11bfee
 
dddbaa5
 
 
 
 
 
 
 
a11bfee
dddbaa5
a24bd74
 
 
00b0f0f
49293a6
00b0f0f
49293a6
00b0f0f
 
a11bfee
 
 
 
 
00b0f0f
dddbaa5
bf68103
00b0f0f
a11bfee
00b0f0f
 
 
 
dddbaa5
 
00b0f0f
 
 
dddbaa5
00b0f0f
 
a11bfee
 
00b0f0f
a11bfee
 
 
 
 
 
 
 
 
dddbaa5
a11bfee
dddbaa5
a11bfee
 
 
 
00b0f0f
 
 
 
 
 
a24bd74
00b0f0f
 
 
dddbaa5
a11bfee
 
 
 
 
00b0f0f
 
a24bd74
00b0f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dddbaa5
 
 
 
 
 
a11bfee
 
00b0f0f
 
dddbaa5
00b0f0f
dddbaa5
00b0f0f
 
 
 
 
 
 
 
dddbaa5
 
00b0f0f
 
 
dddbaa5
00b0f0f
 
 
a11bfee
 
00b0f0f
a11bfee
 
 
 
 
 
 
 
 
dddbaa5
a11bfee
dddbaa5
a11bfee
 
 
 
00b0f0f
 
 
 
 
 
dddbaa5
00b0f0f
 
 
dddbaa5
a11bfee
00b0f0f
 
 
a24bd74
00b0f0f
 
 
 
 
 
 
 
 
 
 
 
 
dddbaa5
 
 
 
 
 
a11bfee
 
00b0f0f
 
 
 
 
 
dddbaa5
00b0f0f
 
 
 
 
a11bfee
 
 
00b0f0f
 
 
 
 
dddbaa5
00b0f0f
 
 
a24bd74
dddbaa5
 
a11bfee
 
00b0f0f
 
 
 
 
 
 
dddbaa5
00b0f0f
 
 
 
 
a11bfee
 
 
00b0f0f
 
 
 
 
a24bd74
00b0f0f
 
 
a24bd74
dddbaa5
 
a11bfee
 
00b0f0f
 
 
 
 
a24bd74
dddbaa5
9a7698c
a11bfee
9a7698c
 
a11bfee
9a7698c
 
 
 
 
 
 
 
 
 
a11bfee
 
 
9a7698c
 
 
 
 
 
 
 
 
 
 
a11bfee
 
 
 
 
 
 
 
 
9a7698c
a11bfee
 
 
 
 
9a7698c
 
 
 
 
 
a11bfee
 
 
 
9a7698c
 
 
 
 
 
 
 
a11bfee
 
 
 
 
9a7698c
 
a11bfee
9a7698c
a11bfee
 
 
 
 
9a7698c
 
 
fc65cce
a11bfee
5aa5b79
 
a11bfee
5aa5b79
bf68103
 
fc65cce
 
5aa5b79
445884d
fc65cce
445884d
bf68103
 
 
 
a11bfee
 
 
bf68103
44e7696
bf68103
44e7696
859f566
a11bfee
fc65cce
5aa5b79
a11bfee
fc65cce
5aa5b79
a11bfee
 
 
44e7696
445884d
5aa5b79
5570429
44e7696
445884d
 
 
 
 
fc65cce
44e7696
a86e220
44e7696
 
fc65cce
859f566
a86e220
44e7696
 
fc65cce
5aa5b79
a86e220
44e7696
 
fc65cce
5aa5b79
a86e220
44e7696
 
 
fc65cce
5aa5b79
445884d
fc65cce
5aa5b79
5570429
5aa5b79
5570429
445884d
 
 
0dc832b
445884d
44e7696
a11bfee
44e7696
a11bfee
5aa5b79
445884d
 
 
 
5aa5b79
859f566
a11bfee
44e7696
 
445884d
44e7696
5aa5b79
 
a11bfee
bd96870
5570429
a11bfee
445884d
bd96870
445884d
dddbaa5
 
445884d
a11bfee
8882332
445884d
fc65cce
445884d
49293a6
445884d
 
a11bfee
 
 
dddbaa5
fc65cce
00b0f0f
 
445884d
 
 
00b0f0f
dddbaa5
 
a11bfee
 
 
 
 
 
 
445884d
00b0f0f
445884d
 
 
 
 
 
dddbaa5
a11bfee
a4b81cc
445884d
a11bfee
445884d
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445884d
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445884d
 
a11bfee
 
 
 
 
 
 
 
 
 
 
445884d
a11bfee
445884d
a11bfee
 
 
 
5570429
a11bfee
 
445884d
a4b81cc
445884d
5570429
445884d
 
 
 
a11bfee
 
 
 
 
445884d
a4b81cc
 
a11bfee
a86e220
 
 
 
 
 
a11bfee
 
 
 
 
 
a86e220
a11bfee
 
 
 
 
a86e220
 
a11bfee
 
 
 
 
bf68103
a11bfee
a86e220
a11bfee
 
 
 
 
a86e220
 
a11bfee
8882332
a11bfee
a86e220
 
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a86e220
 
a11bfee
 
 
 
 
a86e220
a11bfee
 
 
 
 
 
a4b81cc
a11bfee
44e7696
a11bfee
 
445884d
5aa5b79
 
a11bfee
49293a6
a11bfee
 
 
49293a6
a11bfee
 
d265a89
 
a86e220
 
a11bfee
a86e220
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5570429
a11bfee
 
 
a86e220
a11bfee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
continue where the previous AI agent left off: """
πŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
ENHANCED VERSION WITH CLEAR BOUNDARIES AND RELIABLE VISUALIZATIONS
Fixed to show clear OSS vs Enterprise boundaries with architectural honesty
"""

import logging
import sys
import traceback
import json
import datetime
import asyncio
import time
import random
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple

# ===========================================
# CONFIGURE LOGGING FIRST
# ===========================================
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler('arf_demo.log')
    ]
)
logger = logging.getLogger(__name__)

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent))

# ===========================================
# BOUNDARY MANAGEMENT SYSTEM - NEW CRITICAL ADDITION
# ===========================================
class BoundaryManager:
    """Manages clear boundaries between OSS and Enterprise"""
    
    @staticmethod
    def get_system_boundaries() -> Dict[str, Any]:
        """Get clear system boundary definitions"""
        installation = get_installation_status()
        
        boundaries = {
            "oss": {
                "available": installation["oss_installed"],
                "version": installation["oss_version"] or "mock",
                "license": "Apache 2.0",
                "capabilities": ["advisory", "analysis", "reasoning"],
                "cannot_do": ["execute", "modify_infrastructure", "autonomous_healing"],
                "label": "βœ… REAL ARF OSS" if installation["oss_installed"] else "⚠️ MOCK ARF",
                "color": "#10b981" if installation["oss_installed"] else "#64748b",
                "icon": "βœ…" if installation["oss_installed"] else "⚠️"
            },
            "enterprise": {
                "available": installation["enterprise_installed"],
                "version": installation["enterprise_version"] or "simulated",
                "license": "Commercial" if installation["enterprise_installed"] else "SIMULATED",
                "capabilities": ["autonomous_execution", "rollback_guarantees", "novel_protocols"],
                "requires": ["infrastructure_access", "safety_controls", "enterprise_license"],
                "label": "πŸš€ REAL Enterprise" if installation["enterprise_installed"] else "🎭 SIMULATED Enterprise",
                "color": "#8b5cf6" if installation["enterprise_installed"] else "#f59e0b",
                "icon": "πŸš€" if installation["enterprise_installed"] else "🎭"
            },
            "demo_mode": {
                "architecture": "OSS advises β†’ Enterprise executes",
                "honesty_level": "Architecturally Honest",
                "transparency": "Clear boundaries between real and simulated"
            }
        }
        
        return boundaries
    
    @staticmethod
    def get_boundary_badges() -> str:
        """Get HTML badges showing clear boundaries"""
        boundaries = BoundaryManager.get_system_boundaries()
        oss = boundaries["oss"]
        enterprise = boundaries["enterprise"]
        
        return f"""
        <div style="margin: 20px 0; padding: 15px; background: #f8fafc; border-radius: 12px; 
                   border: 2px solid #e2e8f0; text-align: center;">
            <div style="font-size: 14px; color: #64748b; margin-bottom: 15px; font-weight: 500;">
                πŸ—οΈ System Architecture Boundaries
            </div>
            
            <div style="display: flex; justify-content: center; align-items: center; gap: 20px; 
                       flex-wrap: wrap; margin-bottom: 15px;">
                <div style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; 
                           background: {oss['color']}; color: white; border-radius: 20px; 
                           font-size: 12px; font-weight: bold;">
                    <span>{oss['icon']}</span>
                    <span>{oss['label']} v{oss['version']}</span>
                </div>
                
                <div style="font-size: 20px; color: #94a3b8;">β†’</div>
                
                <div style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; 
                           background: {enterprise['color']}; color: white; border-radius: 20px; 
                           font-size: 12px; font-weight: bold;">
                    <span>{enterprise['icon']}</span>
                    <span>{enterprise['label']}</span>
                </div>
            </div>
            
            <div style="font-size: 13px; color: #475569; line-height: 1.5;">
                <strong>OSS advises</strong> ({oss['license']}) β€’ <strong>Enterprise executes</strong> ({enterprise['license']})<br>
                Clear separation ensures production safety and architectural honesty
            </div>
        </div>
        """
    
    @staticmethod
    def create_agent_with_boundary(agent_name: str, status: str, 
                                 is_real_arf: bool = True, confidence: float = 0.0) -> str:
        """Create agent display with clear boundary indicator"""
        icons = {
            "Detection": "πŸ•΅οΈβ€β™‚οΈ",
            "Recall": "🧠", 
            "Decision": "🎯"
        }
        
        border_color = "#10b981" if is_real_arf else "#f59e0b"
        background = "#f0fdf4" if is_real_arf else "#fef3c7"
        badge_text = "REAL ARF" if is_real_arf else "SIMULATED"
        
        # Confidence bar
        confidence_bar = ""
        if confidence > 0:
            confidence_color = "#10b981" if confidence >= 0.9 else "#f59e0b" if confidence >= 0.7 else "#ef4444"
            confidence_bar = f"""
            <div style="margin: 10px 0;">
                <div style="display: flex; justify-content: space-between; font-size: 12px; margin-bottom: 4px;">
                    <span style="color: #64748b;">Confidence</span>
                    <span style="color: {confidence_color}; font-weight: 600;">{confidence:.1%}</span>
                </div>
                <div style="height: 6px; background: #e2e8f0; border-radius: 3px;">
                    <div style="width: {confidence*100}%; height: 100%; background: {confidence_color}; 
                             border-radius: 3px;"></div>
                </div>
            </div>
            """
        
        return f"""
        <div style="border: 2px solid {border_color}; border-radius: 12px; padding: 20px; 
                   background: {background}; text-align: center; position: relative;">
            
            <!-- Boundary badge -->
            <div style="position: absolute; top: -10px; left: 50%; transform: translateX(-50%);
                       padding: 2px 12px; background: {border_color}; color: white; 
                       border-radius: 12px; font-size: 11px; font-weight: bold;">
                {badge_text}
            </div>
            
            <!-- Agent icon and name -->
            <div style="font-size: 32px; margin-bottom: 10px;">{icons.get(agent_name, 'πŸ€–')}</div>
            <div style="font-size: 16px; font-weight: 600; color: #1e293b; margin-bottom: 8px;">
                {agent_name} Agent
            </div>
            
            <!-- Status -->
            <div style="font-size: 14px; color: #475569; margin-bottom: 12px; line-height: 1.4;">
                {status}
            </div>
            
            {confidence_bar}
            
            <!-- Mode indicator -->
            <div style="margin-top: 10px; padding: 6px 12px; background: white; 
                       border-radius: 8px; display: inline-block;">
                <div style="font-size: 12px; color: {border_color}; font-weight: 600;">
                    {badge_text} MODE
                </div>
            </div>
        </div>
        """
    
    @staticmethod
    def create_boundary_indicator(action: str, is_simulated: bool = True) -> str:
        """Create clear execution boundary indicator"""
        if is_simulated:
            return f"""
            <div style="border: 3px dashed #f59e0b; border-radius: 16px; padding: 25px; 
                       background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
                       text-align: center; margin: 20px 0;">
                <div style="font-size: 36px; margin-bottom: 15px;">🎭</div>
                <h4 style="margin: 0 0 12px 0; font-size: 20px; color: #92400e; font-weight: 700;">
                    SIMULATED ENTERPRISE EXECUTION
                </h4>
                <p style="font-size: 15px; color: #92400e; margin-bottom: 15px; line-height: 1.6;">
                    <strong>Action:</strong> {action}<br>
                    <strong>Mode:</strong> Enterprise Simulation (not real execution)<br>
                    <strong>Boundary:</strong> OSS advises β†’ Enterprise would execute
                </p>
                <div style="display: inline-block; padding: 10px 24px; background: #92400e; 
                           border-radius: 20px; font-size: 14px; font-weight: bold; color: white; 
                           text-transform: uppercase; letter-spacing: 1px;">
                    DEMO BOUNDARY
                </div>
                <p style="font-size: 13px; color: #92400e; margin-top: 15px; font-style: italic;">
                    In production, Enterprise edition would execute against real infrastructure
                </p>
            </div>
            """
        else:
            return f"""
            <div style="border: 3px solid #10b981; border-radius: 16px; padding: 25px; 
                       background: linear-gradient(135deg, #f0fdf4 0%, #bbf7d0 100%);
                       text-align: center; margin: 20px 0;">
                <div style="font-size: 36px; margin-bottom: 15px;">⚑</div>
                <h4 style="margin: 0 0 12px 0; font-size: 20px; color: #065f46; font-weight: 700;">
                    REAL ENTERPRISE EXECUTION
                </h4>
                <p style="font-size: 15px; color: #065f46; margin-bottom: 15px; line-height: 1.6;">
                    <strong>Action:</strong> {action}<br>
                    <strong>Mode:</strong> Enterprise Autonomous<br>
                    <strong>Boundary:</strong> Real execution with safety guarantees
                </p>
                <div style="display: inline-block; padding: 10px 24px; background: #065f46; 
                           border-radius: 20px; font-size: 14px; font-weight: bold; color: white; 
                           text-transform: uppercase; letter-spacing: 1px;">
                    ENTERPRISE+
                </div>
            </div>
            """

# ===========================================
# ARF INSTALLATION CHECK SYSTEM - ENHANCED
# ===========================================
def check_arf_installation():
    """
    Check if real ARF packages are installed
    Returns detailed installation status with boundary info
    """
    results = {
        "oss_installed": False,
        "enterprise_installed": False,
        "oss_version": None,
        "enterprise_version": None,
        "oss_edition": "unknown",
        "oss_license": "unknown",
        "execution_allowed": False,
        "recommendations": [],
        "boundaries": {
            "oss_can": ["advisory_analysis", "rag_search", "healing_intent"],
            "oss_cannot": ["execute", "modify_infra", "autonomous_healing"],
            "enterprise_requires": ["license", "infra_access", "safety_controls"]
        },
        "badges": {
            "oss": {"text": "⚠️ Mock ARF", "color": "#f59e0b", "icon": "⚠️"},
            "enterprise": {"text": "πŸ”’ Enterprise Required", "color": "#64748b", "icon": "πŸ”’"}
        },
        "timestamp": datetime.datetime.now().isoformat()
    }
    
    # Check OSS package
    try:
        import agentic_reliability_framework as arf_oss
        results["oss_installed"] = True
        results["oss_version"] = getattr(arf_oss, '__version__', '3.3.7')
        
        # Try to get more info
        try:
            results["oss_edition"] = arf_oss.OSS_EDITION
            results["oss_license"] = arf_oss.OSS_LICENSE
            results["execution_allowed"] = arf_oss.EXECUTION_ALLOWED
        except Exception as e:
            logger.debug(f"Could not get OSS details: {e}")
            
        results["badges"]["oss"] = {
            "text": f"βœ… ARF OSS v{results['oss_version']}", 
            "color": "#10b981", 
            "icon": "βœ…"
        }
        
        logger.info(f"βœ… ARF OSS v{results['oss_version']} detected")
        
    except ImportError as e:
        results["recommendations"].append(
            "Install real ARF OSS: `pip install agentic-reliability-framework==3.3.7`"
        )
        logger.info("⚠️ ARF OSS not installed - using mock mode")
    
    # Check Enterprise package
    try:
        import arf_enterprise
        results["enterprise_installed"] = True
        results["enterprise_version"] = getattr(arf_enterprise, '__version__', '1.0.2')
        results["badges"]["enterprise"] = {
            "text": f"πŸš€ Enterprise v{results['enterprise_version']}", 
            "color": "#8b5cf6", 
            "icon": "πŸš€"
        }
        logger.info(f"βœ… ARF Enterprise v{results['enterprise_version']} detected")
    except ImportError as e:
        results["recommendations"].append(
            "Install ARF Enterprise: `pip install agentic-reliability-enterprise` (requires license)"
        )
        logger.info("⚠️ ARF Enterprise not installed - using simulation")
    
    return results

# Global installation status cache
_installation_status = None

def get_installation_status():
    """Get cached installation status"""
    global _installation_status
    if _installation_status is None:
        _installation_status = check_arf_installation()
    return _installation_status

def get_installation_badges():
    """Get formatted badge HTML for UI"""
    installation = get_installation_status()
    oss_badge = installation["badges"]["oss"]
    enterprise_badge = installation["badges"]["enterprise"]
    
    # Add boundary context
    boundaries = BoundaryManager.get_system_boundaries()
    
    return f"""
    <div style="display: flex; justify-content: center; gap: 10px; margin-top: 10px; flex-wrap: wrap;">
        <span style="padding: 4px 12px; background: {oss_badge['color']}; 
                    color: white; border-radius: 20px; font-size: 12px; font-weight: bold; 
                    display: flex; align-items: center; gap: 6px;">
            {oss_badge['icon']} {oss_badge['text']}
        </span>
        <span style="padding: 4px 12px; background: {enterprise_badge['color']}; 
                    color: white; border-radius: 20px; font-size: 12px; font-weight: bold;
                    display: flex; align-items: center; gap: 6px;">
            {enterprise_badge['icon']} {enterprise_badge['text']}
        </span>
    </div>
    <div style="text-align: center; margin: 10px 0; font-size: 13px; color: #64748b;">
        Architecture: <strong>{boundaries['demo_mode']['architecture']}</strong> β€’ 
        Mode: <strong>{boundaries['demo_mode']['honesty_level']}</strong>
    </div>
    """

# ===========================================
# ASYNC UTILITIES - ENHANCED VERSION
# ===========================================
class AsyncRunner:
    """Enhanced async runner with better error handling"""
    
    @staticmethod
    def run_async(coro):
        """Run async coroutine in sync context"""
        try:
            loop = asyncio.get_event_loop()
        except RuntimeError:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
        
        try:
            return loop.run_until_complete(coro)
        except Exception as e:
            logger.error(f"Async execution failed: {e}")
            # Return error state instead of crashing
            return {"error": str(e), "status": "failed", "boundary_note": "Execution boundary reached"}
    
    @staticmethod
    def async_to_sync(async_func):
        """Decorator to convert async function to sync"""
        def wrapper(*args, **kwargs):
            try:
                return AsyncRunner.run_async(async_func(*args, **kwargs))
            except Exception as e:
                logger.error(f"Async to sync conversion failed: {e}")
                # Return a sensible fallback with boundary context
                return {"error": str(e), "status": "failed", "boundary_context": "OSS advisory only - execution requires Enterprise"}
        return wrapper

# ===========================================
# SIMPLE SETTINGS
# ===========================================
class Settings:
    """Simple settings class"""
    def __init__(self):
        self.arf_mode = "demo"
        self.use_true_arf = True  # Use true ARF integration
        self.default_scenario = "Cache Miss Storm"
        self.max_history_items = 100
        self.auto_refresh_seconds = 30
        self.show_boundaries = True  # NEW: Show clear boundaries
        self.architectural_honesty = True  # NEW: Be transparent about what's real vs simulated

settings = Settings()

# ===========================================
# RELIABLE VISUALIZATION HELPERS - ENHANCED WITH BOUNDARIES
# ===========================================
def create_simple_telemetry_plot(scenario_name: str, is_real_arf: bool = True):
    """Simple guaranteed-to-work telemetry plot with boundary indicators"""
    try:
        import plotly.graph_objects as go
        
        # Create telemetry data with anomaly
        time_points = list(range(0, 60, 5))
        normal_values = [100, 105, 98, 102, 101, 99, 103, 100, 105, 102, 100, 101]
        anomaly_values = [100, 105, 98, 102, 350, 420, 380, 410, 105, 102, 100, 101]
        
        fig = go.Figure()
        
        # Normal traffic
        fig.add_trace(go.Scatter(
            x=time_points,
            y=normal_values,
            mode='lines',
            name='Normal',
            line=dict(color='#3b82f6', width=2, dash='dot')
        ))
        
        # Anomaly
        fig.add_trace(go.Scatter(
            x=time_points,
            y=anomaly_values,
            mode='lines+markers',
            name='🚨 Anomaly',
            line=dict(color='#ef4444', width=3),
            marker=dict(size=8, color='#ef4444')
        ))
        
        # Highlight anomaly region
        fig.add_vrect(
            x0=20, x1=35,
            fillcolor="red", opacity=0.1,
            layer="below", line_width=0,
            annotation_text="Anomaly Detected",
            annotation_position="top left"
        )
        
        # Add boundary indicator in title
        boundary_text = "REAL ARF OSS" if is_real_arf else "DEMO SIMULATION"
        boundary_color = "#10b981" if is_real_arf else "#f59e0b"
        
        fig.update_layout(
            title=dict(
                text=f'πŸ“ˆ {scenario_name} - Live Telemetry<br>'
                     f'<span style="font-size: 12px; color: {boundary_color}">'
                     f'πŸ’Ž {boundary_text}</span>',
                font=dict(size=16, color='#1e293b')
            ),
            height=300,
            paper_bgcolor='white',
            plot_bgcolor='white',
            xaxis=dict(
                title='Time (minutes)',
                gridcolor='#e2e8f0',
                showgrid=True,
                color='#1e293b'
            ),
            yaxis=dict(
                title='Requests/sec',
                gridcolor='#e2e8f0',
                showgrid=True,
                color='#1e293b'
            ),
            legend=dict(
                yanchor="top",
                y=0.99,
                xanchor="left",
                x=0.01,
                bgcolor='rgba(255, 255, 255, 0.9)',
                bordercolor='#e2e8f0',
                borderwidth=1
            ),
            margin=dict(l=50, r=30, t=60, b=50)
        )
        
        return fig
    except Exception as e:
        logger.error(f"Error creating telemetry plot: {e}")
        # Fallback to HTML visualization
        return create_html_telemetry_fallback(scenario_name, is_real_arf)

def create_html_telemetry_fallback(scenario_name: str, is_real_arf: bool) -> str:
    """HTML fallback for telemetry visualization with boundary indicators"""
    boundary_color = "#10b981" if is_real_arf else "#f59e0b"
    boundary_text = "REAL ARF OSS" if is_real_arf else "DEMO SIMULATION"
    
    return f"""
    <div style="border: 2px solid {boundary_color}; border-radius: 16px; padding: 20px; 
               background: white; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
        
        <!-- Boundary indicator -->
        <div style="position: absolute; top: 15px; right: 15px; padding: 4px 10px; 
                   background: {boundary_color}; color: white; border-radius: 15px; 
                   font-size: 11px; font-weight: bold; display: flex; align-items: center; gap: 5px;">
            πŸ’Ž {boundary_text}
        </div>
        
        <h4 style="margin: 0 0 15px 0; color: #1e293b; font-size: 16px; font-weight: 600;">
            πŸ“ˆ {scenario_name} - Live Telemetry
        </h4>
        
        <!-- Simplified timeline -->
        <div style="position: relative; height: 100px; margin: 20px 0;">
            <!-- Background line -->
            <div style="position: absolute; left: 0; right: 0; top: 50%; 
                       height: 2px; background: #e2e8f0; transform: translateY(-50%);"></div>
            
            <!-- Normal range -->
            <div style="position: absolute; left: 10%; right: 40%; top: 50%; 
                       height: 6px; background: #10b981; transform: translateY(-50%); 
                       border-radius: 3px; opacity: 0.3;"></div>
            
            <!-- Anomaly point -->
            <div style="position: absolute; left: 70%; top: 50%; 
                       transform: translate(-50%, -50%);">
                <div style="width: 20px; height: 20px; border-radius: 50%; 
                           background: #ef4444; border: 3px solid white; 
                           box-shadow: 0 0 0 2px #ef4444;">
                </div>
                <div style="position: absolute; top: 25px; left: 50%; transform: translateX(-50%);
                           white-space: nowrap; font-size: 11px; color: #64748b;">
                    350% spike
                </div>
            </div>
            
            <!-- Labels -->
            <div style="position: absolute; left: 10%; top: 70px; font-size: 11px; color: #64748b;">
                Normal: 100%
            </div>
            <div style="position: absolute; left: 40%; top: 70px; font-size: 11px; color: #64748b;">
                Warning: 150%
            </div>
            <div style="position: absolute; left: 70%; top: 70px; font-size: 11px; 
                       color: #ef4444; font-weight: 500;">
                Anomaly: 350%
            </div>
        </div>
        
        <!-- Status indicator -->
        <div style="display: flex; justify-content: space-between; align-items: center; 
                   margin-top: 15px; padding: 10px; background: #f8fafc; border-radius: 8px;">
            <div>
                <div style="font-size: 12px; color: #64748b;">Status</div>
                <div style="font-size: 14px; color: #ef4444; font-weight: 600;">
                    🚨 Anomaly Detected
                </div>
            </div>
            <div style="text-align: right;">
                <div style="font-size: 12px; color: #64748b;">ARF Mode</div>
                <div style="font-size: 14px; color: {boundary_color}; font-weight: 600;">
                    {boundary_text}
                </div>
            </div>
        </div>
    </div>
    """

def create_simple_impact_plot(scenario_name: str, is_real_arf: bool = True):
    """Simple guaranteed-to-work impact plot with boundary indicators"""
    try:
        import plotly.graph_objects as go
        
        # Business impact metrics
        categories = ['Revenue Loss', 'Users Affected', 'SLA Violation', 'Recovery Time']
        values = [8500, 45000, 4.8, 45]  # Last one in minutes
        
        colors = ['#ef4444', '#f59e0b', '#8b5cf6', '#3b82f6']
        
        fig = go.Figure(data=[go.Bar(
            x=categories,
            y=values,
            marker_color=colors,
            text=[f'${values[0]:,}/hr', f'{values[1]:,}', f'{values[2]}%', f'{values[3]} min'],
            textposition='auto',
        )])
        
        # Add boundary indicator in title
        boundary_text = "REAL ARF OSS" if is_real_arf else "DEMO SIMULATION"
        boundary_color = "#10b981" if is_real_arf else "#f59e0b"
        
        fig.update_layout(
            title=dict(
                text=f'πŸ’° {scenario_name} - Business Impact<br>'
                     f'<span style="font-size: 12px; color: {boundary_color}">'
                     f'πŸ’Ž {boundary_text} Analysis</span>',
                font=dict(size=16, color='#1e293b')
            ),
            height=300,
            paper_bgcolor='white',
            plot_bgcolor='white',
            xaxis=dict(
                title='Impact Metric',
                gridcolor='#e2e8f0',
                showgrid=True,
                color='#1e293b',
                tickangle=-45
            ),
            yaxis=dict(
                title='Value',
                gridcolor='#e2e8f0',
                showgrid=True,
                color='#1e293b'
            ),
            margin=dict(l=50, r=30, t=60, b=80)
        )
        
        return fig
    except Exception as e:
        logger.error(f"Error creating impact plot: {e}")
        # Fallback to HTML visualization
        return create_html_impact_fallback(scenario_name, is_real_arf)

def create_html_impact_fallback(scenario_name: str, is_real_arf: bool) -> str:
    """HTML fallback for impact visualization"""
    boundary_color = "#10b981" if is_real_arf else "#f59e0b"
    boundary_text = "REAL ARF OSS" if is_real_arf else "DEMO SIMULATION"
    
    impact_map = {
        "Cache Miss Storm": {"revenue": 8500, "users": 45000, "recovery": 45},
        "Database Connection Pool Exhaustion": {"revenue": 4200, "users": 25000, "recovery": 35},
        "Kubernetes Memory Leak": {"revenue": 5500, "users": 35000, "recovery": 40},
        "API Rate Limit Storm": {"revenue": 3800, "users": 20000, "recovery": 25},
        "Network Partition": {"revenue": 12000, "users": 75000, "recovery": 60},
        "Storage I/O Saturation": {"revenue": 6800, "users": 30000, "recovery": 50}
    }
    
    impact = impact_map.get(scenario_name, {"revenue": 5000, "users": 30000, "recovery": 30})
    
    return f"""
    <div style="border: 2px solid {boundary_color}; border-radius: 16px; padding: 20px; 
               background: white; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
        
        <!-- Boundary indicator -->
        <div style="position: absolute; top: 15px; right: 15px; padding: 4px 10px; 
                   background: {boundary_color}; color: white; border-radius: 15px; 
                   font-size: 11px; font-weight: bold; display: flex; align-items: center; gap: 5px;">
            πŸ’Ž {boundary_text}
        </div>
        
        <h4 style="margin: 0 0 15px 0; color: #1e293b; font-size: 16px; font-weight: 600;">
            πŸ’° {scenario_name} - Business Impact
        </h4>
        
        <!-- Impact metrics -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 15px;">
            <div style="text-align: center; padding: 12px; background: #fef2f2; border-radius: 10px;">
                <div style="font-size: 12px; color: #64748b; margin-bottom: 5px;">Revenue Risk</div>
                <div style="font-size: 20px; font-weight: 700; color: #ef4444;">
                    ${impact['revenue']:,}/hr
                </div>
            </div>
            
            <div style="text-align: center; padding: 12px; background: #fef3c7; border-radius: 10px;">
                <div style="font-size: 12px; color: #64748b; margin-bottom: 5px;">Users Affected</div>
                <div style="font-size: 20px; font-weight: 700; color: #f59e0b;">
                    {impact['users']:,}
                </div>
            </div>
            
            <div style="text-align: center; padding: 12px; background: #f1f5f9; border-radius: 10px;">
                <div style="font-size: 12px; color: #64748b; margin-bottom: 5px;">Manual Recovery</div>
                <div style="font-size: 20px; font-weight: 700; color: #64748b;">
                    {impact['recovery']} min
                </div>
            </div>
            
            <div style="text-align: center; padding: 12px; background: #f0fdf4; border-radius: 10px;">
                <div style="font-size: 12px; color: #64748b; margin-bottom: 5px;">ARF Recovery</div>
                <div style="font-size: 20px; font-weight: 700; color: #10b981;">
                    {int(impact['recovery'] * 0.27)} min
                </div>
            </div>
        </div>
        
        <!-- Boundary note -->
        <div style="margin-top: 15px; padding: 10px; background: #f8fafc; border-radius: 8px;">
            <div style="font-size: 12px; color: #64748b; line-height: 1.5;">
                <strong>Analysis Mode:</strong> {boundary_text}<br>
                <strong>Confidence:</strong> 94% β€’ <strong>ROI Impact:</strong> 5.2Γ—
            </div>
        </div>
    </div>
    """

def create_empty_plot(title: str, is_real_arf: bool = True):
    """Create an empty placeholder plot with boundary indicators"""
    try:
        import plotly.graph_objects as go
        
        boundary_color = "#10b981" if is_real_arf else "#f59e0b"
        boundary_text = "REAL ARF OSS" if is_real_arf else "DEMO SIMULATION"
        
        # Create a simple line plot that WILL display
        fig = go.Figure()
        
        # Add sample data so it shows something
        fig.add_trace(go.Scatter(
            x=[1, 2, 3, 4, 5],
            y=[2, 3, 1, 4, 3],
            mode='lines+markers',
            name='Sample Data',
            line=dict(color='#3b82f6', width=2)
        ))
        
        fig.update_layout(
            height=300,
            title=dict(
                text=f'{title}<br>'
                     f'<span style="font-size: 12px; color: {boundary_color}">'
                     f'πŸ’Ž {boundary_text}</span>',
                font=dict(size=14, color='#1e293b'),
                x=0.5,
                xanchor='center'
            ),
            paper_bgcolor='white',
            plot_bgcolor='white',
            xaxis=dict(
                title='Time',
                gridcolor='#e2e8f0',
                showgrid=True,
                color='#1e293b'
            ),
            yaxis=dict(
                title='Value',
                gridcolor='#e2e8f0',
                showgrid=True,
                color='#1e293b'
            ),
            margin=dict(l=50, r=30, t=50, b=50),
            showlegend=True
        )
        
        return fig
    except ImportError:
        logger.warning("Plotly not available for plots")
        # Return HTML fallback
        return f"""
        <div style="border: 2px solid #e2e8f0; border-radius: 12px; padding: 20px; 
                   background: white; text-align: center; height: 300px; 
                   display: flex; flex-direction: column; justify-content: center;">
            <div style="font-size: 48px; margin-bottom: 15px;">πŸ“Š</div>
            <h4 style="margin: 0 0 10px 0; color: #1e293b; font-size: 16px;">
                {title}
            </h4>
            <div style="font-size: 14px; color: #64748b;">
                Visualization requires Plotly<br>
                Install with: <code>pip install plotly</code>
            </div>
        </div>
        """
    except Exception as e:
        logger.error(f"Error creating plot: {e}")
        return None

def get_inactive_agent_html(agent_name: str, description: str, is_real_arf: bool = False):
    """Get HTML for inactive agent state with boundary indicators"""
    icons = {
        "Detection": "πŸ•΅οΈβ€β™‚οΈ",
        "Recall": "🧠", 
        "Decision": "🎯"
    }
    
    border_color = "#e2e8f0"
    background = "#f8fafc"
    badge_text = "INACTIVE"
    
    if is_real_arf:
        border_color = "#10b981"
        background = "#f0fdf4"
        badge_text = "REAL ARF (INACTIVE)"
    
    return f"""
    <div style="border: 2px solid {border_color}; border-radius: 14px; padding: 18px; background: {background}; text-align: center; min-height: 180px; display: flex; flex-direction: column; align-items: center; justify-content: center; opacity: 0.7;">
        <div style="font-size: 32px; margin-bottom: 10px; opacity: 0.5;">{icons.get(agent_name, '⏳')}</div>
        <div style="width: 100%;">
            <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #94a3b8;">{agent_name} Agent</h4>
            <p style="font-size: 13px; color: #cbd5e1; margin-bottom: 12px; line-height: 1.4;">{description}</p>
            <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
                <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.5); border-radius: 6px; color: #cbd5e1; font-weight: 500;">Status: Inactive</span>
                <span style="font-size: 11px; padding: 3px 8px; background: rgba(255, 255, 255, 0.5); border-radius: 6px; color: #cbd5e1; font-weight: 500;">Mode: {badge_text}</span>
            </div>
            <div style="display: inline-block; padding: 5px 14px; background: #e2e8f0; border-radius: 20px; font-size: 12px; font-weight: bold; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px;">WAITING</div>
        </div>
    </div>
    """

# ===========================================
# IMPORT MODULAR COMPONENTS - ENHANCED WITH BOUNDARIES
# ===========================================
def import_components() -> Dict[str, Any]:
    """Safely import all components with proper error handling"""
    components = {
        "all_available": False,
        "error": None,
        "get_styles": lambda: "",  # Default empty styles
        "show_boundaries": settings.show_boundaries,  # Boundary flag
    }
    
    try:
        logger.info("Starting component import...")
        
        # First, import gradio (always available in Hugging Face Spaces)
        try:
            import gradio as gr
            components["gr"] = gr
            logger.info("βœ… Gradio imported successfully")
        except ImportError as e:
            logger.error(f"❌ Gradio not available: {e}")
            raise ImportError("Gradio is required but not available")
        
        # Import UI styles FIRST (to avoid circular dependencies)
        try:
            from ui.styles import get_styles
            components["get_styles"] = get_styles
            logger.info("βœ… UI styles imported successfully")
        except ImportError as e:
            logger.warning(f"⚠️ UI styles not available: {e}")
            # Use empty styles as fallback
            components["get_styles"] = lambda: ""
        
        # Import UI components
        try:
            from ui.components import (
                create_header, create_status_bar, create_tab1_incident_demo,
                create_tab2_business_roi, create_tab3_enterprise_features,
                create_tab4_audit_trail, create_tab5_learning_engine,
                create_footer
            )
            components.update({
                "create_header": create_header,
                "create_status_bar": create_status_bar,
                "create_tab1_incident_demo": create_tab1_incident_demo,
                "create_tab2_business_roi": create_tab2_business_roi,
                "create_tab3_enterprise_features": create_tab3_enterprise_features,
                "create_tab4_audit_trail": create_tab4_audit_trail,
                "create_tab5_learning_engine": create_tab5_learning_engine,
                "create_footer": create_footer,
            })
            logger.info("βœ… UI components imported successfully")
        except ImportError as e:
            logger.error(f"❌ UI components not available: {e}")
            # Create minimal UI fallbacks with boundary indicators
            gr = components["gr"]
            components.update({
                "create_header": lambda version="3.3.7", mock=False: gr.HTML(
                    f"""
                    <div style="text-align: center; padding: 20px;">
                        <h2 style="margin: 0 0 10px 0; color: #1e293b;">πŸš€ ARF v{version} Demo</h2>
                        <p style="color: #64748b; margin: 0;">Clear boundaries: OSS advises β†’ Enterprise executes</p>
                    </div>
                    """
                ),
                "create_status_bar": lambda: gr.HTML(BoundaryManager.get_boundary_badges()),
                "create_tab1_incident_demo": lambda *args: [gr.Dropdown()] * 24,
                "create_tab2_business_roi": lambda *args: [gr.Plot()] * 7,
                "create_tab3_enterprise_features": lambda: [gr.JSON()] * 8,
                "create_tab4_audit_trail": lambda: [gr.Button()] * 6,
                "create_tab5_learning_engine": lambda: [gr.Plot()] * 10,
                "create_footer": lambda: gr.HTML(
                    "<footer style='text-align: center; color: #64748b; padding: 20px;'>"
                    "ARF v3.3.7 β€’ Architecture: OSS advises β†’ Enterprise executes"
                    "</footer>"
                ),
            })
        
        # Try to import scenarios from demo module
        try:
            from demo.scenarios import INCIDENT_SCENARIOS
            components["INCIDENT_SCENARIOS"] = INCIDENT_SCENARIOS
            logger.info(f"βœ… Loaded {len(INCIDENT_SCENARIOS)} scenarios from demo module")
        except ImportError as e:
            logger.warning(f"⚠️ Demo scenarios not available: {e}")
            # Create minimal fallback scenarios with boundary context
            components["INCIDENT_SCENARIOS"] = {
                "Cache Miss Storm": {
                    "component": "Redis Cache Cluster",
                    "severity": "HIGH",
                    "impact_radius": "85% of users",
                    "business_impact": {"revenue_loss_per_hour": 8500},
                    "detection_time": "45 seconds",
                    "tags": ["cache", "redis", "latency"],
                    "metrics": {"affected_users": 45000},
                    "boundary_note": "OSS analysis only - execution requires Enterprise"
                }
            }
        
        # Try to import TrueARF337Orchestrator
        try:
            from core.true_arf_orchestrator import TrueARF337Orchestrator
            components["DemoOrchestrator"] = TrueARF337Orchestrator
            logger.info("βœ… Using TrueARF337Orchestrator with real v3.3.7 integration")
        except ImportError as e:
            logger.warning(f"⚠️ TrueARF337Orchestrator not available: {e}")
            # Fall back to real ARF integration
            try:
                from core.real_arf_integration import RealARFIntegration
                components["DemoOrchestrator"] = RealARFIntegration
                logger.info("βœ… Falling back to RealARFIntegration")
            except ImportError as e2:
                logger.warning(f"⚠️ RealARFIntegration also not available: {e2}")
                # Create a minimal mock orchestrator with boundary awareness
                class MockOrchestrator:
                    async def analyze_incident(self, scenario_name, scenario_data):
                        return {
                            "status": "mock",
                            "scenario": scenario_name,
                            "message": "Mock analysis (no real ARF available)",
                            "boundary_note": "OSS advisory mode - execution requires Enterprise",
                            "demo_display": {
                                "real_arf_version": "mock",
                                "true_oss_used": False,
                                "enterprise_simulated": True,
                                "architectural_boundary": "OSS advises β†’ Enterprise would execute"
                            }
                        }
                    async def execute_healing(self, scenario_name, mode="autonomous"):
                        return {
                            "status": "mock",
                            "scenario": scenario_name,
                            "message": "Mock execution (no real ARF available)",
                            "boundary_note": "Simulated Enterprise execution - real execution requires infrastructure",
                            "enterprise_features_used": ["simulated_execution", "mock_rollback", "demo_mode"]
                        }
                components["DemoOrchestrator"] = MockOrchestrator
                logger.info("⚠️ Using mock orchestrator with boundary awareness")
        
        # Try to import ROI calculator
        try:
            import importlib.util
            spec = importlib.util.find_spec("core.calculators")
            if spec is not None:
                from core.calculators import EnhancedROICalculator
                components["EnhancedROICalculator"] = EnhancedROICalculator()
                logger.info("βœ… EnhancedROICalculator imported successfully")
            else:
                raise ImportError("core.calculators module not found")
        except ImportError as e:
            logger.warning(f"⚠️ EnhancedROICalculator not available: {e}")
            class MockCalculator:
                def calculate_comprehensive_roi(self, **kwargs):
                    return {
                        "status": "βœ… Calculated Successfully",
                        "summary": {
                            "your_annual_impact": "$1,530,000",
                            "potential_savings": "$1,254,600",
                            "enterprise_cost": "$625,000",
                            "roi_multiplier": "5.2Γ—",
                            "payback_months": "6.0",
                            "annual_roi_percentage": "420%",
                            "boundary_context": "Based on OSS analysis + simulated Enterprise execution"
                        },
                        "boundary_note": "ROI calculation includes OSS advisory value and simulated Enterprise execution benefits"
                    }
            components["EnhancedROICalculator"] = MockCalculator()
            logger.info("⚠️ Using mock ROI calculator with boundary context")
        
        # Try to import visualization engine with boundary awareness
        try:
            spec = importlib.util.find_spec("core.visualizations")
            if spec is not None:
                from core.visualizations import EnhancedVisualizationEngine
                # Wrap the visualization engine to add boundary indicators
                class BoundaryAwareVisualizationEngine(EnhancedVisualizationEngine):
                    def create_executive_dashboard(self, data=None, is_real_arf=True):
                        result = super().create_executive_dashboard(data)
                        # Add boundary indicator if it's a Plotly figure
                        if hasattr(result, 'update_layout'):
                            boundary_color = "#10b981" if is_real_arf else "#f59e0b"
                            boundary_text = "REAL ARF OSS" if is_real_arf else "SIMULATED"
                            result.update_layout(
                                title=f"{result.layout.title.text}<br>"
                                      f"<span style='font-size: 12px; color: {boundary_color}'>"
                                      f"πŸ’Ž {boundary_text}</span>"
                            )
                        return result
                    
                    def create_telemetry_plot(self, scenario_name, anomaly_detected=True, is_real_arf=True):
                        return create_simple_telemetry_plot(scenario_name, is_real_arf)
                    
                    def create_impact_gauge(self, scenario_name, is_real_arf=True):
                        return create_simple_impact_plot(scenario_name, is_real_arf)
                    
                    def create_timeline_comparison(self, is_real_arf=True):
                        # Use the simple timeline from original app.py
                        try:
                            import plotly.graph_objects as go
                            
                            phases = ["Detection", "Analysis", "Decision", "Execution", "Recovery"]
                            manual_times = [300, 1800, 1200, 1800, 3600]  # seconds
                            arf_times = [45, 30, 60, 720, 0]
                            
                            # Convert to minutes for readability
                            manual_times_min = [t/60 for t in manual_times]
                            arf_times_min = [t/60 for t in arf_times]
                            
                            fig = go.Figure()
                            
                            boundary_color = "#10b981" if is_real_arf else "#f59e0b"
                            boundary_text = "REAL ARF" if is_real_arf else "SIMULATED"
                            
                            fig.add_trace(go.Bar(
                                name='Manual Process',
                                x=phases,
                                y=manual_times_min,
                                marker_color='#ef4444',
                                text=[f"{t:.0f}m" for t in manual_times_min],
                                textposition='auto'
                            ))
                            
                            fig.add_trace(go.Bar(
                                name=f'ARF Autonomous ({boundary_text})',
                                x=phases,
                                y=arf_times_min,
                                marker_color=boundary_color,
                                text=[f"{t:.0f}m" for t in arf_times_min],
                                textposition='auto'
                            ))
                            
                            total_manual = sum(manual_times_min)
                            total_arf = sum(arf_times_min)
                            
                            fig.update_layout(
                                title=f"⏰ Incident Timeline Comparison<br>"
                                     f"<span style='font-size: 14px; color: #6b7280'>"
                                     f"Total: {total_manual:.0f}m manual vs {total_arf:.0f}m ARF "
                                     f"({((total_manual - total_arf) / total_manual * 100):.0f}% faster)</span>",
                                barmode='group',
                                height=400,
                                plot_bgcolor='rgba(0,0,0,0)',
                                paper_bgcolor='rgba(0,0,0,0)',
                                legend=dict(
                                    orientation="h",
                                    yanchor="bottom",
                                    y=1.02,
                                    xanchor="right",
                                    x=1
                                ),
                                yaxis_title="Time (minutes)"
                            )
                            
                            return fig
                        except Exception as e:
                            logger.error(f"Timeline plot failed: {e}")
                            return create_empty_plot("Timeline Comparison", is_real_arf)
                
                components["EnhancedVisualizationEngine"] = BoundaryAwareVisualizationEngine()
                logger.info("βœ… EnhancedVisualizationEngine imported successfully with boundary awareness")
            else:
                raise ImportError("core.visualizations module not found")
        except ImportError as e:
            logger.warning(f"⚠️ EnhancedVisualizationEngine not available: {e}")
            class MockVisualizationEngine:
                def create_executive_dashboard(self, data=None, is_real_arf=True):
                    return create_empty_plot("Executive Dashboard", is_real_arf)
                
                def create_telemetry_plot(self, scenario_name, anomaly_detected=True, is_real_arf=True):
                    return create_simple_telemetry_plot(scenario_name, is_real_arf)
                
                def create_impact_gauge(self, scenario_name, is_real_arf=True):
                    return create_simple_impact_plot(scenario_name, is_real_arf)
                
                def create_timeline_comparison(self, is_real_arf=True):
                    return create_empty_plot("Timeline Comparison", is_real_arf)
            
            components["EnhancedVisualizationEngine"] = MockVisualizationEngine()
            logger.info("⚠️ Using mock visualization engine with boundary indicators")
        
        components["all_available"] = True
        components["error"] = None
        logger.info("βœ… Successfully imported all modular components with boundary awareness")
        
    except Exception as e:
        logger.error(f"❌ CRITICAL IMPORT ERROR: {e}")
        logger.error(traceback.format_exc())
        components["error"] = str(e)
        components["all_available"] = False
        
        # Ensure we have minimal components with boundary context
        if "gr" not in components:
            try:
                import gradio as gr
                components["gr"] = gr
            except:
                pass
        
        # Ensure we have scenarios with boundary notes
        if "INCIDENT_SCENARIOS" not in components:
            components["INCIDENT_SCENARIOS"] = {
                "Cache Miss Storm": {
                    "component": "Redis Cache Cluster",
                    "severity": "HIGH",
                    "business_impact": {"revenue_loss_per_hour": 8500},
                    "boundary_note": "OSS analysis only - execution requires Enterprise"
                }
            }
    
    return components

# ===========================================
# GLOBAL COMPONENTS - LAZY LOADED
# ===========================================
_components = None
_audit_manager = None

def get_components() -> Dict[str, Any]:
    """Lazy load components singleton"""
    global _components
    if _components is None:
        _components = import_components()
    return _components

# ===========================================
# AUDIT TRAIL MANAGER - ENHANCED WITH BOUNDARY INFO
# ===========================================
class AuditTrailManager:
    """Enhanced audit trail manager with boundary tracking"""
    
    def __init__(self):
        self.executions = []
        self.incidents = []
        self.boundary_crossings = []
        logger.info("AuditTrailManager initialized with boundary tracking")
    
    def add_execution(self, scenario: str, mode: str, success: bool = True, 
                     savings: float = 0, boundary_note: str = "") -> Dict:
        """Add execution to audit trail with boundary context"""
        entry = {
            "time": datetime.datetime.now().strftime("%H:%M"),
            "scenario": scenario,
            "mode": mode,
            "status": "βœ… Success" if success else "❌ Failed",
            "savings": f"${savings:,.0f}",
            "details": f"{mode} execution at {datetime.datetime.now().isoformat()}",
            "boundary_note": boundary_note or "OSS advisory β†’ Enterprise execution boundary"
        }
        self.executions.insert(0, entry)
        
        # Track boundary crossing
        if "Enterprise" in mode or "Autonomous" in mode:
            self.boundary_crossings.append({
                "time": datetime.datetime.now().isoformat(),
                "boundary": "OSS β†’ Enterprise",
                "scenario": scenario,
                "note": "Crossed from OSS advisory to Enterprise execution"
            })
        
        return entry
    
    def add_incident(self, scenario: str, severity: str = "HIGH", 
                    boundary_context: str = "") -> Dict:
        """Add incident to audit trail with boundary context"""
        entry = {
            "time": datetime.datetime.now().strftime("%H:%M"),
            "scenario": scenario,
            "severity": severity,
            "component": get_components()["INCIDENT_SCENARIOS"].get(scenario, {}).get("component", "unknown"),
            "status": "Analyzed",
            "boundary_context": boundary_context or "OSS advisory analysis only"
        }
        self.incidents.insert(0, entry)
        return entry
    
    def get_execution_table(self) -> List[List]:
        """Get execution table data with boundary notes"""
        return [
            [e["time"], e["scenario"], e["mode"], e["status"], e["savings"], 
             f"{e['details'][:30]}... {e.get('boundary_note', '')[:20]}..."]
            for e in self.executions[:10]
        ]
    
    def get_incident_table(self) -> List[List]:
        """Get incident table data with boundary context"""
        return [
            [e["time"], e["component"], e["scenario"], e["severity"], 
             f"{e['status']} ({e.get('boundary_context', 'OSS')})"]
            for e in self.incidents[:15]
        ]
    
    def get_boundary_report(self) -> Dict[str, Any]:
        """Get report on boundary crossings"""
        return {
            "total_crossings": len(self.boundary_crossings),
            "crossings": self.boundary_crossings[-5:],  # Last 5 crossings
            "summary": f"{len(self.boundary_crossings)} OSS→Enterprise boundary crossings tracked"
        }
    
    def clear(self) -> None:
        """Clear audit trail"""
        self.executions = []
        self.incidents = []
        self.boundary_crossings = []

def get_audit_manager() -> AuditTrailManager:
    """Lazy load audit manager singleton"""
    global _audit_manager
    if _audit_manager is None:
        _audit_manager = AuditTrailManager()
    return _audit_manager

# ===========================================
# HELPER FUNCTIONS - ENHANCED WITH BOUNDARY CONTEXT
# ===========================================
def get_scenario_impact(scenario_name: str) -> float:
    """Get average impact for a given scenario"""
    impact_map = {
        "Cache Miss Storm": 8500,
        "Database Connection Pool Exhaustion": 4200,
        "Kubernetes Memory Leak": 5500,
        "API Rate Limit Storm": 3800,
        "Network Partition": 12000,
        "Storage I/O Saturation": 6800
    }
    return impact_map.get(scenario_name, 5000)

def extract_roi_multiplier(roi_result: Dict) -> float:
    """Extract ROI multiplier from EnhancedROICalculator result"""
    try:
        # Try to get from summary
        if "summary" in roi_result and "roi_multiplier" in roi_result["summary"]:
            roi_str = roi_result["summary"]["roi_multiplier"]
            # Handle format like "5.2Γ—"
            if "Γ—" in roi_str:
                return float(roi_str.replace("Γ—", ""))
            return float(roi_str)
        
        # Try to get from scenarios
        if "scenarios" in roi_result and "base_case" in roi_result["scenarios"]:
            roi_str = roi_result["scenarios"]["base_case"]["roi"]
            if "Γ—" in roi_str:
                return float(roi_str.replace("Γ—", ""))
            return float(roi_str)
        
        # Try direct access
        if "roi_multiplier" in roi_result:
            roi_val = roi_result["roi_multiplier"]
            if isinstance(roi_val, (int, float)):
                return float(roi_val)
        
        return 5.2  # Default fallback
    except Exception as e:
        logger.warning(f"Failed to extract ROI multiplier: {e}, using default 5.2")
        return 5.2

# ===========================================
# VISUALIZATION HELPERS - USING SIMPLE PLOTS WITH BOUNDARIES
# ===========================================
def create_telemetry_plot(scenario_name: str, is_real_arf: bool = True):
    """Create a telemetry visualization for the selected scenario"""
    try:
        # Use our enhanced simple plot with boundary indicators
        return create_simple_telemetry_plot(scenario_name, is_real_arf)
    except Exception as e:
        logger.error(f"Failed to create telemetry plot: {e}")
        return create_simple_telemetry_plot(scenario_name, is_real_arf)

def create_impact_plot(scenario_name: str, is_real_arf: bool = True):
    """Create a business impact visualization"""
    try:
        # Use our enhanced simple plot with boundary indicators
        return create_simple_impact_plot(scenario_name, is_real_arf)
    except Exception as e:
        logger.error(f"Failed to create impact plot: {e}")
        return create_simple_impact_plot(scenario_name, is_real_arf)

def create_timeline_plot(scenario_name: str, is_real_arf: bool = True):
    """Create an incident timeline visualization"""
    try:
        # Use simple timeline from original app.py
        import plotly.graph_objects as go
        
        # Timeline events
        events = ['Incident Start', 'ARF Detection', 'Analysis', 'Resolution']
        times = [0, 0.75, 2.5, 12]  # minutes
        colors = ['#ef4444', '#f59e0b', '#3b82f6', '#10b981']
        icons = ['🚨', 'πŸ•΅οΈβ€β™‚οΈ', '🧠', 'βœ…']
        
        fig = go.Figure()
        
        # Add events as markers
        for i, (event, time, color, icon) in enumerate(zip(events, times, colors, icons)):
            fig.add_trace(go.Scatter(
                x=[time],
                y=[1],
                mode='markers+text',
                marker=dict(size=20, color=color, symbol='circle'),
                text=[f'{icon}<br>{event}<br>{time} min'],
                textposition='top center',
                name=event,
                hoverinfo='text',
                showlegend=False
            ))
        
        # Add connecting line
        fig.add_trace(go.Scatter(
            x=times,
            y=[1, 1, 1, 1],
            mode='lines',
            line=dict(color='#64748b', width=2, dash='dash'),
            showlegend=False
        ))
        
        # Add boundary indicator in title
        boundary_text = "REAL ARF OSS" if is_real_arf else "DEMO SIMULATION"
        boundary_color = "#10b981" if is_real_arf else "#f59e0b"
        
        fig.update_layout(
            title=dict(
                text=f'⏰ {scenario_name} - Incident Timeline<br>'
                     f'<span style="font-size: 12px; color: {boundary_color}">'
                     f'πŸ’Ž {boundary_text}</span>',
                font=dict(size=16, color='#1e293b')
            ),
            height=300,
            paper_bgcolor='white',
            plot_bgcolor='white',
            xaxis=dict(
                title='Time (minutes)',
                range=[-1, max(times) + 2],
                gridcolor='#e2e8f0',
                showgrid=True,
                color='#1e293b'
            ),
            yaxis=dict(
                showticklabels=False,
                range=[0.8, 1.2],
                color='#1e293b'
            ),
            showlegend=False,
            margin=dict(l=50, r=30, t=60, b=50)
        )
        
        return fig
    except Exception as e:
        logger.error(f"Failed to create timeline plot: {e}")
        return create_empty_plot(f'Timeline: {scenario_name}', is_real_arf)

# ===========================================
# SCENARIO UPDATE HANDLER - ENHANCED WITH BOUNDARIES
# ===========================================
def update_scenario_display(scenario_name: str) -> tuple:
    """Update all scenario-related displays with scenario-specific data"""
    scenario = get_components()["INCIDENT_SCENARIOS"].get(scenario_name, {})
    impact = scenario.get("business_impact", {})
    metrics = scenario.get("metrics", {})
    
    # Get boundary context
    boundaries = BoundaryManager.get_system_boundaries()
    oss_label = boundaries["oss"]["label"]
    enterprise_label = boundaries["enterprise"]["label"]
    
    # Create scenario card HTML with boundary context
    scenario_html = f"""
    <div style="border: 1px solid #e2e8f0; border-radius: 14px; padding: 20px; background: white; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #f1f5f9;">
            <h3 style="margin: 0; font-size: 18px; color: #1e293b;">🚨 {scenario_name}</h3>
            <span style="padding: 4px 12px; background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-transform: uppercase; letter-spacing: 0.5px;">{scenario.get('severity', 'HIGH')}</span>
        </div>
        <div style="margin-top: 15px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; padding: 4px 0;">
                <span style="font-size: 13px; color: #64748b; font-weight: 500;">Component:</span>
                <span style="font-size: 14px; color: #1e293b; font-weight: 600;">{scenario.get('component', 'Unknown').replace('_', ' ').title()}</span>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; padding: 4px 0;">
                <span style="font-size: 13px; color: #64748b; font-weight: 500;">Affected Users:</span>
                <span style="font-size: 14px; color: #1e293b; font-weight: 600;">{metrics.get('affected_users', 'Unknown') if 'affected_users' in metrics else 'Unknown'}</span>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; padding: 4px 0;">
                <span style="font-size: 13px; color: #64748b; font-weight: 500;">Revenue Risk:</span>
                <span style="font-size: 14px; color: #ef4444; font-weight: 700;">${impact.get('revenue_loss_per_hour', 0):,}/hour</span>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; padding: 4px 0;">
                <span style="font-size: 13px; color: #64748b; font-weight: 500;">Detection Time:</span>
                <span style="font-size: 14px; color: #1e293b; font-weight: 600;">45 seconds (ARF AI)</span>
            </div>
            <div style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 15px; padding-top: 12px; border-top: 1px solid #f1f5f9;">
                <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">{scenario.get('component', 'unknown').split('_')[0] if '_' in scenario.get('component', '') else scenario.get('component', 'unknown')}</span>
                <span style="padding: 3px 8px; background: #f1f5f9; border-radius: 6px; font-size: 11px; color: #475569; font-weight: 500;">{scenario.get('severity', 'high').lower()}</span>
                <span style="padding: 3px 8px; background: #10b981; color: white; border-radius: 6px; font-size: 11px; font-weight: 500;">{oss_label.split(' ')[-1]}</span>
                <span style="padding: 3px 8px; background: #f59e0b; color: white; border-radius: 6px; font-size: 11px; font-weight: 500;">{enterprise_label.split(' ')[-1]}</span>
            </div>
            <div style="margin-top: 10px; padding: 8px; background: #f8fafc; border-radius: 8px; border-left: 3px solid #3b82f6;">
                <div style="font-size: 11px; color: #64748b; line-height: 1.4;">
                    <strong>Architecture:</strong> {oss_label} advises β†’ {enterprise_label} would execute
                </div>
            </div>
        </div>
    </div>
    """
    
    # Create visualizations with boundary context
    is_real_arf = boundaries["oss"]["available"]
    telemetry_plot = create_simple_telemetry_plot(scenario_name, is_real_arf)
    impact_plot = create_simple_impact_plot(scenario_name, is_real_arf)
    timeline_plot = create_timeline_plot(scenario_name, is_real_arf)
    
    return (
        scenario_html,
        telemetry_plot,
        impact_plot,
        timeline_plot
    )

# ===========================================
# TRUE ARF ANALYSIS HANDLER - ENHANCED WITH BOUNDARY AWARENESS
# ===========================================
@AsyncRunner.async_to_sync
async def run_true_arf_analysis(scenario_name: str):
    """Run true ARF v3.3.7 analysis with OSS + Enterprise simulation"""
    try:
        logger.info(f"Running TRUE ARF analysis for: {scenario_name}")
        
        scenario = get_components()["INCIDENT_SCENARIOS"].get(scenario_name, {})
        
        if not scenario:
            raise ValueError(f"Scenario '{scenario_name}' not found")
        
        # Check installation status and boundaries
        installation = get_installation_status()
        real_arf_available = installation["oss_installed"]
        boundaries = BoundaryManager.get_system_boundaries()
        
        # Use TrueARF337Orchestrator if available
        orchestrator = get_components()["DemoOrchestrator"]()
        analysis = await orchestrator.analyze_incident(scenario_name, scenario)
        
        # Check for errors
        if analysis.get("status") == "error":
            error_msg = analysis.get("message", "Unknown error")
            raise ValueError(f"Analysis failed: {error_msg}")
        
        # Add to audit trail with boundary context
        get_audit_manager().add_incident(
            scenario_name, 
            scenario.get("severity", "HIGH"),
            boundary_context=f"OSS analysis via {boundaries['oss']['label']}"
        )
        
        # Update incident table
        incident_table_data = get_audit_manager().get_incident_table()
        
        # Extract values from analysis
        demo_display = analysis.get("demo_display", {})
        real_arf_version = demo_display.get("real_arf_version", "mock")
        true_oss_used = analysis.get("true_oss_used", False)
        enterprise_simulated = analysis.get("enterprise_simulated", False)
        
        # Get analysis data based on mode
        if true_oss_used:
            oss_analysis = analysis.get("oss_analysis", {})
            analysis_data = oss_analysis.get("analysis", {})
            
            detection_result = analysis_data.get("detection", {})
            detection_confidence = detection_result.get("confidence", 0.987)
            detection_time_seconds = detection_result.get("detection_time_ms", 45000) / 1000
            
            similar_incidents = analysis_data.get("recall", [])
            similar_count = len(similar_incidents)
            
            decision_data = analysis_data.get("decision", {})
            decision_confidence = decision_data.get("confidence", 0.94)
            success_rate = decision_data.get("historical_success_rate", 0.87)
            
            # Check for enterprise enhancements
            enterprise_enhancements = analysis.get("enterprise_enhancements", {})
            novel_execution = enterprise_enhancements is not None and enterprise_enhancements.get("enterprise_available", False)
            
            if enterprise_enhancements:
                enhancements = enterprise_enhancements.get("enhancements", {})
                rollback_guarantee = enhancements.get("rollback_guarantees", {}).get("guarantee", "N/A")
            else:
                rollback_guarantee = "N/A"
            
            oss_results = {
                "status": "βœ… TRUE ARF OSS Analysis Complete",
                "arf_version": "3.3.7",
                "edition": "OSS (Apache 2.0)",
                "license": "Apache 2.0",
                "scenario": scenario_name,
                "confidence": decision_confidence,
                "novel_execution": novel_execution,
                "rollback_guarantee": rollback_guarantee,
                "agents_executed": ["Detection", "Recall", "Decision"],
                "boundary_context": f"Analysis via {boundaries['oss']['label']}",
                "execution_boundary": f"Execution requires {boundaries['enterprise']['label']}",
                "findings": [
                    f"Anomaly detected with {detection_confidence:.1%} confidence",
                    f"{similar_count} similar incidents found in RAG memory",
                    f"Historical success rate for similar actions: {success_rate:.1%}",
                    f"True ARF OSS package used: βœ… Yes",
                    f"Enterprise features available: {'βœ… Simulated' if enterprise_simulated else '❌ Not installed'}",
                    f"Architectural boundary: OSS advises β†’ Enterprise executes"
                ],
                "recommendations": [
                    "Scale resources based on historical patterns",
                    "Implement circuit breaker pattern",
                    "Add enhanced monitoring for key metrics",
                    f"Rollback guarantee: {rollback_guarantee}",
                    "Upgrade to Enterprise for autonomous execution"
                ],
                "healing_intent": decision_data,
                "architectural_note": "This is the OSS advisory boundary. Execution requires Enterprise edition."
            }
        else:
            # Mock fallback
            detection_result = analysis.get("detection", {})
            detection_confidence = detection_result.get("confidence", 0.987)
            detection_time_seconds = detection_result.get("detection_time_seconds", 45)
            
            similar_incidents = analysis.get("recall", [])
            similar_count = len(similar_incidents)
            
            decision_confidence = analysis.get("confidence", 0.94)
            healing_intent = analysis.get("decision", {})
            success_rate = healing_intent.get("success_rate", 0.87)
            
            oss_results = {
                "status": "⚠️ Enhanced Mock Analysis",
                "arf_version": "mock",
                "scenario": scenario_name,
                "confidence": decision_confidence,
                "agents_executed": ["Detection", "Recall", "Decision"],
                "boundary_context": "Mock analysis - real ARF OSS not installed",
                "execution_boundary": "Execution requires Enterprise edition",
                "findings": [
                    f"Anomaly detected with {detection_confidence:.1%} confidence",
                    f"{similar_count} similar incidents found in RAG memory",
                    f"Historical success rate for similar actions: {success_rate:.1%}",
                    f"Detection time: {detection_time_seconds} seconds",
                    f"Install agentic-reliability-framework==3.3.7 for true OSS analysis",
                    f"Architectural boundary: OSS advises β†’ Enterprise executes"
                ],
                "recommendations": [
                    "Scale resources based on historical patterns",
                    "Implement circuit breaker pattern",
                    "Add enhanced monitoring for key metrics",
                    "Install true ARF OSS package for production use",
                    "Upgrade to Enterprise for autonomous execution"
                ],
                "healing_intent": healing_intent,
                "install_command": "pip install agentic-reliability-framework==3.3.7",
                "architectural_note": "Mock mode demonstrates the architecture. Real OSS provides advisory intelligence."
            }
        
        # Create agent HTML with clear boundary indicators using BoundaryManager
        detection_html = BoundaryManager.create_agent_with_boundary(
            agent_name="Detection",
            status=f"Anomaly detected: <strong>{detection_confidence:.1%} confidence</strong>",
            is_real_arf=true_oss_used,
            confidence=detection_confidence
        )
        
        recall_html = BoundaryManager.create_agent_with_boundary(
            agent_name="Recall",
            status=f"<strong>{similar_count} similar incidents</strong> found in RAG memory",
            is_real_arf=true_oss_used,
            confidence=0.92  # Default recall confidence
        )
        
        decision_html = BoundaryManager.create_agent_with_boundary(
            agent_name="Decision",
            status=f"Generating healing intent with <strong>{decision_confidence:.1%} confidence</strong>",
            is_real_arf=true_oss_used,
            confidence=decision_confidence
        )
        
        logger.info(f"Analysis completed successfully for {scenario_name} (True ARF: {real_arf_version})")
        return (
            detection_html, recall_html, decision_html,
            oss_results, incident_table_data
        )
        
    except Exception as e:
        logger.error(f"Analysis failed: {e}", exc_info=True)
        
        # Return error state with boundary context
        boundaries = BoundaryManager.get_system_boundaries()
        
        error_html = BoundaryManager.create_agent_with_boundary(
            agent_name="Error",
            status=f"Analysis failed: {str(e)[:80]}...",
            is_real_arf=False,
            confidence=0.0
        )
        
        error_results = {
            "status": "❌ Analysis Failed",
            "error": str(e),
            "scenario": scenario_name,
            "boundary_context": f"OSS advisory via {boundaries['oss']['label']}",
            "suggestion": "Check logs and try again. Ensure ARF OSS is installed for real analysis."
        }
        
        return (
            error_html, error_html, error_html,
            error_results, []
        )

# ===========================================
# ENTERPRISE EXECUTION HANDLER - ENHANCED WITH BOUNDARY CLARITY
# ===========================================
def execute_enterprise_healing(scenario_name, approval_required, mcp_mode_value):
    """Execute enterprise healing with clear boundary indicators"""
    import gradio as gr
    
    scenario = get_components()["INCIDENT_SCENARIOS"].get(scenario_name, {})
    boundaries = BoundaryManager.get_system_boundaries()
    
    # Determine mode
    mode = "Approval" if approval_required else "Autonomous"
    
    # OSS can't execute in any mode - only advisory
    if "Advisory" in mcp_mode_value or boundaries["oss"]["available"] and not boundaries["enterprise"]["available"]:
        # Show clear OSS boundary
        approval_html = BoundaryManager.create_boundary_indicator(
            "Scale Redis cluster from 3 to 5 nodes",
            is_simulated=True
        )
        
        enterprise_results = {
            "status": "❌ OSS Boundary Reached",
            "error": f"{boundaries['oss']['label']} is advisory-only. Cannot execute in Advisory mode.",
            "requires_enterprise": True,
            "enterprise_features_required": [
                "autonomous_execution",
                "novel_execution_protocols", 
                "rollback_guarantees",
                "deterministic_confidence",
                "enterprise_mcp_server"
            ],
            "boundary_note": f"Architectural boundary: {boundaries['oss']['label']} advises β†’ {boundaries['enterprise']['label']} executes",
            "contact": "sales@arf.dev"
        }
        execution_table_data = get_audit_manager().get_execution_table()
        return gr.HTML.update(value=approval_html), enterprise_results, execution_table_data
    
    # Calculate savings based on scenario
    impact = scenario.get("business_impact", {})
    revenue_loss = impact.get("revenue_loss_per_hour", get_scenario_impact(scenario_name))
    savings = int(revenue_loss * 0.85)
    
    # Add to audit trail with boundary context
    get_audit_manager().add_execution(
        scenario_name, mode, savings=savings,
        boundary_note=f"Crossed OSS→Enterprise boundary via {boundaries['enterprise']['label']}"
    )
    
    # Get orchestrator for execution simulation
    orchestrator = get_components()["DemoOrchestrator"]()
    
    # Create approval display with boundary clarity
    if approval_required:
        approval_html = f"""
        <div style="border: 2px solid #e2e8f0; border-radius: 14px; padding: 20px; background: white; margin-top: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #f1f5f9;">
                <h4 style="margin: 0; font-size: 16px; color: #1e293b;">πŸ‘€ Enterprise Approval Required</h4>
                <span style="padding: 4px 12px; background: #f59e0b; color: white; border-radius: 8px; font-size: 12px; font-weight: bold; text-transform: uppercase;">ENTERPRISE</span>
            </div>
            <div style="margin-top: 15px;">
                <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Scenario:</strong> {scenario_name}</p>
                <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Mode:</strong> Enterprise Approval</p>
                <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Action:</strong> Scale Redis cluster from 3 to 5 nodes</p>
                <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Estimated Savings:</strong> <span style="color: #10b981; font-weight: 700;">${savings:,}</span></p>
                
                <!-- Boundary progression -->
                <div style="display: flex; flex-direction: column; gap: 10px; margin-top: 20px;">
                    <div style="padding: 12px; background: #f0fdf4; border-radius: 10px; border-left: 4px solid #10b981; font-size: 14px; color: #475569; font-weight: 500;">
                        βœ… 1. OSS Analysis Complete ({boundaries['oss']['label']})
                    </div>
                    <div style="padding: 12px; background: #fef3c7; border-radius: 10px; border-left: 4px solid #f59e0b; font-size: 14px; color: #475569; font-weight: 500;">
                        ⏳ 2. Awaiting human review ({boundaries['enterprise']['label']})
                    </div>
                    <div style="padding: 12px; background: #f1f5f9; border-radius: 10px; border-left: 4px solid #3b82f6; font-size: 14px; color: #475569; font-weight: 500;">
                        3. {boundaries['enterprise']['label']} will execute upon approval
                    </div>
                </div>
                
                <div style="margin-top: 15px; padding: 10px; background: #f0fdf4; border-radius: 8px; border-left: 4px solid #10b981;">
                    <p style="margin: 0; font-size: 13px; color: #475569;">
                        <strong>Architecture:</strong> {boundaries['oss']['label']} β†’ {boundaries['enterprise']['label']}<br>
                        <strong>Boundary:</strong> Advisory analysis β†’ Approval workflow β†’ Execution
                    </p>
                </div>
            </div>
        </div>
        """
        
        enterprise_results = {
            "status": "⏳ Awaiting Approval",
            "execution_mode": mode,
            "scenario": scenario_name,
            "timestamp": datetime.datetime.now().isoformat(),
            "enterprise": True,
            "boundary_progression": [
                f"OSS advisory complete ({boundaries['oss']['label']})",
                f"Enterprise approval pending ({boundaries['enterprise']['label']})",
                "Execution queued upon approval"
            ],
            "actions_queued": [
                "Scale resources based on ML recommendations",
                "Implement circuit breaker pattern", 
                "Deploy enhanced monitoring",
                "Update RAG memory with outcome"
            ],
            "business_impact": {
                "estimated_recovery_time": "12 minutes",
                "manual_comparison": "45 minutes",
                "estimated_cost_saved": f"${savings:,}",
                "users_protected": "45,000 β†’ 0",
                "mttr_reduction": "73% faster"
            },
            "safety_checks": {
                "blast_radius": "2 services (within limit)",
                "business_hours": "Compliant",
                "action_type": "Pending approval",
                "circuit_breaker": "Will activate"
            },
            "enterprise_features": [
                "approval_workflows",
                "audit_trail",
                "compliance_reporting",
                "enhanced_safety"
            ],
            "architectural_note": f"Clear boundary: {boundaries['oss']['label']} advises β†’ {boundaries['enterprise']['label']} executes with approval"
        }
    else:
        # Try to execute with true ARF simulation
        try:
            # Simulate Enterprise autonomous execution
            execution_result = AsyncRunner.run_async(
                orchestrator.execute_healing(scenario_name, "autonomous")
            )
            
            if execution_result.get("status") in ["executed", "success"]:
                approval_html = f"""
                <div style="border: 2px solid #e2e8f0; border-radius: 14px; padding: 20px; background: white; margin-top: 20px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #f1f5f9;">
                        <h4 style="margin: 0; font-size: 16px; color: #1e293b;">⚑ Enterprise Autonomous Execution</h4>
                        <span style="padding: 4px 12px; background: #10b981; color: white; border-radius: 8px; font-size: 12px; font-weight: bold; text-transform: uppercase;">ENTERPRISE+</span>
                    </div>
                    <div style="margin-top: 15px;">
                        <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Scenario:</strong> {scenario_name}</p>
                        <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Mode:</strong> Enterprise Autonomous</p>
                        <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Action Executed:</strong> Scaled Redis cluster from 3 to 5 nodes</p>
                        <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Recovery Time:</strong> 12 minutes (vs 45 min manual)</p>
                        <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Cost Saved:</strong> <span style="color: #10b981; font-weight: 700;">${savings:,}</span></p>
                        
                        <!-- Boundary progression -->
                        <div style="display: flex; flex-direction: column; gap: 10px; margin-top: 20px;">
                            <div style="padding: 12px; background: #f0fdf4; border-radius: 10px; border-left: 4px solid #10b981; font-size: 14px; color: #475569; font-weight: 500;">
                                βœ… 1. {boundaries['oss']['label']} generated intent
                            </div>
                            <div style="padding: 12px; background: #f0fdf4; border-radius: 10px; border-left: 4px solid #10b981; font-size: 14px; color: #475569; font-weight: 500;">
                                βœ… 2. Safety checks passed ({boundaries['enterprise']['label']})
                            </div>
                            <div style="padding: 12px; background: #f0fdf4; border-radius: 10px; border-left: 4px solid #10b981; font-size: 14px; color: #475569; font-weight: 500;">
                                βœ… 3. Autonomous execution completed ({boundaries['enterprise']['label']}+)
                            </div>
                        </div>
                        
                        <div style="margin-top: 15px; padding: 10px; background: #f0fdf4; border-radius: 8px; border-left: 4px solid #10b981;">
                            <p style="margin: 0; font-size: 13px; color: #475569;">
                                <strong>Architecture Executed:</strong> {boundaries['oss']['label']} β†’ {boundaries['enterprise']['label']}<br>
                                <strong>Boundary Crossed:</strong> Advisory β†’ Autonomous execution
                            </p>
                        </div>
                    </div>
                </div>
                """
                
                enterprise_results = {
                    "status": "βœ… Enterprise Execution Successful",
                    "execution_mode": mode,
                    "scenario": scenario_name,
                    "timestamp": datetime.datetime.now().isoformat(),
                    "enterprise": True,
                    "boundary_crossed": f"OSS β†’ {boundaries['enterprise']['label']}",
                    "actions_executed": [
                        "βœ… Scaled resources based on ML recommendations",
                        "βœ… Implemented circuit breaker pattern",
                        "βœ… Deployed enhanced monitoring", 
                        "βœ… Updated RAG memory with outcome"
                    ],
                    "business_impact": {
                        "recovery_time": "60 min β†’ 12 min",
                        "cost_saved": f"${savings:,}",
                        "users_impacted": "45,000 β†’ 0",
                        "mttr_reduction": "73% faster"
                    },
                    "safety_checks": {
                        "blast_radius": "2 services (within limit)",
                        "business_hours": "Compliant",
                        "action_type": "Approved",
                        "circuit_breaker": "Active"
                    },
                    "enterprise_features_used": execution_result.get("enterprise_features_used", [
                        "deterministic_confidence",
                        "novel_execution_protocols",
                        "rollback_guarantees",
                        "business_aware_execution"
                    ]),
                    "architectural_result": f"Successfully crossed OSS→Enterprise boundary: {boundaries['oss']['label']} advised → {boundaries['enterprise']['label']} executed"
                }
            else:
                # Execution failed
                approval_html = f"""
                <div style="border: 2px solid #ef4444; border-radius: 14px; padding: 20px; background: #fef2f2; margin-top: 20px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #fecaca;">
                        <h4 style="margin: 0; font-size: 16px; color: #1e293b;">❌ Enterprise Execution Failed</h4>
                        <span style="padding: 4px 12px; background: #ef4444; color: white; border-radius: 8px; font-size: 12px; font-weight: bold; text-transform: uppercase;">FAILED</span>
                    </div>
                    <div style="margin-top: 15px;">
                        <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Scenario:</strong> {scenario_name}</p>
                        <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Error:</strong> {execution_result.get('message', 'Unknown error')}</p>
                        <p style="margin-top: 10px; color: #64748b; font-size: 14px;">
                            <strong>Boundary Context:</strong> This is a simulation. Real {boundaries['enterprise']['label']} execution requires infrastructure access.
                        </p>
                    </div>
                </div>
                """
                
                enterprise_results = {
                    "status": "❌ Enterprise Execution Failed",
                    "execution_mode": mode,
                    "scenario": scenario_name,
                    "timestamp": datetime.datetime.now().isoformat(),
                    "error": execution_result.get("message", "Unknown error"),
                    "simulation": True,
                    "requires_real_enterprise": True,
                    "boundary_context": f"Simulated execution of {boundaries['enterprise']['label']} - real execution requires production infrastructure",
                    "suggestion": f"Install arf_enterprise package for real {boundaries['enterprise']['label']} execution"
                }
                
        except Exception as e:
            logger.error(f"Execution failed: {e}")
            approval_html = f"""
            <div style="border: 2px solid #ef4444; border-radius: 14px; padding: 20px; background: #fef2f2; margin-top: 20px;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #fecaca;">
                    <h4 style="margin: 0; font-size: 16px; color: #1e293b;">❌ Execution Error</h4>
                    <span style="padding: 4px 12px; background: #ef4444; color: white; border-radius: 8px; font-size: 12px; font-weight: bold; text-transform: uppercase;">ERROR</span>
                </div>
                <div style="margin-top: 15px;">
                    <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Scenario:</strong> {scenario_name}</p>
                    <p style="margin: 8px 0; font-size: 14px; color: #475569;"><strong>Error:</strong> {str(e)}</p>
                    <p style="margin-top: 10px; color: #64748b; font-size: 14px;">
                        <strong>Boundary Context:</strong> Failed at OSS→Enterprise boundary. Real execution requires {boundaries['enterprise']['label']} license.
                    </p>
                </div>
            </div>
            """
            
            enterprise_results = {
                "status": "❌ Execution Error",
                "execution_mode": mode,
                "scenario": scenario_name,
                "timestamp": datetime.datetime.now().isoformat(),
                "error": str(e),
                "simulation": True,
                "requires_enterprise": True,
                "boundary_context": f"Failed crossing OSS→{boundaries['enterprise']['label']} boundary",
                "suggestion": f"Contact sales@arf.dev for {boundaries['enterprise']['label']} trial"
            }
    
    # Update execution table
    execution_table_data = get_audit_manager().get_execution_table()
    
    return gr.HTML.update(value=approval_html), enterprise_results, execution_table_data

# ===========================================
# ROI CALCULATION FUNCTION - ENHANCED WITH BOUNDARY CONTEXT
# ===========================================
def calculate_roi(scenario_name, monthly_incidents, team_size):
    """Calculate ROI with boundary context"""
    try:
        logger.info(f"Calculating ROI for {scenario_name}")
        
        # Validate inputs
        monthly_incidents = int(monthly_incidents) if monthly_incidents else 15
        team_size = int(team_size) if team_size else 5
        
        # Get scenario-specific impact
        avg_impact = get_scenario_impact(scenario_name)
        
        # Get boundary context
        boundaries = BoundaryManager.get_system_boundaries()
        
        # Calculate ROI
        roi_calculator = get_components()["EnhancedROICalculator"]
        roi_result = roi_calculator.calculate_comprehensive_roi(
            monthly_incidents=monthly_incidents,
            avg_impact=float(avg_impact),
            team_size=team_size
        )
        
        # Extract ROI multiplier for visualization
        roi_multiplier = extract_roi_multiplier(roi_result)
        
        # Add boundary context to ROI result
        if "summary" in roi_result:
            roi_result["summary"]["boundary_context"] = (
                f"Based on {boundaries['oss']['label']} analysis + "
                f"{boundaries['enterprise']['label']} simulated execution"
            )
            roi_result["summary"]["architecture"] = "OSS advises β†’ Enterprise executes"
        
        # Create visualization with boundary context
        viz_engine = get_components()["EnhancedVisualizationEngine"]
        is_real_arf = boundaries["oss"]["available"]
        chart = viz_engine.create_executive_dashboard(
            {"roi_multiplier": roi_multiplier}, 
            is_real_arf=is_real_arf
        )
        
        return roi_result, chart
        
    except Exception as e:
        logger.error(f"ROI calculation error: {e}")
        
        # Get boundary context for fallback
        boundaries = BoundaryManager.get_system_boundaries()
        
        # Provide fallback results with boundary context
        fallback_result = {
            "status": "βœ… Calculated Successfully",
            "summary": {
                "your_annual_impact": "$1,530,000",
                "potential_savings": "$1,254,600",
                "enterprise_cost": "$625,000",
                "roi_multiplier": "5.2Γ—",
                "payback_months": "6.0",
                "annual_roi_percentage": "420%",
                "boundary_context": f"Based on {boundaries['oss']['label']} + {boundaries['enterprise']['label']} simulation",
                "architecture": "OSS advises β†’ Enterprise executes"
            },
            "note": "Using demo calculation - real ROI varies by organization"
        }
        
        # Always return a valid chart with boundary context
        viz_engine = get_components()["EnhancedVisualizationEngine"]
        is_real_arf = boundaries["oss"]["available"]
        fallback_chart = viz_engine.create_executive_dashboard(
            {"roi_multiplier": 5.2}, 
            is_real_arf=is_real_arf
        )
        
        return fallback_result, fallback_chart

# ===========================================
# CREATE DEMO INTERFACE - ENHANCED WITH BOUNDARY AWARENESS
# ===========================================
def create_demo_interface():
    """Create demo interface using modular components with boundary awareness"""
    
    import gradio as gr
    
    # Get components
    components = get_components()
    
    # Get CSS styles
    css_styles = components["get_styles"]()
    
    # Store CSS for later use in launch()
    global _demo_css
    _demo_css = css_styles
    
    # Get boundary badges for the interface
    boundary_badges = BoundaryManager.get_boundary_badges()
    
    # Create interface without css parameter (will be added in launch)
    with gr.Blocks(
        title=f"πŸš€ ARF Investor Demo v3.8.0 - TRUE ARF v3.3.7"
    ) as demo:
        
        # Header - Updated to show true ARF version and boundaries
        header_html = components["create_header"]("3.3.7", settings.use_true_arf)
        
        # Status bar with boundary badges
        status_html = components["create_status_bar"]()
        
        # Add boundary badges as a separate element
        boundary_display = gr.HTML(value=boundary_badges, visible=settings.show_boundaries)
        
        # ============ 5 TABS ============
        with gr.Tabs(elem_classes="tab-nav"):
            
            # TAB 1: Live Incident Demo
            with gr.TabItem("πŸ”₯ Live Incident Demo", id="tab1"):
                (scenario_dropdown, scenario_card, telemetry_viz, impact_viz,
                 workflow_header, detection_agent, recall_agent, decision_agent,
                 oss_section, enterprise_section, oss_btn, enterprise_btn, 
                 approval_toggle, mcp_mode, timeline_viz,
                 detection_time, mttr, auto_heal, savings,
                 oss_results_display, enterprise_results_display, approval_display, demo_btn) = components["create_tab1_incident_demo"]()
            
            # TAB 2: Business ROI
            with gr.TabItem("πŸ’° Business Impact & ROI", id="tab2"):
                (dashboard_output, roi_scenario_dropdown, monthly_slider, team_slider,
                 calculate_btn, roi_output, roi_chart) = components["create_tab2_business_roi"](components["INCIDENT_SCENARIOS"])
            
            # TAB 3: Enterprise Features
            with gr.TabItem("🏒 Enterprise Features", id="tab3"):
                (license_display, validate_btn, trial_btn, upgrade_btn,
                 mcp_mode_tab3, mcp_mode_info, features_table, integrations_table) = components["create_tab3_enterprise_features"]()
            
            # TAB 4: Audit Trail
            with gr.TabItem("πŸ“œ Audit Trail & History", id="tab4"):
                (refresh_btn, clear_btn, export_btn, execution_table,
                 incident_table, export_text) = components["create_tab4_audit_trail"]()
            
            # TAB 5: Learning Engine
            with gr.TabItem("🧠 Learning Engine", id="tab5"):
                (learning_graph, graph_type, show_labels, search_query, search_btn,
                 clear_btn_search, search_results, stats_display, patterns_display,
                 performance_display) = components["create_tab5_learning_engine"]()
        
        # Footer
        footer_html = components["create_footer"]()
        
        # ============ EVENT HANDLERS ============
        
        # Update scenario display when dropdown changes
        scenario_dropdown.change(
            fn=update_scenario_display,
            inputs=[scenario_dropdown],
            outputs=[scenario_card, telemetry_viz, impact_viz, timeline_viz]
        )
        
        # Run OSS Analysis - Now uses TRUE ARF v3.3.7 with boundary awareness
        oss_btn.click(
            fn=run_true_arf_analysis,  # Updated function with boundary awareness
            inputs=[scenario_dropdown],
            outputs=[
                detection_agent, recall_agent, decision_agent,
                oss_results_display, incident_table
            ]
        )
        
        # Execute Enterprise Healing - Updated with boundary clarity
        enterprise_btn.click(
            fn=execute_enterprise_healing,
            inputs=[scenario_dropdown, approval_toggle, mcp_mode],
            outputs=[approval_display, enterprise_results_display, execution_table]
        )
        
        # Run Complete Demo with boundary progression
        @AsyncRunner.async_to_sync
        async def run_complete_demo_async(scenario_name):
            """Run a complete demo walkthrough with true ARF and boundary awareness"""
            # Step 1: Update scenario
            update_result = update_scenario_display(scenario_name)
            
            # Step 2: Run true ARF analysis
            oss_result = await run_true_arf_analysis(scenario_name)
            
            # Step 3: Execute Enterprise (simulation) with boundary context
            await asyncio.sleep(1)
            
            scenario = components["INCIDENT_SCENARIOS"].get(scenario_name, {})
            impact = scenario.get("business_impact", {})
            revenue_loss = impact.get("revenue_loss_per_hour", get_scenario_impact(scenario_name))
            savings = int(revenue_loss * 0.85)
            
            # Get boundary context
            boundaries = BoundaryManager.get_system_boundaries()
            
            # Get orchestrator for execution simulation
            orchestrator = components["DemoOrchestrator"]()
            execution_result = await orchestrator.execute_healing(scenario_name, "autonomous")
            
            enterprise_results = {
                "demo_mode": "Complete Walkthrough",
                "scenario": scenario_name,
                "arf_version": "3.3.7",
                "true_oss_used": True,
                "enterprise_simulated": True,
                "boundary_progression": [
                    f"1. Incident detected - {boundaries['oss']['label']}",
                    f"2. OSS analysis completed - {boundaries['oss']['label']}",
                    f"3. HealingIntent created - {boundaries['oss']['label']}",
                    f"4. Enterprise license validated ({boundaries['enterprise']['label']})",
                    f"5. Autonomous execution simulated ({boundaries['enterprise']['label']}+)",
                    f"6. Outcome recorded in RAG memory"
                ],
                "execution_result": execution_result,
                "outcome": {
                    "recovery_time": "12 minutes",
                    "manual_comparison": "45 minutes",
                    "cost_saved": f"${savings:,}",
                    "users_protected": "45,000",
                    "learning": "Pattern added to RAG memory"
                },
                "architectural_summary": f"This demonstrates the complete ARF v3.3.7 architecture: {boundaries['oss']['label']} for advisory analysis β†’ {boundaries['enterprise']['label']} for autonomous execution"
            }
            
            # Create demo completion message with enhanced boundary context
            demo_message = f"""
<div style="border: 1px solid #e2e8f0; border-radius: 14px; padding: 20px; 
            background: linear-gradient(135deg, #f0fdf4 0%, #e9d5ff 100%); margin-top: 20px;
            box-shadow: 0 8px 32px rgba(16, 185, 129, 0.1);">
    
    <!-- Header with dual-color badge showing boundary -->
    <div style="display: flex; justify-content: space-between; align-items: center; 
                margin-bottom: 20px; padding-bottom: 12px; border-bottom: 2px solid #e2e8f0;">
        <div>
            <h3 style="margin: 0; font-size: 18px; color: #1e293b; font-weight: 700;">
                βœ… Complete Demo: Architecture Validated
            </h3>
            <p style="margin: 5px 0 0 0; font-size: 13px; color: #64748b;">
                ARF v3.3.7 β€’ OSS advises β†’ Enterprise executes
            </p>
        </div>
        <div style="display: flex; align-items: center; gap: 8px;">
            <span style="padding: 6px 14px; background: linear-gradient(90deg, #10b981 0%, #10b981 50%, #8b5cf6 50%, #8b5cf6 100%); 
                        color: white; border-radius: 20px; font-size: 12px; font-weight: bold;">
                BOUNDARY VALIDATED
            </span>
        </div>
    </div>
    
    <!-- Key Results Grid -->
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
        <!-- Left Column: OSS Results -->
        <div style="border-left: 4px solid #10b981; padding: 12px; background: #f8fafc; border-radius: 8px;">
            <div style="font-size: 11px; color: #64748b; text-transform: uppercase; font-weight: 600; 
                       margin-bottom: 5px; display: flex; align-items: center; gap: 6px;">
                <span style="display: inline-block; width: 8px; height: 8px; background: #10b981; border-radius: 50%;"></span>
                {boundaries['oss']['label']}
            </div>
            <div style="font-size: 14px; color: #475569; line-height: 1.5;">
                β€’ Anomaly detected in 45s<br>
                β€’ 3 similar incidents recalled<br>
                β€’ 94% confidence healing plan<br>
                β€’ Apache 2.0 license validated
            </div>
        </div>
        
        <!-- Right Column: Enterprise Results -->
        <div style="border-left: 4px solid #8b5cf6; padding: 12px; background: #f8fafc; border-radius: 8px;">
            <div style="font-size: 11px; color: #64748b; text-transform: uppercase; font-weight: 600; 
                       margin-bottom: 5px; display: flex; align-items: center; gap: 6px;">
                <span style="display: inline-block; width: 8px; height: 8px; background: #8b5cf6; border-radius: 50%;"></span>
                {boundaries['enterprise']['label']}
            </div>
            <div style="font-size: 14px; color: #475569; line-height: 1.5;">
                β€’ Autonomous execution simulated<br>
                β€’ Rollback guarantee: 100%<br>
                β€’ 12min vs 45min recovery<br>
                β€’ ${savings:,} saved
            </div>
        </div>
    </div>
    
    <!-- Boundary Progression Visualization -->
    <div style="margin-bottom: 20px;">
        <div style="font-size: 12px; color: #64748b; text-transform: uppercase; font-weight: 600; 
                   margin-bottom: 12px; text-align: center;">
            πŸ—οΈ Architecture Flow
        </div>
        <div style="display: flex; align-items: center; justify-content: center; gap: 0;">
            <!-- OSS -->
            <div style="text-align: center; padding: 12px 16px; background: #f0fdf4; border-radius: 10px 0 0 10px; 
                       border: 2px solid #10b981; border-right: none; min-width: 140px;">
                <div style="font-size: 14px; color: #065f46; font-weight: 700;">OSS Advisory</div>
                <div style="font-size: 11px; color: #059669; margin-top: 3px;">Apache 2.0</div>
            </div>
            
            <!-- Arrow -->
            <div style="padding: 0 5px; background: #f1f5f9; position: relative;">
                <div style="width: 0; height: 0; border-top: 15px solid transparent; 
                           border-bottom: 15px solid transparent; border-left: 15px solid #10b981;"></div>
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
                           background: white; padding: 2px 6px; border-radius: 10px; font-size: 11px;
                           color: #64748b; border: 1px solid #e2e8f0; white-space: nowrap;">
                    advises
                </div>
            </div>
            
            <!-- Enterprise -->
            <div style="text-align: center; padding: 12px 16px; background: #f5f3ff; border-radius: 0 10px 10px 0; 
                       border: 2px solid #8b5cf6; border-left: none; min-width: 140px;">
                <div style="font-size: 14px; color: #5b21b6; font-weight: 700;">Enterprise</div>
                <div style="font-size: 11px; color: #7c3aed; margin-top: 3px;">Commercial</div>
            </div>
        </div>
    </div>
    
    <!-- ROI Summary -->
    <div style="background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); 
                border-radius: 10px; padding: 15px; margin-bottom: 15px;">
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; text-align: center;">
            <div>
                <div style="font-size: 11px; color: #64748b; margin-bottom: 5px;">Time Saved</div>
                <div style="font-size: 18px; font-weight: 700; color: #10b981;">73%</div>
            </div>
            <div>
                <div style="font-size: 11px; color: #64748b; margin-bottom: 5px;">Cost Saved</div>
                <div style="font-size: 18px; font-weight: 700; color: #10b981;">${savings:,}</div>
            </div>
            <div>
                <div style="font-size: 11px; color: #64748b; margin-bottom: 5px;">ROI Multiplier</div>
                <div style="font-size: 18px; font-weight: 700; color: #8b5cf6;">5.2Γ—</div>
            </div>
        </div>
    </div>
    
    <!-- Architecture Validation -->
    <div style="padding: 12px; background: #f0fdf4; border-radius: 8px; border: 1px solid #d1fae5;">
        <div style="display: flex; align-items: center; gap: 10px;">
            <div style="font-size: 20px;">βœ…</div>
            <div>
                <div style="font-size: 13px; color: #065f46; font-weight: 600; margin-bottom: 2px;">
                    Architecture Successfully Validated
                </div>
                <div style="font-size: 12px; color: #059669;">
                    Clear separation maintained: OSS for advisory intelligence, Enterprise for autonomous execution
                </div>
            </div>
        </div>
    </div>
    
    <!-- Call to Action -->
    <div style="margin-top: 15px; padding-top: 15px; border-top: 1px dashed #e2e8f0; 
                text-align: center; font-size: 12px; color: #64748b;">
        Ready for production? <a href="#" style="color: #8b5cf6; font-weight: 600; text-decoration: none;">
        Install ARF Enterprise β†’</a>
    </div>
</div>
"""
            
            # Combine all results
            return (
                *update_result,
                *oss_result[:3],  # detection_agent, recall_agent, decision_agent
                oss_result[3],    # oss_results_display
                enterprise_results,
                demo_message,
                incident_table,  # Will be updated from oss_result[4]
                execution_table
            )
        
        demo_btn.click(
            fn=run_complete_demo_async,
            inputs=[scenario_dropdown],
            outputs=[
                scenario_card, telemetry_viz, impact_viz, timeline_viz,
                detection_agent, recall_agent, decision_agent,
                oss_results_display,
                enterprise_results_display,
                approval_display,
                incident_table,
                execution_table
            ]
        )
        
        # ROI Calculation
        calculate_btn.click(
            fn=calculate_roi,
            inputs=[roi_scenario_dropdown, monthly_slider, team_slider],
            outputs=[roi_output, roi_chart]
        )
        
        # Update ROI scenario
        roi_scenario_dropdown.change(
            fn=lambda x: get_components()["EnhancedROICalculator"]().calculate_comprehensive_roi(),
            inputs=[],
            outputs=[roi_output]
        )
        
        # Update ROI chart
        monthly_slider.change(
            fn=lambda x, y: calculate_roi(roi_scenario_dropdown.value, x, y)[1],
            inputs=[monthly_slider, team_slider],
            outputs=[roi_chart]
        )
        
        team_slider.change(
            fn=lambda x, y: calculate_roi(roi_scenario_dropdown.value, x, y)[1],
            inputs=[monthly_slider, team_slider],
            outputs=[roi_chart]
        )
        
        # Audit Trail Functions
        def refresh_audit_trail():
            """Refresh audit trail tables"""
            return (
                get_audit_manager().get_execution_table(),
                get_audit_manager().get_incident_table()
            )
        
        def clear_audit_trail():
            """Clear audit trail"""
            get_audit_manager().clear()
            return [], []
        
        def export_audit_trail():
            """Export audit trail as JSON"""
            audit_data = {
                "executions": get_audit_manager().executions,
                "incidents": get_audit_manager().incidents,
                "boundary_crossings": get_audit_manager().boundary_crossings,
                "export_time": datetime.datetime.now().isoformat(),
                "arf_version": "3.3.7",
                "architecture": "OSS advises β†’ Enterprise executes"
            }
            return json.dumps(audit_data, indent=2)
        
        refresh_btn.click(
            fn=refresh_audit_trail,
            inputs=[],
            outputs=[execution_table, incident_table]
        )
        
        clear_btn.click(
            fn=clear_audit_trail,
            inputs=[],
            outputs=[execution_table, incident_table]
        )
        
        export_btn.click(
            fn=export_audit_trail,
            inputs=[],
            outputs=[export_text]
        )
        
        # Enterprise Features
        def validate_license():
            """Validate enterprise license with boundary context"""
            boundaries = BoundaryManager.get_system_boundaries()
            
            if boundaries["enterprise"]["available"]:
                return {
                    "status": "βœ… Valid License",
                    "license_type": "Enterprise",
                    "version": boundaries["enterprise"]["version"],
                    "expires": "2025-12-31",
                    "capabilities": boundaries["enterprise"]["capabilities"],
                    "boundary_context": f"Real {boundaries['enterprise']['label']} detected"
                }
            else:
                return {
                    "status": "⚠️ Demo Mode",
                    "license_type": "Simulated",
                    "version": boundaries["enterprise"]["version"],
                    "expires": "Demo only",
                    "capabilities": boundaries["enterprise"]["capabilities"],
                    "boundary_context": f"Simulating {boundaries['enterprise']['label']} - requires license",
                    "contact": "sales@arf.dev"
                }
        
        validate_btn.click(
            fn=validate_license,
            inputs=[],
            outputs=[license_display]
        )
        
        # Initialize with boundary badges
        demo.load(
            fn=lambda: boundary_badges,
            inputs=[],
            outputs=[boundary_display]
        )
        
        # Load default scenario
        demo.load(
            fn=lambda: update_scenario_display(settings.default_scenario),
            inputs=[],
            outputs=[scenario_card, telemetry_viz, impact_viz, timeline_viz]
        )
        
        # Load ROI data
        demo.load(
            fn=lambda: calculate_roi(settings.default_scenario, 15, 5),
            inputs=[],
            outputs=[roi_output, roi_chart]
        )
        
        logger.info("βœ… Demo interface created successfully with boundary awareness")
    
    return demo

# ===========================================
# LAUNCH FUNCTION - UPDATED FOR SPACES COMPATIBILITY
# ===========================================
def launch_demo():
    """Launch the demo application with proper configuration"""
    try:
        logger.info("πŸš€ Starting ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION")
        logger.info(f"πŸ“Š Settings: mode={settings.arf_mode}, use_true_arf={settings.use_true_arf}")
        
        # Check installation and show boundaries
        installation = get_installation_status()
        boundaries = BoundaryManager.get_system_boundaries()
        
        logger.info("=" * 60)
        logger.info("πŸ—οΈ  SYSTEM ARCHITECTURE BOUNDARIES:")
        logger.info(f"  OSS: {boundaries['oss']['label']} v{boundaries['oss']['version']}")
        logger.info(f"  Enterprise: {boundaries['enterprise']['label']} v{boundaries['enterprise']['version']}")
        logger.info(f"  Mode: {boundaries['demo_mode']['architecture']}")
        logger.info(f"  Honesty: {boundaries['demo_mode']['honesty_level']}")
        logger.info("=" * 60)
        
        if installation["oss_installed"]:
            logger.info("βœ… True ARF OSS detected - using real v3.3.7 integration")
        else:
            logger.warning("⚠️ ARF OSS not installed - using enhanced mock mode")
            logger.info("πŸ’‘ Install: pip install agentic-reliability-framework==3.3.7")
        
        if installation["enterprise_installed"]:
            logger.info("πŸš€ ARF Enterprise detected - real autonomous execution available")
        else:
            logger.info("🎭 Enterprise not installed - simulating autonomous execution")
            logger.info("πŸ’‘ Contact sales@arf.dev for Enterprise trial")
        
        # Create interface
        demo = create_demo_interface()
        
        # Get CSS styles from components
        components = get_components()
        css_styles = components["get_styles"]()
        
        # Configure Gradio launch for Hugging Face Spaces
        launch_config = {
            "server_name": "0.0.0.0",
            "server_port": 7860,
            "share": False,  # Spaces handles sharing
            "favicon_path": None,
            "auth": None,
            "auth_message": None,
            "ssl_verify": True,
            "ssl_keyfile": None,
            "ssl_certfile": None,
            "quiet": False,
            "show_error": True,
            "debug": False,
            "enable_queue": True,
            "max_threads": 40,
            "theme": "default",
            "dark": False,
            "show_api": False,
            "allowed_paths": None,
            "blocked_paths": None,
            "app_kwargs": {},
            "root_path": "",
        }
        
        # Update with CSS
        if css_styles:
            launch_config["css"] = css_styles
        
        logger.info("βœ… Launch configuration ready")
        logger.info("🌐 Starting web server...")
        
        return demo, launch_config
        
    except Exception as e:
        logger.error(f"❌ Launch failed: {e}", exc_info=True)
        
        # Create minimal fallback interface
        import gradio as gr
        
        with gr.Blocks(title="ARF Demo - Fallback Mode") as fallback_demo:
            gr.HTML("""
                <div style="text-align: center; padding: 50px;">
                    <h1 style="color: #ef4444;">🚨 ARF Demo Failed to Start</h1>
                    <p style="color: #64748b; font-size: 16px;">Error: """ + str(e) + """</p>
                    <div style="margin-top: 30px; padding: 20px; background: #fef2f2; border-radius: 10px; display: inline-block;">
                        <p style="color: #dc2626; font-weight: bold;">Troubleshooting Steps:</p>
                        <ol style="text-align: left; color: #475569;">
                            <li>Check logs for detailed error</li>
                            <li>Ensure all dependencies are installed</li>
                            <li>Try: pip install agentic-reliability-framework==3.3.7</li>
                            <li>Restart the application</li>
                        </ol>
                    </div>
                </div>
            """)
        
        return fallback_demo, {"server_name": "0.0.0.0", "server_port": 7860}

# ===========================================
# MAIN EXECUTION
# ===========================================
if __name__ == "__main__":
    try:
        logger.info("πŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION")
        logger.info("=" * 60)
        logger.info("Enhanced version with clear boundaries and reliable visualizations")
        logger.info("Fixed to show clear OSS vs Enterprise boundaries with architectural honesty")
        logger.info("=" * 60)
        
        # Launch the demo
        demo, config = launch_demo()
        
        # Show startup message
        print("\n" + "="*60)
        print("πŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION")
        print("πŸ“Š Architecture: OSS advises β†’ Enterprise executes")
        print("🌐 Starting on http://localhost:7860")
        print("="*60 + "\n")
        
        # Launch with error handling
        try:
            demo.launch(**config)
        except Exception as launch_error:
            logger.error(f"❌ Launch error: {launch_error}")
            
            # Try alternative launch without CSS
            if "css" in config:
                logger.info("⚠️ Retrying without CSS...")
                config.pop("css", None)
                demo.launch(**config)
            else:
                # Last resort: simple launch
                demo.launch(server_name="0.0.0.0", server_port=7860)
        
    except KeyboardInterrupt:
        logger.info("πŸ‘‹ Demo stopped by user")
    except Exception as e:
        logger.error(f"❌ Fatal error: {e}", exc_info=True)
        sys.exit(1)