File size: 146,782 Bytes
b6e0497
5b3f47c
 
498388a
663691e
046e6cb
fb680d1
b6e0497
f91e1f4
9f47de8
 
 
a86e220
9f47de8
 
 
49293a6
9f47de8
 
7f3d172
9f47de8
 
 
 
 
 
 
 
 
 
 
a86e220
 
9f47de8
 
 
b6e0497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
c3adeed
b987839
c3adeed
 
b987839
 
c3adeed
 
 
b987839
 
 
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34a2540
9f47de8
 
 
 
 
 
 
046e6cb
9f47de8
 
046e6cb
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
046e6cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
 
 
046e6cb
9f47de8
 
046e6cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
 
046e6cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
 
 
c3adeed
9f47de8
 
c3adeed
9f47de8
 
 
 
 
 
 
 
 
b987839
804a1ea
 
 
 
 
 
 
 
 
c3adeed
 
 
 
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b99f4d
 
 
 
 
 
9f47de8
 
 
 
 
 
 
 
 
8b99f4d
 
 
 
 
 
9f47de8
 
 
 
a86e220
9f47de8
 
 
 
 
 
7ea7462
 
b0cdc19
a11bfee
9f47de8
 
b0cdc19
9f47de8
 
 
b0cdc19
 
 
 
b6e0497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3657c9
b6e0497
 
d3657c9
 
 
 
b6e0497
d3657c9
 
 
b6e0497
 
d3657c9
b6e0497
d3657c9
b6e0497
 
 
 
 
d3657c9
 
 
b6e0497
 
 
 
 
 
 
 
 
d3657c9
 
 
 
 
 
b6e0497
 
 
d3657c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6e0497
d3657c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6e0497
d3657c9
 
 
 
b6e0497
 
d3657c9
 
b6e0497
 
 
d3657c9
b6e0497
d3657c9
 
 
 
 
 
 
 
 
b6e0497
 
d3657c9
b6e0497
a5398f8
b0cdc19
a5398f8
f91e1f4
 
b0cdc19
601702b
 
f91e1f4
9f47de8
 
f91e1f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0cdc19
 
 
f91e1f4
 
 
 
 
 
 
 
9f47de8
f91e1f4
 
b0cdc19
f91e1f4
b0cdc19
 
 
f91e1f4
b0cdc19
f91e1f4
a5398f8
 
b0cdc19
a5398f8
 
f91e1f4
 
 
b0cdc19
f91e1f4
b0cdc19
 
 
f91e1f4
601702b
b0cdc19
f91e1f4
601702b
f91e1f4
 
b0cdc19
f91e1f4
b0cdc19
f91e1f4
b0cdc19
f91e1f4
 
 
 
a11bfee
f91e1f4
601702b
b0cdc19
601702b
a86e220
f91e1f4
 
 
 
 
 
 
 
 
fc65cce
f91e1f4
 
b0cdc19
f91e1f4
a5398f8
 
 
b0cdc19
 
 
 
 
 
 
 
 
a5398f8
b0cdc19
f91e1f4
 
 
 
 
 
 
 
b0cdc19
 
 
 
 
 
f91e1f4
 
 
b0cdc19
f91e1f4
 
b0cdc19
 
 
f91e1f4
a86e220
b0cdc19
f91e1f4
a86e220
bd96870
f91e1f4
b0cdc19
f91e1f4
 
 
b0cdc19
f91e1f4
 
 
a86e220
f91e1f4
 
b0cdc19
f91e1f4
b0cdc19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f91e1f4
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b28d6b4
34a2540
 
b28d6b4
f516920
b28d6b4
 
34a2540
 
 
b28d6b4
 
34a2540
b28d6b4
 
34a2540
 
 
 
 
 
 
 
 
6c5d8cf
34a2540
 
6c5d8cf
f10e39f
 
 
 
 
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
601702b
34a2540
 
 
601702b
34a2540
f10e39f
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
601702b
34a2540
 
 
9f47de8
34a2540
 
 
 
f91e1f4
34a2540
 
 
 
601702b
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
34a2540
 
 
 
 
 
fb680d1
34a2540
 
 
 
 
 
 
 
9f47de8
34a2540
 
 
 
9f47de8
 
 
34a2540
9f47de8
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb680d1
34a2540
 
 
 
 
 
 
 
9f47de8
34a2540
 
 
 
9f47de8
 
 
34a2540
9f47de8
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
34a2540
 
 
 
 
 
fb680d1
34a2540
 
 
 
 
 
 
 
9f47de8
34a2540
 
 
 
9f47de8
 
 
34a2540
9f47de8
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
 
 
34a2540
9f47de8
34a2540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
34a2540
 
 
 
 
 
9a7698c
fc65cce
b987839
5aa5b79
9f47de8
b987839
9f47de8
 
 
 
 
 
 
f91e1f4
9f47de8
f91e1f4
9f47de8
 
 
 
 
 
 
 
663691e
9f47de8
 
 
 
663691e
9f47de8
 
 
 
 
 
 
 
 
 
 
663691e
 
9f47de8
5aa5b79
9f47de8
 
 
 
5b3f47c
9f47de8
5b3f47c
 
9f47de8
5b3f47c
9f47de8
5b3f47c
 
 
9f47de8
5b3f47c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
5b3f47c
 
 
 
 
 
 
 
 
9f47de8
b987839
9f47de8
 
 
b987839
9f47de8
b987839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
 
b987839
 
 
9f47de8
b987839
 
 
 
 
 
9f47de8
 
b987839
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
b987839
 
 
 
 
 
 
 
 
 
 
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663691e
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
 
 
 
 
 
 
 
 
 
663691e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
9f47de8
 
b987839
9f47de8
 
 
 
 
 
 
 
 
 
 
f91e1f4
9f47de8
 
 
f91e1f4
9f47de8
 
 
a11bfee
9f47de8
 
 
 
 
 
 
 
f91e1f4
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
9f47de8
 
 
b987839
 
cc15516
b987839
 
 
 
 
 
 
 
 
cc15516
b987839
 
cc15516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
cc15516
b987839
 
cc15516
b987839
cc15516
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
cc15516
b987839
 
 
cc15516
 
 
 
 
 
 
 
 
 
b987839
 
 
cc15516
b987839
 
 
 
 
 
 
 
 
cc15516
b987839
 
cc15516
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
cc15516
b987839
 
cc15516
b987839
cc15516
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
cc15516
b987839
 
 
cc15516
 
 
 
 
 
 
 
 
 
b987839
 
 
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
046e6cb
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
 
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663691e
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b3f47c
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
498388a
9f47de8
 
 
498388a
 
9f47de8
 
 
 
 
 
 
 
 
 
 
b6e0497
 
 
 
 
 
 
 
 
9f47de8
 
 
b6e0497
9f47de8
 
 
b6e0497
 
 
 
9f47de8
b6e0497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
b6e0497
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
b6e0497
 
 
 
 
 
 
 
9f47de8
 
b6e0497
 
 
 
 
9f47de8
b6e0497
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
 
b6e0497
 
 
 
 
 
9f47de8
b6e0497
9f47de8
b0cdc19
a5398f8
 
 
9f47de8
498388a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
663691e
 
 
6d28bf3
663691e
6d28bf3
 
 
663691e
6d28bf3
663691e
6d28bf3
663691e
6d28bf3
 
 
9f47de8
b987839
9f47de8
 
 
 
b987839
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f91e1f4
9f47de8
b987839
 
9f47de8
b987839
f91e1f4
 
b0cdc19
f91e1f4
9f47de8
 
b0cdc19
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0cdc19
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0cdc19
 
 
 
9f47de8
b0cdc19
 
 
 
9f47de8
 
b0cdc19
 
9f47de8
 
f91e1f4
9f47de8
b6e0497
9f47de8
f91e1f4
b6e0497
9f47de8
 
 
 
 
 
d3657c9
 
9f47de8
c3adeed
9f47de8
c3adeed
9f47de8
44e7696
b6e0497
d3657c9
 
 
 
 
 
 
 
b6e0497
 
 
d3657c9
 
 
 
 
9f47de8
1ae979c
9f47de8
 
 
859f566
5aa5b79
9f47de8
 
445884d
b6e0497
9f47de8
d79de79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb680d1
a11bfee
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a86e220
9f47de8
 
a11bfee
d3657c9
 
 
 
 
 
 
 
 
 
 
 
 
 
9f47de8
a11bfee
663691e
f91e1f4
d79de79
f91e1f4
663691e
fb680d1
d3657c9
663691e
a11bfee
 
0049149
046e6cb
0049149
d4ad053
0049149
046e6cb
 
0049149
34a2540
046e6cb
0049149
046e6cb
9f47de8
d4ad053
f91e1f4
9f47de8
fb680d1
9f47de8
 
a11bfee
a86e220
b987839
9f47de8
f91e1f4
9f47de8
 
 
 
 
 
 
 
663691e
 
9f47de8
34a2540
d4ad053
9f47de8
 
 
 
 
 
 
663691e
9f47de8
 
 
 
 
 
 
 
 
 
 
5b3f47c
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
663691e
9f47de8
 
 
5b3f47c
9f47de8
 
 
 
d3657c9
9f47de8
 
 
 
 
d3657c9
9f47de8
d3657c9
9f47de8
 
d3657c9
5b3f47c
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
d3657c9
 
9f47de8
 
 
 
d3657c9
9f47de8
 
 
 
 
 
 
 
d3657c9
 
9f47de8
 
 
 
d3657c9
9f47de8
 
 
663691e
9f47de8
 
 
 
 
 
d3657c9
9f47de8
 
 
 
 
 
 
 
 
 
 
 
d3657c9
9f47de8
 
 
 
d3657c9
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
d3657c9
9f47de8
 
 
d3657c9
9f47de8
 
 
d3657c9
663691e
9f47de8
 
d3657c9
9f47de8
 
 
 
 
 
498388a
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
d3657c9
 
9f47de8
 
 
 
 
 
 
 
 
b987839
 
 
9f47de8
 
 
d79de79
fb680d1
9f47de8
 
 
b987839
 
9f47de8
 
 
 
 
f91e1f4
9f47de8
fb680d1
d79de79
fb680d1
9f47de8
 
 
 
 
 
a11bfee
a4b81cc
9f47de8
 
f91e1f4
9f47de8
f91e1f4
5aa5b79
 
b987839
9f47de8
b987839
 
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b987839
9f47de8
b987839
9f47de8
b987839
 
9f47de8
 
 
b987839
9f47de8
b987839
 
 
 
9f47de8
 
 
 
 
 
 
 
5b3f47c
9f47de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb680d1
49293a6
663691e
a11bfee
663691e
fb680d1
d79de79
663691e
49293a6
9f47de8
 
 
 
 
 
 
 
b6e0497
d265a89
85eb95b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c3adeed
85eb95b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
804a1ea
 
 
6dc71ce
804a1ea
 
 
85eb95b
c3adeed
804a1ea
85eb95b
c3adeed
804a1ea
 
 
 
c3adeed
804a1ea
 
 
 
 
 
 
85eb95b
 
 
 
 
 
 
 
 
 
c3adeed
85eb95b
 
 
 
 
 
 
804a1ea
 
c3adeed
85eb95b
804a1ea
85eb95b
804a1ea
 
 
c3adeed
804a1ea
 
85eb95b
 
 
 
 
 
 
c3adeed
804a1ea
 
 
 
 
c3adeed
85eb95b
 
 
 
 
 
 
 
 
 
 
804a1ea
 
 
 
 
 
 
 
 
 
 
 
 
85eb95b
c3adeed
6dc71ce
804a1ea
 
6dc71ce
804a1ea
 
 
6dc71ce
c3adeed
804a1ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
# app.py - Complete fixed version with Plotly compatibility AND MODERN COMPONENTS
# πŸš€ ARF Ultimate Investor Demo v3.3.9 - ENTERPRISE EDITION
# Enhanced with clear OSS vs Enterprise boundaries
# UPDATED: Added realism panel integration for enterprise-seasoned SRE experience
# UPDATED: Added dynamic performance metrics for Phase 2
# SURGICAL FIX: Fixed AsyncRunner.async_to_sync contract violation
# DOCTRINAL FIX: Updated unpacking contract from 24 to 26 values
# MODERN UI: Integrated modern_components.py for enhanced UI foundation

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))

# ===========================================
# MODERN UI FEATURE FLAGS
# ===========================================
# Feature flags configuration for safe rollout
FEATURE_FLAGS = {
    'modern_ui': True,           # Use modern components
    'dark_mode': True,           # Enable dark mode toggle
    'responsive_design': True,   # Use responsive CSS
    'progressive_disclosure': False,  # Start disabled
    'keyboard_nav': False,
    'realtime_updates': False
}

# Check URL parameters for feature flag overrides (placeholder)
def get_feature_flags():
    flags = FEATURE_FLAGS.copy()
    # TODO: Add URL parameter parsing if needed
    return flags

# ===========================================
# FIX FOR ASYNC EVENT LOOP ISSUES - UPDATED FOR SPACES COMPATIBILITY
# ===========================================
# CRITICAL FIX: Don't apply nest_asyncio here - let uvicorn handle it
# This fixes the "loop_factory" TypeError
try:
    import nest_asyncio
    # Only apply if we're NOT in the main thread (detect if uvicorn is running)
    # We'll handle this differently in the main() function
    logger.info("βœ… nest_asyncio imported but not applied yet")
except ImportError:
    logger.warning("⚠️ nest_asyncio not available, async operations may have issues")

# ===========================================
# IMPORT UTILITY CLASSES FIRST
# ===========================================
from utils.installation import InstallationHelper
from demo.guidance import DemoPsychologyController, get_demo_controller

# ===========================================
# BOUNDARY MANAGEMENT SYSTEM
# ===========================================
class BoundaryManager:
    """Manages clear boundaries between OSS and Enterprise"""
    
    @staticmethod
    def get_system_boundaries():
        """Get current system boundaries"""
        installation = get_installation_status()
        
        return {
            "oss": {
                "available": installation["oss_installed"],
                "version": installation["oss_version"] or "mock",
                "label": installation["badges"]["oss"]["text"],
                "color": installation["badges"]["oss"]["color"],
                "icon": installation["badges"]["oss"]["icon"],
                "capabilities": ["advisory_analysis", "rag_search", "healing_intent"],
                "license": "Apache 2.0"
            },
            "enterprise": {
                "available": installation["enterprise_installed"],
                "version": installation["enterprise_version"] or "simulated",
                "label": installation["badges"]["enterprise"]["text"],
                "color": installation["badges"]["enterprise"]["color"],
                "icon": installation["badges"]["enterprise"]["icon"],
                "capabilities": ["autonomous_execution", "rollback_guarantee", "mcp_integration", "enterprise_support"],
                "license": "Commercial"
            },
            "demo_mode": {
                "active": True,
                "architecture": "OSS advises β†’ Enterprise executes",
                "boundary_visible": settings.show_boundaries
            }
        }
    
    @staticmethod
    def get_boundary_badges() -> str:
        """Get HTML badges showing system boundaries"""
        boundaries = BoundaryManager.get_system_boundaries()
        
        return f"""
        <div style="display: flex; justify-content: center; gap: 20px; margin: 0 auto 25px auto; 
                    max-width: 800px; flex-wrap: wrap;">
            <div style="display: flex; align-items: center; gap: 10px; padding: 12px 20px; 
                        background: linear-gradient(135deg, {boundaries['oss']['color']}22 0%, {boundaries['oss']['color']}11 100%);
                        border: 2px solid {boundaries['oss']['color']}; border-radius: 12px;">
                <div style="font-size: 24px;">{boundaries['oss']['icon']}</div>
                <div>
                    <div style="font-size: 14px; font-weight: 600; color: {boundaries['oss']['color']};">
                        {boundaries['oss']['label']}
                    </div>
                    <div style="font-size: 11px; color: #64748b;">
                        Apache 2.0 β€’ Advisory Intelligence
                    </div>
                </div>
            </div>
            
            <div style="display: flex; align-items: center; gap: 10px; padding: 12px 20px; 
                        background: linear-gradient(135deg, {boundaries['enterprise']['color']}22 0%, {boundaries['enterprise']['color']}11 100%);
                        border: 2px solid {boundaries['enterprise']['color']}; border-radius: 12px;">
                <div style="font-size: 24px;">{boundaries['enterprise']['icon']}</div>
                <div>
                    <div style="font-size: 14px; font-weight: 600; color: {boundaries['enterprise']['color']};">
                        {boundaries['enterprise']['label']}
                    </div>
                    <div style="font-size: 11px; color: #64748b;">
                        Commercial β€’ Autonomous Execution
                    </div>
                </div>
            </div>
            
            <div style="display: flex; align-items: center; gap: 10px; padding: 12px 20px; 
                        background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
                        border: 2px dashed #94a3b8; border-radius: 12px;">
                <div style="font-size: 24px;">πŸ—οΈ</div>
                <div>
                    <div style="font-size: 14px; font-weight: 600; color: #475569;">
                        Architecture Boundary
                    </div>
                    <div style="font-size: 11px; color: #64748b;">
                        OSS advises β†’ Enterprise executes
                    </div>
                </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>
            """

# ===========================================
# FIXED: AsyncRunner - CONTRACT-PRESERVING VERSION
# ===========================================
class AsyncRunner:
    """Enhanced async runner with better error handling - FIXED to preserve return contracts"""
    
    @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}")
            # CRITICAL FIX: Return contract-compatible values instead of dict
            error_html = f"""
            <div style="border: 2px solid #ef4444; border-radius: 14px; padding: 18px; 
                       background: linear-gradient(135deg, #fef2f2 0%, #ffffff 100%); 
                       text-align: center; flex: 1; margin: 5px; min-height: 180px;">
                <div style="font-size: 32px; margin-bottom: 10px; color: #ef4444;">❌</div>
                <div style="width: 100%;">
                    <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Async Error</h4>
                    <p style="font-size: 13px; color: #64748b; margin-bottom: 12px; line-height: 1.4;">
                        Async operation failed
                    </p>
                </div>
            </div>
            """
            
            error_dict = {
                "status": "error",
                "error": str(e),
                "scenario": "Unknown",
                "arf_version": "3.3.9",
                "boundary_note": "Async execution boundary reached"
            }
            
            error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([
                {"Error": "Async Execution Failed", "Message": str(e)}
            ])
            
            # πŸ”’ SHAPE CONTRACT ENFORCED: Always return 5-tuple matching expected signature
            return error_html, error_html, error_html, error_dict, error_df
    
    @staticmethod
    def async_to_sync(async_func):
        """Decorator to convert async function to sync - FIXED to preserve return contract"""
        def wrapper(*args, **kwargs):
            try:
                # Direct call to run_async which now preserves contract
                result = AsyncRunner.run_async(async_func(*args, **kwargs))
                
                # Ensure result is a 5-tuple (contract validation)
                if isinstance(result, tuple) and len(result) == 5:
                    return result
                else:
                    # Contract violation - wrap it properly
                    logger.warning(f"Contract violation: Expected 5-tuple, got {type(result)}")
                    error_html = f"""
                    <div style="border: 2px solid #f59e0b; border-radius: 14px; padding: 18px; 
                               background: linear-gradient(135deg, #fef3c7 0%, #ffffff 100%); 
                               text-align: center; flex: 1; margin: 5px; min-height: 180px;">
                        <div style="font-size: 32px; margin-bottom: 10px; color: #f59e0b;">⚠️</div>
                        <div style="width: 100%;">
                            <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Contract Violation</h4>
                            <p style="font-size: 13px; color: #64748b; margin-bottom: 12px; line-height: 1.4;">
                                Expected 5-tuple, got {type(result).__name__}
                            </p>
                        </div>
                    </div>
                    """
                    
                    error_dict = {
                        "status": "contract_error",
                        "error": f"Expected 5-tuple, got {type(result)}",
                        "scenario": args[0] if args else "Unknown",
                        "arf_version": "3.3.9",
                        "boundary_note": "Return contract violation"
                    }
                    
                    error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([
                        {"Error": "Contract Error", "Message": "Return shape violation"}
                    ])
                    
                    return error_html, error_html, error_html, error_dict, error_df
                    
            except Exception as e:
                logger.error(f"Async to sync conversion failed: {e}")
                # πŸ”’ SHAPE CONTRACT ENFORCED: Always return 5-tuple
                error_html = f"""
                <div style="border: 2px solid #ef4444; border-radius: 14px; padding: 18px; 
                           background: linear-gradient(135deg, #fef2f2 0%, #ffffff 100%); 
                           text-align: center; flex: 1; margin: 5px; min-height: 180px;">
                    <div style="font-size: 32px; margin-bottom: 10px; color: #ef4444;">❌</div>
                    <div style="width: 100%;">
                        <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Conversion Error</h4>
                        <p style="font-size: 13px; color: #64748b; margin-bottom: 12px; line-height: 1.4;">
                            Async to sync failed
                        </p>
                    </div>
                </div>
                """
                
                error_dict = {
                    "status": "error",
                    "error": str(e),
                    "scenario": args[0] if args else "Unknown",
                    "arf_version": "3.3.9",
                    "boundary_context": "OSS advisory only - execution requires Enterprise"
                }
                
                error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([
                    {"Error": "Conversion Failed", "Message": str(e)}
                ])
                
                # πŸ”’ SHAPE CONTRACT ENFORCED: Always return 5-tuple
                return error_html, error_html, error_html, error_dict, error_df
        return wrapper

# ===========================================
# SIMPLE SETTINGS - FIXED: Added missing attributes
# ===========================================
class Settings:
    """Simple settings class - FIXED: Added all missing attributes"""
    def __init__(self):
        self.arf_mode = "demo"
        self.use_true_arf = True
        self.default_scenario = "Cache Miss Storm"
        self.max_history_items = 100
        self.auto_refresh_seconds = 30
        self.show_boundaries = True
        self.architectural_honesty = True
        self.engineer_annual_cost = 200000
        self.default_savings_rate = 0.25  # FIXED: Added missing attribute
        self.cache_miss_impact = 8500
        self.database_impact = 4200
        self.kubernetes_impact = 5500
        self.api_impact = 3800
        self.network_impact = 12000
        self.storage_impact = 6800
        self.telemetry_enabled = True
        self.mcp_mode = "simulated"
        self.enterprise_features = ["simulated_execution", "rollback_guarantee"]
        self.default_savings_rate = 0.25  # FIXED: Ensure it's defined
        self.enable_mcp_integration = True  # FIXED: Added missing
        self.enable_learning_engine = True  # FIXED: Added missing
        self.max_concurrent_incidents = 5  # FIXED: Added missing

settings = Settings()

# ===========================================
# ARF INSTALLATION CHECK - FIXED VERSION
# ===========================================
def check_arf_installation():
    """Check if real ARF packages are installed - Fixed version"""
    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 using InstallationHelper
    installation_helper = InstallationHelper()
    status = installation_helper.check_installation()
    
    results["oss_installed"] = status["oss_installed"]
    results["oss_version"] = status["oss_version"]
    results["enterprise_installed"] = status["enterprise_installed"]
    results["enterprise_version"] = status["enterprise_version"]
    results["recommendations"] = status["recommendations"]
    
    if results["oss_installed"]:
        results["badges"]["oss"] = {
            "text": f"βœ… ARF OSS v{results['oss_version']}", 
            "color": "#10b981", 
            "icon": "βœ…"
        }
        logger.info(f"βœ… ARF OSS v{results['oss_version']} detected")
    else:
        results["badges"]["oss"] = {
            "text": "βœ… ARF OSS v3.3.9",
            "color": "#10b981",
            "icon": "βœ…"
        }
        logger.info("βœ… ARF OSS v3.3.9 (demo mode)")
    
    if results["enterprise_installed"]:
        results["badges"]["enterprise"] = {
            "text": f"πŸš€ Enterprise v{results['enterprise_version']}", 
            "color": "#8b5cf6", 
            "icon": "πŸš€"
        }
        logger.info(f"βœ… ARF Enterprise v{results['enterprise_version']} detected")
    else:
        results["badges"]["enterprise"] = {
            "text": "🏒 Enterprise Edition",  # Changed from "πŸ”’ Enterprise Required"
            "color": "#3b82f6",              # Changed from "#64748b" (gray to blue)
            "icon": "🏒"                     # Changed from "πŸ”’"
        }
        logger.info("🏒 Enterprise Edition (simulated)")
    
    return results

_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

# ===========================================
# PLOTLY CONFIGURATION FOR GRADIO COMPATIBILITY
# ===========================================
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
import pandas as pd
import numpy as np

# Configure Plotly for Gradio compatibility
pio.templates.default = "plotly_white"
logger.info("βœ… Plotly configured for Gradio compatibility")

# ===========================================
# MODERN UI COMPONENTS IMPORT
# ===========================================
# Import modern components with fallback
try:
    from ui.modern_components import (
        initialize_modern_ui,
        Card, Grid, ObservationGate,
        SequencingFlow, ProcessDisplay,
        DESIGN_TOKENS, Button, Badge,
        ResponsiveUtils, Accessibility, DarkMode,
        create_example_dashboard
    )
    MODERN_UI_AVAILABLE = True
    logger.info("βœ… Modern UI components loaded successfully")
except ImportError as e:
    MODERN_UI_AVAILABLE = False
    logger.warning(f"⚠️ Modern UI components not available: {e}")
    
    # Create minimal fallback classes
    class Card:
        @staticmethod
        def create(content, **kwargs):
            return f"<div class='card'>{content}</div>"
    
    class ObservationGate:
        @staticmethod
        def create(confidence=65.0, **kwargs):
            return f"<div>Observation Gate: {confidence}%</div>"

# ===========================================
# CSS LOADING FUNCTION
# ===========================================
def load_css_files():
    """Load CSS files for modern UI with fallback - ENHANCED"""
    css_content = ""
    
    # Feature flag check
    flags = get_feature_flags()
    
    if flags.get('modern_ui', True):  # Default to True
        try:
            # Load modern.css
            with open("styles/modern.css", "r") as f:
                css_content += f.read() + "\n"
            logger.info("βœ… Loaded modern.css")
        except FileNotFoundError:
            logger.warning("⚠️ modern.css not found, using fallback")
            css_content += """
            /* Modern CSS Fallback */
            :root {
                --color-primary: #3b82f6;
                --color-success: #10b981;
                --color-warning: #f59e0b;
                --color-danger: #ef4444;
                --color-bg: #ffffff;
                --color-text: #1e293b;
                --color-border: #e2e8f0;
            }
            
            .container {
                width: 100%;
                max-width: 1200px;
                margin: 0 auto;
                padding: 0 1rem;
            }
            
            .card {
                background: white;
                border-radius: 0.75rem;
                border: 1px solid var(--color-border);
                padding: 1.5rem;
                box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
            }
            """
        
        if flags.get('responsive_design', True):
            try:
                # Load responsive.css
                with open("styles/responsive.css", "r") as f:
                    css_content += f.read() + "\n"
                logger.info("βœ… Loaded responsive.css")
            except FileNotFoundError:
                logger.warning("⚠️ responsive.css not found, using fallback")
                css_content += """
                /* Responsive Fallback */
                @media (max-width: 768px) {
                    .grid-2, .grid-3, .grid-4 {
                        grid-template-columns: 1fr !important;
                    }
                    
                    .card {
                        padding: 1rem;
                    }
                }
                """
        
        # Add dark mode toggle CSS
        if flags.get('dark_mode', True):
            css_content += """
            /* Dark Mode Toggle */
            .dark-mode-toggle {
                position: fixed;
                bottom: 20px;
                right: 20px;
                z-index: 1000;
                background: white;
                border: 2px solid var(--color-border);
                border-radius: 50%;
                width: 48px;
                height: 48px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                transition: all 0.3s ease;
            }
            
            .dark-mode-toggle:hover {
                transform: scale(1.1);
                box-shadow: 0 6px 16px rgba(0,0,0,0.15);
            }
            
            [data-theme="dark"] {
                --color-bg: #0f172a;
                --color-text: #f1f5f9;
                --color-border: #334155;
            }
            
            [data-theme="dark"] .card {
                background: #1e293b;
            }
            """
    else:
        # Minimal CSS
        css_content = """
        :root { 
            --color-primary: #3b82f6; 
            --color-bg: #ffffff;
            --color-text: #1e293b;
        }
        
        body {
            font-family: system-ui, -apple-system, sans-serif;
        }
        """
    
    return css_content

# ===========================================
# ENHANCED VISUALIZATION FUNCTIONS WITH GRADIO COMPATIBILITY
# ===========================================
def create_simple_telemetry_plot(scenario_name: str, is_real_arf: bool = True) -> go.Figure:
    """
    FIXED: Enhanced for Gradio compatibility with better error handling
    """
    try:
        # Generate sample telemetry data
        times = pd.date_range(start=datetime.datetime.now() - datetime.timedelta(minutes=10), 
                             end=datetime.datetime.now(), 
                             periods=60)
        
        # Different patterns based on scenario
        if "Cache" in scenario_name:
            normal_values = np.random.normal(30, 5, 30).tolist()
            anomaly_values = np.random.normal(85, 10, 30).tolist()
            data = normal_values + anomaly_values
            title = f"Cache Hit Rate: {scenario_name}"
            y_label = "Hit Rate (%)"
            threshold = 75
        elif "Database" in scenario_name:
            normal_values = np.random.normal(15, 3, 30).tolist()
            anomaly_values = np.random.normal(95, 5, 30).tolist()
            data = normal_values + anomaly_values
            title = f"Database Connections: {scenario_name}"
            y_label = "Connections (%)"
            threshold = 90
        elif "Kubernetes" in scenario_name:
            normal_values = np.random.normal(40, 8, 30).tolist()
            anomaly_values = np.random.normal(95, 2, 30).tolist()
            data = normal_values + anomaly_values
            title = f"Memory Usage: {scenario_name}"
            y_label = "Memory (%)"
            threshold = 85
        else:
            normal_values = np.random.normal(50, 10, 30).tolist()
            anomaly_values = np.random.normal(90, 5, 30).tolist()
            data = normal_values + anomaly_values
            title = f"System Metrics: {scenario_name}"
            y_label = "Metric (%)"
            threshold = 80
        
        # Create Plotly figure
        fig = go.Figure()
        
        # Add normal region
        fig.add_trace(go.Scatter(
            x=times[:30],
            y=data[:30],
            mode='lines',
            name='Normal',
            line=dict(color='#10b981', width=3),
            fill='tozeroy',
            fillcolor='rgba(16, 185, 129, 0.1)'
        ))
        
        # Add anomaly region
        fig.add_trace(go.Scatter(
            x=times[30:],
            y=data[30:],
            mode='lines',
            name='Anomaly',
            line=dict(color='#ef4444', width=3)
        ))
        
        # Add threshold line
        fig.add_hline(y=threshold, line_dash="dash", 
                     line_color="#f59e0b",
                     annotation_text="Alert Threshold",
                     annotation_position="top right")
        
        # Update layout - FIXED: Simplified for Gradio compatibility
        fig.update_layout(
            title={
                'text': title,
                'font': dict(size=18, color='#1e293b', family="Arial, sans-serif"),
                'x': 0.5
            },
            xaxis_title="Time",
            yaxis_title=y_label,
            height=300,
            margin=dict(l=40, r=20, t=50, b=40),
            plot_bgcolor='white',
            paper_bgcolor='white',
            showlegend=True,
            hovermode='x unified'
        )
        
        logger.info(f"βœ… Created telemetry plot for {scenario_name}")
        return fig
        
    except Exception as e:
        logger.error(f"Error creating telemetry plot: {e}")
        # Return a simple valid Plotly figure as fallback
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', name='Fallback'))
        fig.update_layout(
            title=f"Telemetry: {scenario_name}",
            height=300,
            plot_bgcolor='white'
        )
        return fig

def create_simple_impact_plot(scenario_name: str, is_real_arf: bool = True) -> go.Figure:
    """
    FIXED: Enhanced for Gradio compatibility
    """
    try:
        # Impact values based on scenario
        impact_values = {
            "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
        }
        
        impact = impact_values.get(scenario_name, 5000)
        
        # Create gauge chart - FIXED: Enhanced for Gradio
        fig = go.Figure(go.Indicator(
            mode="gauge+number",
            value=impact,
            domain={'x': [0, 1], 'y': [0, 1]},
            title={
                'text': f"Revenue Impact: ${impact:,}/hour",
                'font': dict(size=16, family="Arial, sans-serif")
            },
            number={
                'prefix': "$", 
                'suffix': "/hour",
                'font': dict(size=28, family="Arial, sans-serif")
            },
            gauge={
                'axis': {'range': [None, impact * 1.2], 'tickwidth': 1},
                'bar': {'color': "#ef4444"},
                'bgcolor': "white",
                'borderwidth': 2,
                'bordercolor': "gray",
                'steps': [
                    {'range': [0, impact * 0.3], 'color': '#10b981'},
                    {'range': [impact * 0.3, impact * 0.7], 'color': '#f59e0b'},
                    {'range': [impact * 0.7, impact], 'color': '#ef4444'}
                ],
                'threshold': {
                    'line': {'color': "black", 'width': 4},
                    'thickness': 0.75,
                    'value': impact
                }
            }
        ))
        
        # Update layout - FIXED: Enhanced for Gradio
        fig.update_layout(
            height=400,
            margin=dict(l=30, r=30, t=70, b=30),
            paper_bgcolor='white',
            font=dict(family="Arial, sans-serif")
        )
        
        logger.info(f"βœ… Created impact plot for {scenario_name}")
        return fig
        
    except Exception as e:
        logger.error(f"Error creating impact plot: {e}")
        # Return a simple valid gauge as fallback
        fig = go.Figure(go.Indicator(
            mode="gauge",
            value=0,
            title={'text': "Impact (fallback)"}
        ))
        fig.update_layout(height=400)
        return fig

def create_empty_plot(title: str, is_real_arf: bool = True) -> go.Figure:
    """
    FIXED: Enhanced for Gradio compatibility
    """
    try:
        fig = go.Figure()
        
        # Add text annotation - FIXED: Enhanced
        fig.add_annotation(
            x=0.5, y=0.5,
            text=title,
            showarrow=False,
            font=dict(size=18, color="#64748b", family="Arial, sans-serif"),
            xref="paper",
            yref="paper"
        )
        
        # Add boundary indicator if needed
        if is_real_arf:
            fig.add_annotation(
                x=0.02, y=0.98,
                text="βœ… REAL ARF",
                showarrow=False,
                font=dict(size=12, color="#10b981", family="Arial, sans-serif"),
                xref="paper",
                yref="paper",
                bgcolor="white",
                bordercolor="#10b981",
                borderwidth=1,
                borderpad=4
            )
        
        fig.update_layout(
            title={
                'text': "Visualization Placeholder",
                'font': dict(size=14, color="#94a3b8", family="Arial, sans-serif")
            },
            height=300,
            plot_bgcolor='white',
            paper_bgcolor='white',
            xaxis={'visible': False},
            yaxis={'visible': False},
            margin=dict(l=20, r=20, t=50, b=20)
        )
        
        return fig
        
    except Exception as e:
        logger.error(f"Error creating empty plot: {e}")
        # Ultra-simple fallback
        fig = go.Figure()
        fig.update_layout(height=300)
        return fig

# ===========================================
# ARF OSS UI ADAPTER - DOCTRINALLY PURE IMPLEMENTATION
# ===========================================

def transform_arf_output_for_ui(raw_result: dict, scenario_name: str) -> dict:
    """
    TRANSLATOR FUNCTION - NOT AN ANALYST
    
    Extracts existing intelligence from real ARF OSS output and transforms
    to UI-expected format. Does not compute, infer, or enhance.
    
    Rules:
    1. Source of truth: raw_result["oss_analysis"]["analysis"] 
    2. Extract only what exists
    3. Derive UI fields mechanically from existing data
    4. Never invent intelligence
    5. Defaults must be visibly conservative, not plausible
    6. Status must reflect contribution, not invocation
    
    Returns: UI-compatible dict with populated analysis and agents fields
    """
    
    # ===================================================
    # STEP 1: DETERMINE INPUT MODE AND SOURCE DATA
    # ===================================================
    
    # Mode 1: Real OSS Mode (has oss_analysis)
    if "oss_analysis" in raw_result and raw_result["oss_analysis"]:
        oss_analysis = raw_result["oss_analysis"]
        source_analysis = oss_analysis.get("analysis", {}) if isinstance(oss_analysis, dict) else {}
        is_real_oss = True
        
    # Mode 2: Mock/Fallback Mode (already has analysis at root)
    elif "analysis" in raw_result and raw_result["analysis"]:
        source_analysis = raw_result["analysis"]
        is_real_oss = False
        
    # Mode 3: Error/Failure Mode
    else:
        # Return minimal UI-safe structure to prevent UI breakage
        return {
            "status": raw_result.get("status", "error"),
            "scenario": scenario_name,
            "arf_version": raw_result.get("arf_version", "3.3.9"),
            "analysis": {
                "detected": False,
                "confidence": 0,  # VISIBLY CONSERVATIVE
                "similar_incidents": 0,  # VISIBLY CONSERVATIVE
                "healing_intent_created": False,
                "recommended_action": "Check OSS analysis output",
                "estimated_recovery": "Unknown"  # VISIBLY CONSERVATIVE
            },
            "agents": {
                "detection": {"status": "error", "confidence": 0},
                "recall": {"status": "error", "similar_incidents": 0},
                "decision": {"status": "error", "healing_intent_created": False}
            },
            "boundary_note": "OSS analysis output malformed",
            "installation": {
                "oss_installed": True,
                "version": "3.3.9",
                "edition": "oss"
            }
        }
    
    # ===================================================
    # STEP 2: EXTRACT ANALYSIS DATA (SOURCE OF TRUTH ONLY)
    # ===================================================
    
    # Extract detection data - MUST EXIST IN SOURCE
    detection_data = source_analysis.get("detection", {}) if isinstance(source_analysis, dict) else {}
    recall_data = source_analysis.get("recall", {}) if isinstance(source_analysis, dict) else {}
    decision_data = source_analysis.get("decision", {}) if isinstance(source_analysis, dict) else {}
    
    # ===================================================
    # STEP 3: BUILD UI ANALYSIS (DERIVED, NOT INFERRED)
    # ===================================================
    
    # DOCTRINALLY PURE: detection only when OSS explicitly signals it
    detected = False
    if isinstance(detection_data, dict):
        if "anomaly_detected" in detection_data:
            detected = bool(detection_data["anomaly_detected"])
        elif "detected" in detection_data:
            detected = bool(detection_data["detected"])
    
    # CORRECTED: confidence = 0 if not in source (visibly conservative)
    confidence = 0  # VISIBLY CONSERVATIVE DEFAULT
    # Confidence must come from detection if anomaly detected
    if detected and isinstance(detection_data, dict) and "confidence" in detection_data:
        confidence = detection_data["confidence"]
    elif isinstance(decision_data, dict) and "confidence" in decision_data:
        confidence = decision_data["confidence"]
    
    # CORRECTED: similar_incidents = 0 if not in source (visibly conservative)
    similar_incidents = 0  # VISIBLY CONSERVATIVE DEFAULT
    if isinstance(recall_data, dict) and "results" in recall_data:
        if isinstance(recall_data["results"], list):
            similar_incidents = len(recall_data["results"])
    elif "similar_incidents" in recall_data:
        similar_incidents = recall_data["similar_incidents"]
    
    # DOCTRINALLY PURE: healing intent only when explicitly true in OSS output
    healing_intent_created = False
    if isinstance(decision_data, dict):
        # Healing intent exists if explicitly marked OR an action is present
        healing_intent_created = bool(
            decision_data.get("healing_intent_created", False)
            or decision_data.get("action")
            or decision_data.get("recommended_action")
        )
    
    # Rule: recommended_action = pass through existing decision action text
    recommended_action = "No actionable intelligence found"  # VISIBLY CONSERVATIVE
    if isinstance(decision_data, dict):
        if "action" in decision_data:
            recommended_action = decision_data["action"]
        elif "recommended_action" in decision_data:
            recommended_action = decision_data["recommended_action"]
    
    # CORRECTED: estimated_recovery = "Unknown" (do not calculate or imply)
    estimated_recovery = "Unknown"
    
    # ===================================================
    # STEP 4: BUILD UI AGENTS (CONTRIBUTION-BASED STATUS)
    # ===================================================
    
    # REFINED: Agent status reflects actual contribution, not mere invocation
    # Detection agent: "active" only if detection actually occurred
    detection_status = "active" if detected else "inactive"
    
    # Recall agent: "active" only if similar incidents were found
    recall_status = "active" if similar_incidents > 0 else "inactive"
    
    # Decision agent: "active" only if healing intent was created
    decision_status = "active" if healing_intent_created else "inactive"
    
    # Override status to "error" if OSS status is error
    if raw_result.get("status") == "error":
        detection_status = "error"
        recall_status = "error"
        decision_status = "error"
    
    # ===================================================
    # STEP 5: ASSEMBLE FINAL UI-COMPATIBLE RESULT
    # ===================================================
    
    result = {
        "status": raw_result.get("status", "success"),
        "scenario": raw_result.get("scenario", scenario_name),
        "arf_version": raw_result.get("arf_version", "3.3.9"),
        "analysis": {
            "detected": detected,
            "confidence": confidence,
            "similar_incidents": similar_incidents,
            "healing_intent_created": healing_intent_created,
            "recommended_action": recommended_action,
            "estimated_recovery": estimated_recovery
        },
        "agents": {
            "detection": {
                "status": detection_status,
                "confidence": confidence if detection_status == "active" else 0
            },
            "recall": {
                "status": recall_status,
                "similar_incidents": similar_incidents if recall_status == "active" else 0
            },
            "decision": {
                "status": decision_status,
                "healing_intent_created": healing_intent_created if decision_status == "active" else False
            }
        },
        "boundary_note": raw_result.get("boundary_note", 
            "Real ARF OSS 3.3.9 analysis complete β†’ Ready for Enterprise execution"),
        "installation": {
            "oss_installed": True,
            "version": "3.3.9",
            "edition": "oss"
        }
    }
    
    # Preserve original oss_analysis for debugging (optional)
    if is_real_oss:
        result["_original_oss_analysis"] = raw_result.get("oss_analysis")
    
    return result
    
# ===========================================
# UPDATED: run_true_arf_analysis() - DOCTRINALLY PURE
# ===========================================

@AsyncRunner.async_to_sync
async def run_true_arf_analysis(scenario_name: str) -> tuple:
    """
    DOCTRINALLY PURE VERSION: Adapter transforms ARF OSS output with epistemic honesty
    Returns exactly 5 values as expected by UI:
    1. detection_html (HTML string)
    2. recall_html (HTML string)
    3. decision_html (HTML string)
    4. oss_results_dict (Python dict for JSON display)
    5. incident_df (DataFrame for Gradio DataFrame component)
    """
    
    components = get_components()
    installation = get_installation_status()
    boundaries = BoundaryManager.get_system_boundaries()
    
    logger.info(f"πŸ” Running True ARF analysis for: {scenario_name}")
    
    try:
        # Get orchestrator
        orchestrator = components["DemoOrchestrator"]()
        
        # Get scenario data
        scenarios = components["INCIDENT_SCENARIOS"]
        scenario_data = scenarios.get(scenario_name, {})
        
        # ======================================================
        # DOCTRINAL FIX POINT: CALL REAL ARF OSS
        # ======================================================
        raw_result = await orchestrator.analyze_incident(scenario_name, scenario_data)
        
        # ======================================================
        # DOCTRINAL ADAPTER: TRANSFORM WITH EPISTEMIC HONESTY
        # ======================================================
        transformed_result = transform_arf_output_for_ui(raw_result, scenario_name)
        
        # ======================================================
        # EXISTING UI INTEGRATION (PRESERVED)
        # ======================================================
        # Add to audit trail
        get_audit_manager().add_incident(scenario_name, transformed_result)
        
        # Create HTML for active agents using transformed result
        boundary_color = boundaries["oss"]["color"]
        
        # Extract data from transformed result
        analysis = transformed_result.get("analysis", {})
        agents = transformed_result.get("agents", {})
        
        # Get data for HTML templates
        confidence = analysis.get("confidence", 0)  # CONSERVATIVE DEFAULT
        similar_incidents = analysis.get("similar_incidents", 0)  # CONSERVATIVE DEFAULT
        detection_agent = agents.get("detection", {})
        recall_agent = agents.get("recall", {})
        decision_agent = agents.get("decision", {})
        
        # Detection Agent HTML - Now truthfully reflects actual detection
        detection_status = detection_agent.get("status", "inactive")
        detection_status_text = detection_status.capitalize()
        
        # REFINED: Badge text reflects actual contribution state
        if detection_status == "active":
            detection_badge = "DETECTED"
            confidence_text = f"Anomaly detected with {confidence}% confidence"
        elif detection_status == "inactive":
            detection_badge = "ANALYZING"
            confidence_text = "No anomaly signal found"
        else:
            detection_badge = "ERROR"
            confidence_text = "Detection analysis failed"
        
        detection_html = f"""
        <div style="border: 2px solid {boundary_color}; border-radius: 14px; padding: 18px; 
                   background: linear-gradient(135deg, {boundary_color}10 0%, #ffffff 100%); 
                   text-align: center; flex: 1; margin: 5px; min-height: 180px;">
            <div style="font-size: 32px; margin-bottom: 10px; color: {boundary_color};">πŸ•΅οΈβ€β™‚οΈ</div>
            <div style="width: 100%;">
                <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Detection Process</h4>
                <p style="font-size: 13px; color: #64748b; margin-bottom: 12px; line-height: 1.4;">
                    {confidence_text}
                </p>
                <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
                    <span style="font-size: 11px; padding: 3px 8px; background: {boundary_color}20; 
                               border-radius: 6px; color: {boundary_color}; font-weight: 500;">
                        Status: {detection_status_text}
                    </span>
                </div>
                <div style="display: inline-block; padding: 5px 14px; background: {boundary_color}; 
                           border-radius: 20px; font-size: 12px; font-weight: bold; color: white; 
                           text-transform: uppercase; letter-spacing: 0.5px;">
                    {detection_badge}
                </div>
            </div>
        </div>
        """
        
        # Recall Agent HTML - Now truthfully reflects actual recall
        recall_status = recall_agent.get("status", "inactive")
        recall_status_text = recall_status.capitalize()
        
        # REFINED: Badge text reflects actual contribution state
        if recall_status == "active":
            recall_badge = "RECALLED"
            recall_text = f"Found {similar_incidents} similar incident{'s' if similar_incidents != 1 else ''}"
        elif recall_status == "inactive":
            recall_badge = "SEARCHING"
            recall_text = "No similar incidents found"
        else:
            recall_badge = "ERROR"
            recall_text = "Recall analysis failed"
        
        recall_html = f"""
        <div style="border: 2px solid {boundary_color}; border-radius: 14px; padding: 18px; 
                   background: linear-gradient(135deg, {boundary_color}10 0%, #ffffff 100%); 
                   text-align: center; flex: 1; margin: 5px; min-height: 180px;">
            <div style="font-size: 32px; margin-bottom: 10px; color: {boundary_color};">🧠</div>
            <div style="width: 100%;">
                <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Recall Process</h4>
                <p style="font-size: 13px; color: #64748b; margin-bottom: 12px; line-height: 1.4;">
                    {recall_text}
                </p>
                <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
                    <span style="font-size: 11px; padding: 3px 8px; background: {boundary_color}20; 
                               border-radius: 6px; color: {boundary_color}; font-weight: 500;">
                        Status: {recall_status_text}
                    </span>
                </div>
                <div style="display: inline-block; padding: 5px 14px; background: {boundary_color}; 
                           border-radius: 20px; font-size: 12px; font-weight: bold; color: white; 
                           text-transform: uppercase; letter-spacing: 0.5px;">
                    {recall_badge}
                </div>
            </div>
        </div>
        """
        
        # Decision Agent HTML - Now truthfully reflects actual decision
        decision_status = decision_agent.get("status", "inactive")
        decision_status_text = decision_status.capitalize()
        
        # REFINED: Badge text reflects actual contribution state
        if decision_status == "active":
            decision_badge = "DECIDED"
            decision_text = analysis.get('recommended_action', 'Action recommended')
        elif decision_status == "inactive":
            decision_badge = "EVALUATING"
            decision_text = "No action recommended"
        else:
            decision_badge = "ERROR"
            decision_text = "Decision analysis failed"
        
        decision_html = f"""
        <div style="border: 2px solid {boundary_color}; border-radius: 14px; padding: 18px; 
                   background: linear-gradient(135deg, {boundary_color}10 0%, #ffffff 100%); 
                   text-align: center; flex: 1; margin: 5px; min-height: 180px;">
            <div style="font-size: 32px; margin-bottom: 10px; color: {boundary_color};">🎯</div>
            <div style="width: 100%;">
                <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Decision Process</h4>
                <p style="font-size: 13px; color: #64748b; margin-bottom: 12px; line-height: 1.4;">
                    {decision_text}
                </p>
                <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
                    <span style="font-size: 11px; padding: 3px 8px; background: {boundary_color}20; 
                               border-radius: 6px; color: {boundary_color}; font-weight: 500;">
                        Status: {decision_status_text}
                    </span>
                </div>
                <div style="display: inline-block; padding: 5px 14px; background: {boundary_color}; 
                           border-radius: 20px; font-size: 12px; font-weight: bold; color: white; 
                           text-transform: uppercase; letter-spacing: 0.5px;">
                    {decision_badge}
                </div>
            </div>
        </div>
        """
        
        # OSS Results Dict for JSON display (using transformed result)
        oss_results_dict = transformed_result
        
        # Incident DataFrame
        incident_df = get_audit_manager().get_incident_dataframe()
        
        logger.info(f"βœ… True ARF analysis complete for {scenario_name}")
        logger.info(f"   Detection: {'ACTIVE' if detection_status == 'active' else 'INACTIVE'} (confidence: {confidence})")
        logger.info(f"   Recall: {'ACTIVE' if recall_status == 'active' else 'INACTIVE'} (incidents: {similar_incidents})")
        logger.info(f"   Decision: {'ACTIVE' if decision_status == 'active' else 'INACTIVE'}")
        
        return detection_html, recall_html, decision_html, oss_results_dict, incident_df
        
    except Exception as e:
        logger.error(f"True ARF analysis failed: {e}")
        
        # Return error state with proper types
        error_html = f"""
        <div style="border: 2px solid #ef4444; border-radius: 14px; padding: 18px; 
                   background: linear-gradient(135deg, #fef2f2 0%, #ffffff 100%); 
                   text-align: center; flex: 1; margin: 5px; min-height: 180px;">
            <div style="font-size: 32px; margin-bottom: 10px; color: #ef4444;">❌</div>
            <div style="width: 100%;">
                <h4 style="margin: 0 0 8px 0; font-size: 16px; color: #1e293b;">Analysis Error</h4>
                <p style="font-size: 13px; color: #64748b; margin-bottom: 12px; line-height: 1.4;">
                    Failed to analyze incident
                </p>
                <div style="display: flex; justify-content: space-around; margin-bottom: 12px;">
                    <span style="font-size: 11px; padding: 3px 8px; background: #ef4444; 
                               border-radius: 6px; color: white; font-weight: 500;">
                        Status: Error
                    </span>
                </div>
            </div>
        </div>
        """
        
        error_dict = {
            "status": "error",
            "error": str(e),
            "scenario": scenario_name,
            "arf_version": "3.3.9",
            "analysis": {
                "detected": False,
                "confidence": 0,
                "similar_incidents": 0,
                "healing_intent_created": False,
                "recommended_action": "Check ARF installation",
                "estimated_recovery": "Unknown"
            },
            "agents": {
                "detection": {"status": "error", "confidence": 0},
                "recall": {"status": "error", "similar_incidents": 0},
                "decision": {"status": "error", "healing_intent_created": False}
            }
        }
        
        # Return empty DataFrame on error
        error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([
            {"Error": "Analysis Failed", "Message": str(e)}
        ])
        
        return error_html, error_html, error_html, error_dict, error_df

# ===========================================
# IMPORT MODULAR COMPONENTS - FIXED: Added MockEnhancedROICalculator
# ===========================================
def import_components() -> Dict[str, Any]:
    """Safely import all components with proper error handling - FIXED: Added mock ROI calculator"""
    components = {
        "all_available": False,
        "error": None,
        "get_styles": lambda: "",
        "show_boundaries": settings.show_boundaries,
    }
    
    try:
        logger.info("Starting component import...")
        
        # First, import gradio
        import gradio as gr
        components["gr"] = gr
        
        # Import UI styles
        from ui.styles import get_styles
        components["get_styles"] = get_styles
        
        # Import UI components - IMPORTANT: Now includes create_realism_panel AND update_performance_metrics
        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, create_realism_panel, update_performance_metrics  # Added update_performance_metrics
        )
        
        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,
            "create_realism_panel": create_realism_panel,
            "update_performance_metrics": update_performance_metrics  # Added for dynamic metrics
        })
        
        # Import scenarios
        from demo.scenarios import INCIDENT_SCENARIOS
        components["INCIDENT_SCENARIOS"] = INCIDENT_SCENARIOS
        
        # Try to import TrueARFOrchestrator (renamed for version consistency)
        try:
            from core.true_arf_orchestrator import TrueARFOrchestrator
            components["DemoOrchestrator"] = TrueARFOrchestrator
        except ImportError:
            # Fallback to old name for compatibility during transition
            try:
                from core.true_arf_orchestrator import TrueARF337Orchestrator
                components["DemoOrchestrator"] = TrueARF337Orchestrator
                logger.warning("⚠️ Using TrueARF337Orchestrator - rename to TrueARFOrchestrator for version consistency")
            except ImportError:
                # Fallback to real ARF integration
                try:
                    from core.real_arf_integration import RealARFIntegration
                    components["DemoOrchestrator"] = RealARFIntegration
                except ImportError:
                    # Create a minimal mock orchestrator
                    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
        
        # FIXED: EnhancedROICalculator with proper mock fallback
        try:
            from core.calculators import EnhancedROICalculator
            components["EnhancedROICalculator"] = EnhancedROICalculator()
            logger.info("βœ… Real EnhancedROICalculator loaded")
        except ImportError:
            # Create comprehensive mock ROI calculator
            class MockEnhancedROICalculator:
                """Mock ROI calculator for demo purposes - FIXED to prevent KeyError"""
                
                def calculate_comprehensive_roi(self, scenario_name=None, monthly_incidents=15, team_size=5, **kwargs):
                    """Calculate comprehensive ROI metrics with realistic mock data"""
                    from datetime import datetime
                    
                    # Mock ROI calculation with realistic values
                    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
                    }
                    
                    impact_per_incident = impact_map.get(scenario_name or "Cache Miss Storm", 5000)
                    annual_impact = impact_per_incident * monthly_incidents * 12
                    potential_savings = int(annual_impact * 0.82)
                    enterprise_cost = 625000
                    roi_multiplier = round(potential_savings / enterprise_cost, 1)
                    payback_months = round((enterprise_cost / (potential_savings / 12)), 1)
                    
                    return {
                        "status": "βœ… Calculated Successfully",
                        "scenario": scenario_name or "Cache Miss Storm",
                        "timestamp": datetime.now().isoformat(),
                        "calculator": "MockEnhancedROICalculator",
                        "summary": {
                            "your_annual_impact": f"${annual_impact:,}",
                            "potential_savings": f"${potential_savings:,}",
                            "enterprise_cost": f"${enterprise_cost:,}",
                            "roi_multiplier": f"{roi_multiplier}Γ—",
                            "payback_months": f"{payback_months}",
                            "annual_roi_percentage": f"{int((potential_savings - enterprise_cost) / enterprise_cost * 100)}%",
                            "boundary_context": "Based on OSS analysis + simulated Enterprise execution"
                        },
                        "breakdown": {
                            "direct_cost_savings": f"${int(potential_savings * 0.7):,}",
                            "productivity_gains": f"${int(potential_savings * 0.2):,}",
                            "risk_reduction": f"${int(potential_savings * 0.1):,}"
                        },
                        "annual_projection": {
                            "incidents_prevented": monthly_incidents * 12,
                            "annual_savings": f"${potential_savings:,}",
                            "roi": f"{roi_multiplier}Γ—"
                        },
                        "notes": [
                            "πŸ“Š ROI calculation using mock data",
                            "πŸ’‘ Real enterprise ROI includes additional factors",
                            "πŸ”’ Full ROI requires Enterprise edition",
                            f"πŸ“ˆ Based on {monthly_incidents} incidents/month"
                        ]
                    }
                
                def get_roi_visualization_data(self):
                    """Get data for ROI visualization"""
                    return {
                        "labels": ["Direct Savings", "Productivity", "Risk Reduction", "Upsell"],
                        "values": [65, 20, 10, 5],
                        "colors": ["#10b981", "#3b82f6", "#8b5cf6", "#f59e0b"]
                    }
            
            components["EnhancedROICalculator"] = MockEnhancedROICalculator()
            logger.info("βœ… Mock EnhancedROICalculator created (preventing KeyError)")
        
        # Try to import visualization engine
        try:
            from core.visualizations import EnhancedVisualizationEngine
            components["EnhancedVisualizationEngine"] = EnhancedVisualizationEngine()
        except ImportError:
            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()
        
        components["all_available"] = True
        components["error"] = None
        logger.info("βœ… Successfully imported all modular components including update_performance_metrics")
        
    except Exception as e:
        logger.error(f"❌ IMPORT ERROR: {e}")
        components["error"] = str(e)
        components["all_available"] = False
        
        # Ensure we have minimal components
        if "gr" not in components:
            import gradio as gr
            components["gr"] = gr
        
        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"
                }
            }
        
        # Ensure EnhancedROICalculator exists
        if "EnhancedROICalculator" not in components:
            class MinimalROICalculator:
                def calculate_comprehensive_roi(self, **kwargs):
                    return {
                        "status": "βœ… Minimal ROI Calculation",
                        "summary": {"roi_multiplier": "5.2Γ—"}
                    }
            components["EnhancedROICalculator"] = MinimalROICalculator()
        
        # Ensure update_performance_metrics exists
        if "update_performance_metrics" not in components:
            def fallback_performance_metrics(scenario_name: str):
                """Fallback function if the real one fails"""
                logger.warning(f"Using fallback performance metrics for {scenario_name}")
                return (
                    """<div style="border: 1px solid #e2e8f0; border-radius: 12px; padding: 18px; background: white; margin: 8px; text-align: center; flex: 1; min-width: 140px; border-left: 4px solid #3b82f6;">
                        <div style="font-size: 28px; margin-bottom: 10px;">⏱️</div>
                        <div>
                            <h4 style="margin: 0 0 8px 0; font-size: 14px; color: #64748b; font-weight: 600;">Detection Time</h4>
                            <p style="font-size: 28px; font-weight: bold; color: #1e40af; margin: 8px 0;">42s</p>
                            <p style="font-size: 12px; color: #64748b; margin: 0;">↓ 90% faster than average</p>
                        </div>
                    </div>""",
                    """<div style="border: 1px solid #e2e8f0; border-radius: 12px; padding: 18px; background: white; margin: 8px; text-align: center; flex: 1; min-width: 140px; border-left: 4px solid #10b981;">
                        <div style="font-size: 28px; margin-bottom: 10px;">⚑</div>
                        <div>
                            <h4 style="margin: 0 0 8px 0; font-size: 14px; color: #64748b; font-weight: 600;">Mean Time to Resolve</h4>
                            <p style="font-size: 28px; font-weight: bold; color: #10b981; margin: 8px 0;">14m</p>
                            <p style="font-size: 12px; color: #64748b; margin: 0;">↓ 70% faster than manual</p>
                        </div>
                    </div>""",
                    """<div style="border: 1px solid #e2e8f0; border-radius: 12px; padding: 18px; background: white; margin: 8px; text-align: center; flex: 1; min-width: 140px; border-left: 4px solid #8b5cf6;">
                        <div style="font-size: 28px; margin-bottom: 10px;">πŸ€–</div>
                        <div>
                            <h4 style="margin: 0 0 8px 0; font-size: 14px; color: #64748b; font-weight: 600;">Auto-Heal Rate</h4>
                            <p style="font-size: 28px; font-weight: bold; color: #8b5cf6; margin: 8px 0;">78.9%</p>
                            <p style="font-size: 12px; color: #64748b; margin: 0;">↑ 5.0Γ— industry average</p>
                        </div>
                    </div>""",
                    """<div style="border: 1px solid #e2e8f0; border-radius: 12px; padding: 18px; background: white; margin: 8px; text-align: center; flex: 1; min-width: 140px; border-left: 4px solid #f59e0b;">
                        <div style="font-size: 28px; margin-bottom: 10px;">πŸ’°</div>
                        <div>
                            <h4 style="margin: 0 0 8px 0; font-size: 14px; color: #64748b; font-weight: 600;">Cost Saved</h4>
                            <p style="font-size: 28px; font-weight: bold; color: #f59e0b; margin: 8px 0;">$7.2K</p>
                            <p style="font-size: 12px; color: #64748b; margin: 0;">Per incident avoided</p>
                        </div>
                    </div>"""
                )
            components["update_performance_metrics"] = fallback_performance_metrics
    
    return components

_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 - FIXED: Returns DataFrames instead of HTML
# ===========================================
class AuditTrailManager:
    """Enhanced audit trail manager with boundary tracking - FIXED to return DataFrames"""
    
    def __init__(self):
        self.executions = []
        self.incidents = []
        self.boundary_crossings = []
        self.max_items = settings.max_history_items
    
    def add_execution(self, scenario_name: str, mode: str, result: Dict):
        """Add an execution record"""
        record = {
            "timestamp": datetime.datetime.now().isoformat(),
            "scenario": scenario_name,
            "mode": mode,
            "result": result,
            "boundary_context": "Enterprise execution simulated" if "simulated" in str(result) else "OSS advisory"
        }
        self.executions.insert(0, record)
        if len(self.executions) > self.max_items:
            self.executions = self.executions[:self.max_items]
        
        # Track boundary crossing
        if "enterprise" in mode.lower():
            self.boundary_crossings.append({
                "timestamp": record["timestamp"],
                "from": "OSS",
                "to": "Enterprise",
                "action": scenario_name
            })
        
        logger.info(f"πŸ“ Execution recorded: {scenario_name} ({mode})")
        return record
    
    def add_incident(self, scenario_name: str, analysis_result: Dict):
        """Add an incident analysis record"""
        record = {
            "timestamp": datetime.datetime.now().isoformat(),
            "scenario": scenario_name,
            "analysis": analysis_result,
            "boundary_context": analysis_result.get("boundary_note", "OSS analysis")
        }
        self.incidents.insert(0, record)
        if len(self.incidents) > self.max_items:
            self.incidents = self.incidents[:self.max_items]
        
        logger.info(f"πŸ“ Incident analysis recorded: {scenario_name}")
        return record
    
    def get_execution_dataframe(self) -> pd.DataFrame:
        """
        FIXED: Robust pandas DataFrame creation for Gradio DataFrame component
        """
        try:
            if not self.executions:
                # Return empty DataFrame with correct columns
                return pd.DataFrame(columns=[
                    "Execution ID", "Scenario", "Status", "Mode", 
                    "Start Time", "End Time", "Duration", "Boundary"
                ])
            
            # Build DataFrame from executions with safe access
            data = []
            for i, execution in enumerate(self.executions):
                try:
                    # Safe access to nested dictionaries
                    result = execution.get("result", {})
                    
                    # Execution ID - safe extraction with fallback
                    exec_id = result.get("execution_id", f"exec_{i:03d}")
                    
                    # Status determination with multiple fallbacks
                    status_text = "Unknown"
                    if isinstance(result, dict):
                        status_lower = str(result.get("status", "")).lower()
                        if "success" in status_lower:
                            status_text = "Success"
                        elif "failed" in status_lower or "error" in status_lower:
                            status_text = "Failed"
                        else:
                            # Check if there's an error key
                            if result.get("error"):
                                status_text = "Failed"
                            else:
                                status_text = "Success"
                    
                    # Mode extraction
                    mode = execution.get("mode", "unknown")
                    
                    # Scenario extraction
                    scenario = execution.get("scenario", "Unknown")
                    
                    # Timestamp formatting with validation
                    timestamp = execution.get("timestamp", "")
                    start_time = ""
                    if timestamp and len(timestamp) > 10:
                        try:
                            # Format: YYYY-MM-DD HH:MM:SS
                            start_time = timestamp[:19]
                        except Exception:
                            start_time = timestamp  # Fallback to raw string
                    
                    # End time extraction from telemetry
                    end_time = ""
                    telemetry = result.get("telemetry", {})
                    if telemetry:
                        end_timestamp = telemetry.get("end_time", "")
                        if end_timestamp and len(end_timestamp) > 10:
                            try:
                                end_time = end_timestamp[:19]
                            except Exception:
                                end_time = end_timestamp  # Fallback
                    
                    # Duration - mock or extract from execution
                    duration = "12m"  # Default mock duration
                    if telemetry and "estimated_duration" in telemetry:
                        duration = telemetry.get("estimated_duration", "12m")
                    
                    # Boundary context
                    boundary = execution.get("boundary_context", "Unknown")
                    
                    data.append({
                        "Execution ID": exec_id,
                        "Scenario": scenario,
                        "Status": status_text,
                        "Mode": mode,
                        "Start Time": start_time,
                        "End Time": end_time,
                        "Duration": duration,
                        "Boundary": boundary
                    })
                    
                except Exception as row_error:
                    logger.warning(f"Error processing execution row {i}: {row_error}")
                    # Add error row for debugging
                    data.append({
                        "Execution ID": f"error_{i}",
                        "Scenario": "Error",
                        "Status": "Failed",
                        "Mode": "error",
                        "Start Time": datetime.datetime.now().isoformat()[:19],
                        "End Time": "",
                        "Duration": "0m",
                        "Boundary": "Error processing"
                    })
            
            if not data:
                logger.warning("No valid execution data found, returning empty DataFrame")
                return pd.DataFrame(columns=[
                    "Execution ID", "Scenario", "Status", "Mode", 
                    "Start Time", "End Time", "Duration", "Boundary"
                ])
            
            # Create DataFrame
            df = pd.DataFrame(data)
            
            # Safe sorting - only if we have valid Start Time data
            if not df.empty and "Start Time" in df.columns:
                # Check if Start Time column has valid data
                valid_times = df["Start Time"].apply(
                    lambda x: isinstance(x, str) and len(x) > 0 and x != "None"
                )
                
                if valid_times.any():
                    try:
                        # Sort by time (newest first)
                        df = df.sort_values("Start Time", ascending=False)
                    except Exception as sort_error:
                        logger.warning(f"Could not sort DataFrame: {sort_error}")
                        # Keep unsorted if sorting fails
                else:
                    logger.debug("No valid timestamps for sorting")
            
            logger.info(f"βœ… Created execution DataFrame with {len(df)} rows")
            return df
            
        except Exception as e:
            logger.error(f"❌ Error creating execution DataFrame: {e}")
            # Return informative error DataFrame
            error_df = pd.DataFrame(columns=[
                "Error", "Message", "Timestamp"
            ]).from_records([{
                "Error": "DataFrame Creation Failed",
                "Message": str(e),
                "Timestamp": datetime.datetime.now().isoformat()[:19]
            }])
            return error_df
    
    def get_incident_dataframe(self) -> pd.DataFrame:
        """
        FIXED: Robust pandas DataFrame creation for Gradio DataFrame component
        """
        try:
            if not self.incidents:
                # Return empty DataFrame with correct columns
                return pd.DataFrame(columns=[
                    "Scenario", "Status", "Boundary", "Time", 
                    "Confidence", "Action", "Target"
                ])
            
            # Build DataFrame from incidents with safe access
            data = []
            for i, incident in enumerate(self.incidents):
                try:
                    # Safe extraction of basic fields
                    scenario = incident.get("scenario", "Unknown")
                    boundary = incident.get("boundary_context", "OSS analysis")
                    
                    # Analysis data extraction
                    analysis = incident.get("analysis", {})
                    
                    # Status determination
                    status = "Analyzed"
                    if isinstance(analysis, dict):
                        analysis_status = analysis.get("status", "").lower()
                        if analysis_status:
                            status = analysis_status.capitalize()
                        else:
                            # Fallback status determination
                            if analysis.get("error"):
                                status = "Error"
                            elif analysis.get("analysis") or analysis.get("oss_analysis"):
                                status = "Success"
                    
                    # Timestamp formatting
                    timestamp = incident.get("timestamp", "")
                    time_display = ""
                    if timestamp and len(timestamp) > 10:
                        try:
                            # Extract HH:MM:SS
                            time_display = timestamp[11:19]
                        except Exception:
                            time_display = timestamp[:8] if len(timestamp) >= 8 else timestamp
                    
                    # Extract healing intent details with multiple fallback paths
                    confidence = 0.85  # Default confidence
                    action = "Analysis"
                    target = "system"
                    
                    # Try multiple paths to find healing intent
                    healing_intent = None
                    
                    # Path 1: oss_analysis -> analysis -> decision
                    oss_analysis = analysis.get("oss_analysis", {})
                    if isinstance(oss_analysis, dict):
                        oss_analysis_inner = oss_analysis.get("analysis", {})
                        if isinstance(oss_analysis_inner, dict):
                            healing_intent = oss_analysis_inner.get("decision", {})
                    
                    # Path 2: direct analysis -> decision
                    if not healing_intent and isinstance(analysis.get("analysis", {}), dict):
                        healing_intent = analysis["analysis"].get("decision", {})
                    
                    # Path 3: direct healing_intent
                    if not healing_intent:
                        healing_intent = analysis.get("healing_intent", {})
                    
                    if healing_intent and isinstance(healing_intent, dict):
                        confidence = healing_intent.get("confidence", 0.85)
                        action = healing_intent.get("action", "Analysis")
                        target = healing_intent.get("target", "system")
                    
                    # Format confidence as percentage
                    confidence_display = f"{confidence * 100:.1f}%"
                    
                    data.append({
                        "Scenario": scenario,
                        "Status": status,
                        "Boundary": boundary,
                        "Time": time_display,
                        "Confidence": confidence_display,
                        "Action": action[:50],  # Limit action length
                        "Target": target[:30]   # Limit target length
                    })
                    
                except Exception as row_error:
                    logger.warning(f"Error processing incident row {i}: {row_error}")
                    # Add error row for debugging
                    data.append({
                        "Scenario": "Error",
                        "Status": "Failed",
                        "Boundary": "Error processing",
                        "Time": datetime.datetime.now().isoformat()[11:19],
                        "Confidence": "0.0%",
                        "Action": "Error",
                        "Target": "system"
                    })
            
            if not data:
                logger.warning("No valid incident data found, returning empty DataFrame")
                return pd.DataFrame(columns=[
                    "Scenario", "Status", "Boundary", "Time", 
                    "Confidence", "Action", "Target"
                ])
            
            # Create DataFrame
            df = pd.DataFrame(data)
            
            # Safe sorting - only if we have valid Time data
            if not df.empty and "Time" in df.columns:
                # Check if Time column has valid data
                valid_times = df["Time"].apply(
                    lambda x: isinstance(x, str) and len(x) > 0 and x != "None"
                )
                
                if valid_times.any():
                    try:
                        # Sort by time (newest first)
                        df = df.sort_values("Time", ascending=False)
                    except Exception as sort_error:
                        logger.warning(f"Could not sort incident DataFrame: {sort_error}")
                        # Keep unsorted if sorting fails
                else:
                    logger.debug("No valid timestamps for sorting in incident DataFrame")
            
            logger.info(f"βœ… Created incident DataFrame with {len(df)} rows")
            return df
            
        except Exception as e:
            logger.error(f"❌ Error creating incident DataFrame: {e}")
            # Return informative error DataFrame
            error_df = pd.DataFrame(columns=[
                "Error", "Message", "Timestamp"
            ]).from_records([{
                "Error": "DataFrame Creation Failed",
                "Message": str(e),
                "Timestamp": datetime.datetime.now().isoformat()[:19]
            }])
            return error_df
    
    def get_execution_table_html(self):
        """Legacy HTML method for backward compatibility"""
        if not self.executions:
            return """
            <div style="text-align: center; padding: 30px; color: #64748b;">
                <div style="font-size: 48px; margin-bottom: 10px;">πŸ“­</div>
                <h4 style="margin: 0 0 10px 0;">No executions yet</h4>
                <p style="margin: 0; font-size: 13px;">Run scenarios to see execution history</p>
            </div>
            """
        
        rows = []
        for i, exec in enumerate(self.executions[:10]):
            status = "βœ…" if "success" in exec["result"].get("status", "").lower() else "⚠️"
            boundary = exec["boundary_context"]
            boundary_color = "#10b981" if "OSS" in boundary else "#8b5cf6"
            
            rows.append(f"""
            <tr style="border-bottom: 1px solid #f1f5f9;">
                <td style="padding: 12px; font-size: 13px; color: #1e293b;">
                    {status} {exec["scenario"]}
                </td>
                <td style="padding: 12px; font-size: 13px; color: #64748b;">
                    {exec["mode"]}
                </td>
                <td style="padding: 12px; font-size: 13px;">
                    <div style="display: inline-block; padding: 4px 10px; background: {boundary_color}20; 
                               color: {boundary_color}; border-radius: 12px; font-size: 11px; font-weight: bold;">
                        {boundary}
                    </div>
                </td>
                <td style="padding: 12px; font-size: 13px; color: #94a3b8;">
                    {exec["timestamp"][11:19]}
                </td>
            </tr>
            """)
        
        return f"""
        <div style="border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead style="background: #f8fafc;">
                    <tr style="border-bottom: 2px solid #e2e8f0;">
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight: 600;">Scenario</th>
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight: 600;">Mode</th>
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight: 600;">Boundary</th>
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight: 600;">Time</th>
                    </tr>
                </thead>
                <tbody>
                    {''.join(rows)}
                </tbody>
            </table>
        </div>
        """
    
    def get_incident_table_html(self):
        """Legacy HTML method for backward compatibility"""
        if not self.incidents:
            return """
            <div style="text-align: center; padding: 30px; color: #64748b;">
                <div style="font-size: 48px; margin-bottom: 10px;">πŸ“­</div>
                <h4 style="margin: 0 0 10px 0;">No incidents analyzed yet</h4>
                <p style="margin: 0; font-size: 13px;">Run OSS analysis to see incident history</p>
            </div>
            """
        
        rows = []
        for i, incident in enumerate(self.incidents[:10]):
            scenario = incident["scenario"]
            analysis = incident["analysis"]
            boundary = incident["boundary_context"]
            boundary_color = "#10b981" if "OSS" in boundary else "#8b5cf6"
            
            rows.append(f"""
            <tr style="border-bottom: 1px solid #f1f5f9;">
                <td style="padding: 12px; font-size: 13px; color: #1e293b; font-weight: 500;">
                    {scenario}
                </td>
                <td style="padding: 12px; font-size: 13px; color: #64748b;">
                    {analysis.get('status', 'analyzed')}
                </td>
                <td style="padding: 12px; font-size: 13px;">
                    <div style="display: inline-block; padding: 4px 10px; background: {boundary_color}20; 
                               color: {boundary_color}; border-radius: 12px; font-size: 11px; font-weight: bold;">
                        {boundary}
                    </div>
                </td>
                <td style="padding: 12px; font-size: 13px; color: #94a3b8;">
                    {incident["timestamp"][11:19]}
                </td>
            </tr>
            """)
        
        return f"""
        <div style="border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden;">
            <table style="width: 100%; border-collapse: collapse;">
                <thead style="background: #f8fafc;">
                    <tr style="border-bottom: 2px solid #e2e8f0;">
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight: 600;">Scenario</th>
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight: 600;">Status</th>
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight: 600;">Boundary</th>
                        <th style="padding: 15px; text-align: left; font-size: 13px; color: #475569; font-weight=600;">Time</th>
                    </tr>
                </thead>
                <tbody>
                    {''.join(rows)}
                </tbody>
            </table>
        </div>
        """
    
    def clear(self):
        """Clear all audit trails"""
        self.executions = []
        self.incidents = []
        self.boundary_crossings = []
        logger.info("🧹 Audit trail cleared")
    
    def export_json(self):
        """Export audit trail as JSON"""
        return {
            "executions": self.executions,
            "incidents": self.incidents,
            "boundary_crossings": self.boundary_crossings,
            "export_time": datetime.datetime.now().isoformat(),
            "version": "3.3.9",
            "architecture": "OSS advises β†’ Enterprise executes"
        }

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
# ===========================================
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:
        if "summary" in roi_result and "roi_multiplier" in roi_result["summary"]:
            roi_str = roi_result["summary"]["roi_multiplier"]
            if "Γ—" in roi_str:
                return float(roi_str.replace("Γ—", ""))
            return float(roi_str)
        return 5.2
    except Exception as e:
        logger.warning(f"Failed to extract ROI multiplier: {e}")
        return 5.2

# ===========================================
# SURGICAL FIX: update_scenario_display() - ENHANCED WITH REALISM PANEL
# ===========================================
def update_scenario_display(scenario_name: str) -> tuple:
    """
    ENHANCED: Returns Plotly figures AND realism panel
    Returns 5 values: (scenario_card_html, telemetry_fig, impact_fig, timeline_fig, realism_html)
    """
    components = get_components()
    scenarios = components["INCIDENT_SCENARIOS"]
    
    scenario = scenarios.get(scenario_name, {
        "component": "Unknown System",
        "severity": "MEDIUM",
        "business_impact": {"revenue_loss_per_hour": 5000},
        "boundary_note": "Scenario not found"
    })
    
    # Create scenario card HTML (MODERN: Use Card component if available)
    if get_feature_flags().get('modern_ui', False) and MODERN_UI_AVAILABLE:
        # Use modern Card component
        scenario_card_html = Card.create(
            title=scenario_name,
            content=f"""
            <div style="margin: 15px 0;">
                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                    <div style="padding: 4px 12px; background: var(--color-primary); color: white; 
                               border-radius: 12px; font-size: 12px; font-weight: bold;">
                        {scenario["severity"]} SEVERITY
                    </div>
                    <div style="font-size: 13px; color: var(--text-secondary);">
                        {scenario["component"]}
                    </div>
                </div>
                
                <div style="font-size: 14px; color: var(--text-secondary); line-height: 1.5;">
                    <strong>Boundary Context:</strong> {scenario.get('boundary_note', 'OSS analyzes, Enterprise executes')}
                </div>
            </div>
            """,
            footer=f"Revenue Impact: ${scenario['business_impact'].get('revenue_loss_per_hour', get_scenario_impact(scenario_name)):,}/hour"
        )
    else:
        # Legacy scenario card
        severity_colors = {
            "HIGH": "#ef4444",
            "MEDIUM": "#f59e0b",
            "LOW": "#10b981"
        }
        severity_color = severity_colors.get(scenario["severity"], "#64748b")
        
        impact = scenario["business_impact"].get("revenue_loss_per_hour", get_scenario_impact(scenario_name))
        
        scenario_card_html = f"""
        <div style="border: 1px solid {severity_color}; border-radius: 14px; padding: 20px; 
                    background: linear-gradient(135deg, {severity_color}10 0%, #ffffff 100%);">
            
            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 15px;">
                <div>
                    <h3 style="margin: 0 0 8px 0; font-size: 18px; color: #1e293b; font-weight: 700;">
                        {scenario_name}
                    </h3>
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <div style="padding: 4px 12px; background: {severity_color}; color: white; 
                                   border-radius: 12px; font-size: 12px; font-weight: bold;">
                            {scenario["severity"]} SEVERITY
                        </div>
                        <div style="font-size: 13px; color: #64748b;">
                            {scenario["component"]}
                        </div>
                    </div>
                </div>
                
                <div style="text-align: right;">
                    <div style="font-size: 28px; font-weight: 700; color: {severity_color};">
                        ${impact:,}
                    </div>
                    <div style="font-size: 12px; color: #64748b;">
                        Revenue Loss/Hour
                    </div>
                </div>
            </div>
            
            <!-- Impact breakdown -->
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #f1f5f9;">
                <div style="font-size: 14px; color: #475569; font-weight: 600; margin-bottom: 10px;">
                    Business Impact Analysis
                </div>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px;">
                    <div style="text-align: center;">
                        <div style="font-size: 16px; font-weight: 700; color: {severity_color};">45 min</div>
                        <div style="font-size: 11px; color: #64748b;">Without ARF</div>
                    </div>
                    <div style="text-align: center;">
                        <div style="font-size: 16px; font-weight: 700; color: #10b981;">12 min</div>
                        <div style="font-size: 11px; color: #64748b;">With ARF</div>
                    </div>
                    <div style="text-align: center;">
                        <div style="font-size: 16px; font-weight: 700; color: #10b981;">${int(impact * 0.85):,}</div>
                        <div style="font-size: 11px; color: #64748b;">Savings</div>
                    </div>
                </div>
            </div>
            
            <!-- Boundary context -->
            <div style="margin-top: 20px; padding: 12px; background: #f8fafc; border-radius: 8px;
                        border-left: 3px solid {severity_color}; font-size: 12px; color: #475569;">
                <strong>Boundary Context:</strong> {scenario.get('boundary_note', 'OSS analyzes, Enterprise executes')}
            </div>
        </div>
        """
    
    # Get visualizations as Plotly figures (ENHANCED)
    telemetry_fig = create_simple_telemetry_plot(scenario_name, settings.use_true_arf)
    impact_fig = create_simple_impact_plot(scenario_name, settings.use_true_arf)
    timeline_fig = create_empty_plot(f"Timeline: {scenario_name}", settings.use_true_arf)
    
    # ============ NEW: Create realism panel ============
    try:
        # Use the imported create_realism_panel function
        realism_html = components["create_realism_panel"](scenario, scenario_name)
    except (ImportError, KeyError):
        # Fallback if realism function isn't available yet
        realism_html = """
        <div style="border: 2px solid #f59e0b; border-radius: 14px; padding: 20px; 
                    background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); 
                    text-align: center; margin-top: 20px;">
            <div style="font-size: 36px; margin-bottom: 10px;">πŸ”§</div>
            <h4 style="margin: 0 0 10px 0; color: #92400e;">Realism Panel Loading...</h4>
            <p style="color: #b45309; font-size: 14px;">
                Trade-offs, risk assessments, and ranked actions will appear here
            </p>
        </div>
        """
    
    logger.info(f"βœ… Updated scenario display for {scenario_name} with realism panel")
    
    # ============ CHANGE HERE: Add realism_html to return tuple ============
    return scenario_card_html, telemetry_fig, impact_fig, timeline_fig, realism_html

# ===========================================
# ENHANCED: Combined update function for scenario display + performance metrics
# ===========================================

def update_scenario_display_with_metrics(scenario_name: str) -> tuple:
    """Combined update function - doctrinally compliant"""
    # Get scenario display components (5 outputs)
    scenario_card, telemetry_fig, impact_fig, timeline_fig, _ = update_scenario_display(scenario_name)
    
    # Get doctrinally compliant performance metrics (4 outputs)
    components = get_components()
    detection_time, recall_quality, confidence_score, sequencing_stage = components["update_performance_metrics"](scenario_name)
    
    return (scenario_card, telemetry_fig, impact_fig, timeline_fig,
            detection_time, recall_quality, confidence_score, sequencing_stage)  # Changed

# ===========================================
# FIXED EXECUTION FUNCTION - Returns DataFrames
# ===========================================
def execute_enterprise_healing(scenario_name, approval_required, mcp_mode_value):
    """
    MINIMAL FIX: Returns proper data types matching UI expectations
    FIXED: Returns DataFrame instead of HTML for execution table
    """
    import gradio as gr
    
    components = get_components()
    installation = get_installation_status()
    boundaries = BoundaryManager.get_system_boundaries()
    
    logger.info(f"⚑ Executing enterprise healing for: {scenario_name}")
    
    # Check if Enterprise is actually available
    is_real_enterprise = installation["enterprise_installed"]
    is_simulated = not is_real_enterprise
    
    # Get scenario impact
    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)
    
    # Create approval display HTML
    if approval_required:
        approval_display = """
        <div style="border: 3px solid #f59e0b; border-radius: 14px; padding: 25px; 
                    background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
                    text-align: center; margin-bottom: 20px;">
            <div style="font-size: 36px; margin-bottom: 15px;">⏳</div>
            <h4 style="margin: 0 0 12px 0; font-size: 20px; color: #92400e; font-weight: 700;">
                HUMAN APPROVAL REQUIRED
            </h4>
            <p style="font-size: 15px; color: #92400e; margin-bottom: 15px; line-height: 1.6;">
                Based on your safety settings, this execution requires human approval.
            </p>
        </div>
        """
    else:
        approval_display = """
        <div style="border: 3px solid #10b981; border-radius: 14px; padding: 25px; 
                    background: linear-gradient(135deg, #f0fdf4 0%, #bbf7d0 100%);
                    text-align: center; margin-bottom: 20px;">
            <div style="font-size: 36px; margin-bottom: 15px;">⚑</div>
            <h4 style="margin: 0 0 12px 0; font-size: 20px; color: #065f46; font-weight: 700;">
                AUTONOMOUS APPROVAL GRANTED
            </h4>
            <p style="font-size: 15px; color: #065f46; margin-bottom: 15px; line-height: 1.6;">
                Proceeding with autonomous execution.
            </p>
        </div>
        """
    
    # Execute healing (async)
    @AsyncRunner.async_to_sync
    async def execute_async():
        try:
            orchestrator = components["DemoOrchestrator"]()
            execution_result = await orchestrator.execute_healing(scenario_name, "autonomous")
            
            # Add to audit trail
            get_audit_manager().add_execution(scenario_name, "enterprise_autonomous", execution_result)
            
            return execution_result
            
        except Exception as e:
            logger.error(f"Execution failed: {e}")
            return {
                "status": "failed",
                "error": str(e),
                "boundary_note": "Execution boundary reached"
            }
    
    execution_result = execute_async()
    
    # Create results dict for JSON display
    if is_real_enterprise:
        enterprise_results = {
            "demo_mode": "Real Enterprise",
            "scenario": scenario_name,
            "arf_version": boundaries["enterprise"]["version"],
            "execution_mode": "autonomous" if not approval_required else "human_approved",
            "results": {
                "recovery_time": "12 minutes",
                "cost_saved": f"${savings:,}",
                "users_protected": "45,000"
            },
            "safety_features": [
                "Rollback guarantee: 100%",
                "Atomic execution",
                "MCP validation"
            ]
        }
    else:
        enterprise_results = {
            "demo_mode": "Enterprise Simulation",
            "scenario": scenario_name,
            "arf_version": boundaries["enterprise"]["version"],
            "execution_mode": "simulated_autonomous",
            "results": {
                "recovery_time": "12 minutes (simulated)",
                "cost_saved": f"${savings:,} (simulated)",
                "users_protected": "45,000 (simulated)"
            },
            "safety_features": [
                "Rollback guarantee: 100% (simulated)",
                "Atomic execution (simulated)"
            ]
        }
    
    # Get execution DataFrame (FIXED: Returns DataFrame instead of HTML)
    execution_df = get_audit_manager().get_execution_dataframe()
    
    return approval_display, enterprise_results, execution_df

# ===========================================
# FIXED ROI FUNCTION - Enhanced for Gradio
# ===========================================
def calculate_roi(scenario_name, monthly_incidents, team_size):
    """
    ENHANCED: Returns (JSON/dict, Plotly figure) for ROI calculation with Gradio compatibility
    """
    components = get_components()
    
    try:
        # Try to use real ROI calculator
        calculator = components["EnhancedROICalculator"]
        roi_result = calculator.calculate_comprehensive_roi(
            scenario_name=scenario_name,
            monthly_incidents=monthly_incidents,
            team_size=team_size
        )
    except Exception as e:
        logger.warning(f"ROI calculation failed, using mock: {e}")
        # Mock ROI calculation
        impact_per_incident = get_scenario_impact(scenario_name)
        annual_impact = impact_per_incident * monthly_incidents * 12
        potential_savings = int(annual_impact * 0.82)
        enterprise_cost = 625000
        roi_multiplier = round(potential_savings / enterprise_cost, 1)
        payback_months = round((enterprise_cost / (potential_savings / 12)), 1)
        
        roi_result = {
            "status": "βœ… Calculated Successfully",
            "summary": {
                "your_annual_impact": f"${annual_impact:,}",
                "potential_savings": f"${potential_savings:,}",
                "enterprise_cost": f"${enterprise_cost:,}",
                "roi_multiplier": f"{roi_multiplier}Γ—",
                "payback_months": f"{payback_months}",
                "annual_roi_percentage": f"{int((potential_savings - enterprise_cost) / enterprise_cost * 100)}%",
                "boundary_context": "Based on OSS analysis + simulated Enterprise execution"
            },
            "boundary_note": "ROI calculation includes OSS advisory value and simulated Enterprise execution benefits"
        }
    
    # Create ROI chart as Plotly figure (ENHANCED for Gradio)
    categories = ['Without ARF', 'With ARF', 'Net Savings']
    annual_impact_val = impact_per_incident * monthly_incidents * 12 if 'impact_per_incident' in locals() else 1000000
    potential_savings_val = potential_savings if 'potential_savings' in locals() else 820000
    enterprise_cost_val = enterprise_cost if 'enterprise_cost' in locals() else 625000
    
    values = [annual_impact_val, annual_impact_val - potential_savings_val, potential_savings_val - enterprise_cost_val]
    
    fig = go.Figure(data=[
        go.Bar(
            name='Cost',
            x=categories,
            y=values,
            marker_color=['#ef4444', '#10b981', '#8b5cf6']
        )
    ])
    
    fig.update_layout(
        title={
            'text': f"ROI Analysis: {scenario_name}",
            'font': dict(size=18, color='#1e293b', family="Arial, sans-serif")
        },
        height=400,
        plot_bgcolor='white',
        paper_bgcolor='white',
        showlegend=False,
        margin=dict(l=40, r=20, t=60, b=40)
    )
    
    logger.info(f"βœ… Created ROI plot for {scenario_name}")
    
    # Return both the dict and the Plotly figure
    return roi_result, fig

# ===========================================
# CREATE DEMO INTERFACE - UPDATED WITH MODERN UI INTEGRATION
# ===========================================
def create_demo_interface():
    """Create demo interface using modular components with boundary awareness and modern UI"""
    
    import gradio as gr
    
    # Get components
    components = get_components()
    
    # Get feature flags
    flags = get_feature_flags()
    
    # Create interface WITHOUT css parameter (fixes Gradio 6.0 warning)
    with gr.Blocks(
        title=f"πŸš€ ARF Investor Demo v3.3.9 - TRUE ARF OSS Integration"
    ) as demo:
        
        # MODERN UI INITIALIZATION
        if flags.get('modern_ui', True) and MODERN_UI_AVAILABLE:
            try:
                # Initialize modern UI with theme support
                modern_ui_init = gr.HTML(initialize_modern_ui())
                logger.info("βœ… Modern UI initialized")
            except Exception as e:
                logger.warning(f"⚠️ Modern UI initialization failed: {e}")
                modern_ui_init = gr.HTML("<!-- Modern UI failed to initialize -->")
        else:
            modern_ui_init = gr.HTML("<!-- Modern UI not enabled -->")
        
        # Add dark mode toggle if enabled
        if flags.get('dark_mode', True):
            dark_mode_toggle = gr.HTML(create_dark_mode_toggle())
            logger.info("βœ… Dark mode toggle added")
        
        # Header
        header_html = components["create_header"]("3.3.9")
        
        # Status bar with boundary badges
        status_html = components["create_status_bar"]()
        
        
        # ============ 5 TABS ============
        with gr.Tabs(elem_classes="tab-nav"):
            
            # TAB 1: Live Incident Demo - NOW WITH MODERN COMPONENTS
            with gr.TabItem("πŸ”₯ Live Incident Demo", id="tab1"):
                # ===== SURGICAL FIX: SAFE UNPACKING WITH ERROR HANDLING =====
                try:
                    logger.info("πŸ”§ Extracting Tab1 components with safe unpacking...")
                    
                    # Get the raw result tuple
                    tab1_result = components["create_tab1_incident_demo"]()
                    
                    # Debug logging for contract verification
                    logger.info(f"πŸ“Š Tab1 result type: {type(tab1_result)}")
                    if hasattr(tab1_result, '__len__'):
                        logger.info(f"πŸ“Š Tab1 result length: {len(tab1_result)}")
                        for i, item in enumerate(tab1_result):
                            item_type = type(item).__name__ if hasattr(item, '__name__') else type(item)
                            logger.debug(f"  Index {i}: {item_type}")
                    
                    # MANUAL INDEX-BASED UNPACKING (CONTRACT ENFORCEMENT)
                    # Indices verified against components.py return statement
                    scenario_dropdown = tab1_result[0]
                    historical_panel = tab1_result[1]
                    scenario_card = tab1_result[2]
                    telemetry_viz = tab1_result[3]
                    impact_viz = tab1_result[4]
                    observation_gate_placeholder = tab1_result[5]
                    sequencing_panel = tab1_result[6]
                    workflow_header = tab1_result[7]
                    detection_process = tab1_result[8]
                    recall_process = tab1_result[9]
                    decision_process = tab1_result[10]
                    oss_section = tab1_result[11]
                    enterprise_section = tab1_result[12]
                    oss_btn = tab1_result[13]
                    enterprise_btn = tab1_result[14]
                    approval_toggle = tab1_result[15]
                    mcp_mode = tab1_result[16]
                    timeline_viz = tab1_result[17]
                    detection_time = tab1_result[18]
                    recall_quality = tab1_result[19]      # ← CRITICAL: WAS mttr
                    confidence_score = tab1_result[20]    # ← CRITICAL: WAS auto_heal
                    sequencing_stage = tab1_result[21]    # ← CRITICAL: WAS savings
                    oss_results_display = tab1_result[22]
                    enterprise_results_display = tab1_result[23]
                    approval_display = tab1_result[24]
                    demo_btn = tab1_result[25]            # ← CRITICAL: Index 25 MUST be demo_btn
                    
                    logger.info("βœ… Tab1 components successfully extracted with correct contract")
                    
                except Exception as e:
                    logger.error(f"❌ Tab1 component extraction failed: {e}")
                    logger.error("πŸ”„ Creating fallback components to maintain system integrity...")
                    
                    # FALLBACK CREATION (Minimal viable components)
                    import gradio as gr
                    
                    # Create minimal placeholder components
                    scenario_dropdown = gr.Dropdown(choices=["Error Mode"], value="Error Mode")
                    historical_panel = gr.DataFrame(value=[["System in recovery mode"]])
                    scenario_card = gr.Markdown("### System Initialization Issue")
                    telemetry_viz = gr.Plot()
                    impact_viz = gr.Plot()
                    observation_gate_placeholder = gr.Markdown("**Observation Gate:** System integrity check")
                    sequencing_panel = gr.Markdown("**Sequencing:** Initializing...")
                    workflow_header = gr.Markdown("### Policy Recovery Mode")
                    detection_process = gr.Textbox(value="DETECTION: ERROR")
                    recall_process = gr.Textbox(value="RECALL: ERROR")
                    decision_process = gr.Textbox(value="DECISION: ERROR")
                    oss_section = gr.Markdown("#### OSS: Unavailable")
                    enterprise_section = gr.Markdown("#### Enterprise: Unavailable")
                    oss_btn = gr.Button("Unavailable", variant="secondary")
                    enterprise_btn = gr.Button("Unavailable", variant="secondary")
                    approval_toggle = gr.Checkbox(label="Approval: Error", value=False)
                    mcp_mode = gr.Radio(choices=["Error"], value="Error")
                    timeline_viz = gr.Plot()
                    detection_time = gr.Number(value=0)
                    recall_quality = gr.Number(value=0)      # ← CORRECT VARIABLE NAME
                    confidence_score = gr.Number(value=0)    # ← CORRECT VARIABLE NAME
                    sequencing_stage = gr.Textbox(value="Error")  # ← CORRECT VARIABLE NAME
                    oss_results_display = gr.Markdown("### Results: Unavailable")
                    enterprise_results_display = gr.Markdown("### Results: Unavailable")
                    approval_display = gr.Markdown("**Status:** System recovery in progress")
                    demo_btn = gr.Button("πŸ”„ System Recovery Required", variant="secondary", size="lg")
                    
                    logger.warning("⚠️ Using fallback components - full functionality limited")
                # ===== END SURGICAL FIX =====
            
            # 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"]()
        
        # Add CSS debug panel for testing
        if flags.get('modern_ui', True):
            debug_html = gr.HTML(f"""
            <div style="position: fixed; bottom: 80px; right: 20px; z-index: 999;
                        background: white; padding: 10px; border-radius: 8px;
                        border: 1px solid var(--color-border, #e2e8f0); font-size: 12px;
                        box-shadow: 0 2px 8px rgba(0,0,0,0.1); opacity: 0.9;">
                <strong>CSS Debug:</strong><br>
                Modern UI: {flags.get('modern_ui', False)}<br>
                Dark Mode: {flags.get('dark_mode', False)}<br>
                CSS Loaded: βœ…
            </div>
            """)
        
        # ============ EVENT HANDLERS ============
        
        # Update scenario display when dropdown changes - NOW INCLUDES PERFORMANCE METRICS
        scenario_dropdown.change(
            fn=update_scenario_display_with_metrics,
            inputs=[scenario_dropdown],
            outputs=[
                scenario_card, telemetry_viz, impact_viz, timeline_viz,
                detection_time, recall_quality, confidence_score, sequencing_stage
            ]
        )
        
        # ===========================================
        # FIXED: OSS Analysis Button Connection - SIMPLE PASSTHROUGH
        # ===========================================
        def run_oss_analysis_real_arf(scenario_name: str) -> tuple:
            """
            Simple passthrough to run_true_arf_analysis()
            The decorator now handles contract preservation
            """
            logger.info(f"πŸš€ Running TRUE ARF OSS analysis for: {scenario_name}")
            return run_true_arf_analysis(scenario_name)
        
        # Run OSS Analysis - FIXED: Simple passthrough
        oss_btn.click(
            fn=run_oss_analysis_real_arf,
            inputs=[scenario_dropdown],
            outputs=[
                detection_process, recall_process, decision_process,
                oss_results_display, incident_table
            ]
        )
        
        # Execute Enterprise Healing - FIXED: Now returns DataFrame for execution_table
        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 with metrics
            update_result = update_scenario_display_with_metrics(scenario_name)
            
            # Step 2: Run OSS analysis using TRUE ARF OSS function
            oss_result = run_oss_analysis_real_arf(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_amount = 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.9",
                "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_amount:,}",
                    "users_protected": "45,000",
                    "learning": "Pattern added to RAG memory"
                },
                "architectural_summary": f"This demonstrates the complete ARF v3.3.9 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 var(--color-border, #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 var(--color-border, #e2e8f0);">
                    <div>
                        <h3 style="margin: 0; font-size: 18px; color: var(--color-text, #1e293b); font-weight: 700;">
                            βœ… Complete Demo: Architecture Validated
                        </h3>
                        <p style="margin: 5px 0 0 0; font-size: 13px; color: var(--color-text-secondary, #64748b);">
                            ARF v3.3.9 β€’ 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: var(--color-bg-secondary, #f8fafc); border-radius: 8px;">
                        <div style="font-size: 11px; color: var(--color-text-secondary, #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: var(--color-text, #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: var(--color-bg-secondary, #f8fafc); border-radius: 8px;">
                        <div style="font-size: 11px; color: var(--color-text-secondary, #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: var(--color-text, #475569); line-height: 1.5;">
                            β€’ Autonomous execution simulated<br>
                            β€’ Rollback guarantee: 100%<br>
                            β€’ 12min vs 45min recovery<br>
                            β€’ ${savings_amount:,} saved
                        </div>
                    </div>
                </div>
                
                <!-- Boundary Progression Visualization -->
                <div style="margin-bottom: 20px;">
                    <div style="font-size: 12px; color: var(--color-text-secondary, #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: var(--color-bg-secondary, #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: var(--color-text-secondary, #64748b); border: 1px solid var(--color-border, #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, var(--color-bg-secondary, #f8fafc) 0%, var(--color-bg, #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: var(--color-text-secondary, #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: var(--color-text-secondary, #64748b); margin-bottom: 5px;">Cost Saved</div>
                            <div style="font-size: 18px; font-weight: 700; color: #10b981;">${savings_amount:,}</div>
                        </div>
                        <div>
                            <div style="font-size: 11px; color: var(--color-text-secondary, #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="margin-top: 15px; 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 var(--color-border, #e2e8f0); 
                            text-align: center; font-size: 12px; color: var(--color-text-secondary, #64748b);">
                    Ready for production? <a href="#" style="color: #8b5cf6; font-weight: 600; text-decoration: none;">
                    Install ARF Enterprise β†’</a>
                </div>
            </div>
            """
            
            # Update the enterprise_results_display to include demo completion info
            enterprise_results["demo_completion_message"] = demo_message
            
            # Get updated DataFrames (FIXED: Returns DataFrames)
            incident_df = get_audit_manager().get_incident_dataframe()
            execution_df = get_audit_manager().get_execution_dataframe()
            
            # Combine all results
            return (
                *update_result,  # 8 outputs: scenario_card, telemetry_viz, impact_viz, timeline_viz, detection_time, recall_quality, confidence_score, sequencing_stage
                *oss_result[:3],  # 3 outputs: detection_process, recall_process, decision_process
                oss_result[3],    # 1 output: oss_results_display
                enterprise_results,  # 1 output: enterprise_results_display  
                demo_message,  # 1 output: approval_display
                incident_df,  # 1 output: incident_table (DataFrame)
                execution_df  # 1 output: execution_table (DataFrame)
            )
        
        # FIXED: demo_btn.click with correct output count
        demo_btn.click(
            fn=run_complete_demo_async,
            inputs=[scenario_dropdown],
            outputs=[
                scenario_card, telemetry_viz, impact_viz, timeline_viz,
                detection_time, recall_quality, confidence_score, sequencing_stage,  # 8
                detection_process, recall_process, decision_process,  # 3
                oss_results_display,  # 1
                enterprise_results_display,  # 1
                approval_display,  # 1
                incident_table,  # 1
                execution_table  # 1
            ]
        )
        
        # ROI Calculation
        calculate_btn.click(
            fn=calculate_roi,
            inputs=[roi_scenario_dropdown, monthly_slider, team_slider],
            outputs=[roi_output, roi_chart]
        )
        
        # Update ROI scenario - FIXED: Use the EnhancedROICalculator
        roi_scenario_dropdown.change(
            fn=lambda x: get_components()["EnhancedROICalculator"].calculate_comprehensive_roi(scenario_name=x),
            inputs=[roi_scenario_dropdown],
            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 - FIXED: Returns DataFrames
        def refresh_audit_trail():
            """Refresh audit trail tables - FIXED to return DataFrames"""
            return (
                get_audit_manager().get_execution_dataframe(),  # DataFrame
                get_audit_manager().get_incident_dataframe()    # DataFrame
            )
        
        def clear_audit_trail():
            """Clear audit trail - FIXED to return empty DataFrames"""
            get_audit_manager().clear()
            # Return empty DataFrames with correct columns
            exec_df = pd.DataFrame(columns=["Execution ID", "Scenario", "Status", "Mode", "Start Time"])
            incident_df = pd.DataFrame(columns=["Scenario", "Status", "Boundary", "Time"])
            return exec_df, incident_df
        
        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.9",
                "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]
        )
        
        # Load default scenario - UPDATE outputs without realism_panel
        demo.load(
            fn=lambda: update_scenario_display_with_metrics(settings.default_scenario),
            inputs=[],
            outputs=[
                scenario_card, telemetry_viz, impact_viz, timeline_viz,
                detection_time, recall_quality, confidence_score, sequencing_stage
            ]
        )
        
        # 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 modern UI integration")
    
    return demo

# ===========================================
# DARK MODE TOGGLE FUNCTION
# ===========================================

def create_dark_mode_toggle():
    """Create a dark mode toggle button with JavaScript"""
    return f"""
    <div id="darkModeToggle" class="dark-mode-toggle" onclick="toggleDarkMode()" 
         title="Toggle Dark Mode">
        <span id="darkModeIcon" style="font-size: 24px;">πŸŒ™</span>
    </div>
    
    <script>
    // Check for saved theme or prefer-color-scheme
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const savedTheme = localStorage.getItem('theme');
    const theme = savedTheme || (prefersDark ? 'dark' : 'light');
    
    // Apply theme
    document.documentElement.setAttribute('data-theme', theme);
    updateDarkModeIcon(theme);
    
    function toggleDarkMode() {{
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        // Update theme
        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
        
        // Update icon
        updateDarkModeIcon(newTheme);
        
        // Dispatch event for components that need to know
        document.dispatchEvent(new CustomEvent('themechange', {{ detail: {{ theme: newTheme }} }}));
    }}
    
    function updateDarkModeIcon(theme) {{
        const icon = document.getElementById('darkModeIcon');
        if (theme === 'dark') {{
            icon.textContent = 'β˜€οΈ';
            icon.title = 'Switch to Light Mode';
        }} else {{
            icon.textContent = 'πŸŒ™';
            icon.title = 'Switch to Dark Mode';
        }}
    }}
    
    // Listen for system theme changes
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {{
        if (!localStorage.getItem('theme')) {{
            const newTheme = e.matches ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', newTheme);
            updateDarkModeIcon(newTheme);
        }}
    }});
    </script>
    """

# ===========================================
# MAIN EXECUTION - CRITICAL: THIS LAUNCHES THE APP - UPDATED FOR SPACES
# ===========================================

def main():
    """Main entry point that actually launches the Gradio app"""
    try:
        logger.info("πŸš€ ARF Ultimate Investor Demo v3.3.9 - ENTERPRISE EDITION")
        logger.info("=" * 60)
        logger.info("Enhanced with clear OSS vs Enterprise boundaries")
        logger.info("DOCTRINAL COMPLIANCE: Historical Evidence, Observation Gate, Sequencing")
        logger.info("PHASE 2: Dynamic Performance Metrics by Scenario")
        logger.info(f"Modern UI: {'Enabled' if get_feature_flags().get('modern_ui', True) else 'Disabled'}")
        logger.info(f"True ARF OSS v3.3.9 integration with simulated Enterprise execution")
        logger.info("=" * 60)
        
        # Create the demo interface
        demo = create_demo_interface()
        
        print("\n" + "="*60)
        print("πŸš€ ARF Ultimate Investor Demo v3.3.9 - ENTERPRISE EDITION")
        print("πŸ“Š Architecture: OSS advises β†’ Enterprise executes")
        print("🎭 DOCTRINAL: Historical Evidence + Observation Gate + Sequencing")
        print("🎨 MODERN UI: Design system with responsive components")
        print("="*60 + "\n")
        
        # ============ HUGGING FACE SPACES SPECIFIC ============
        # Spaces handles ports differently - use their system
        import os
        
        # Get port from environment (Spaces sets this)
        port = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
        server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
        
        # Get CSS
        css_styles = load_css_files()
        
        logger.info(f"πŸš€ Launching on {server_name}:{port}")
        print(f"🌐 Starting on http://{server_name}:{port}")
        
        # SIMPLE LAUNCH FOR SPACES COMPATIBILITY
        demo.launch(
            css=css_styles,  # CSS moved to launch() - fixes Gradio 6.0 warning
            server_name=server_name,
            server_port=port,
            share=False,
            debug=False,
            show_error=True,
            quiet=True  # Reduce log noise
        )
        
    except KeyboardInterrupt:
        logger.info("πŸ‘‹ Demo stopped by user")
    except Exception as e:
        logger.error(f"❌ Fatal error: {e}", exc_info=True)
        print(f"\n❌ ERROR: {e}")
        print("Please check the logs for more details.")
        sys.exit(1)

# ===========================================
# HUGGING FACE SPACES COMPATIBILITY - UPDATED
# ===========================================

# This is the entry point that Hugging Face Spaces will use
if __name__ == "__main__":
    # For Hugging Face Spaces, we need to ensure the app stays alive
    import os
    
    # ============ CRITICAL FIXES FOR HUGGING FACE SPACES ============
    
    # 1. Set environment variables for Hugging Face Spaces compatibility
    os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
    os.environ["GRADIO_SERVER_PORT"] = "7860"  # Spaces will override this if needed
    os.environ["GRADIO_SERVER_NAME"] = "0.0.0.0"
    os.environ["GRADIO_HOT_RELOAD"] = "False"  # Disable hot reload in Spaces
    os.environ["GRADIO_QUEUE_ENABLED"] = "True"  # Enable queue for stability
    
    # 2. Additional fixes for uvicorn warnings
    os.environ["UVICORN_LOG_LEVEL"] = "warning"  # Reduce uvicorn log noise
    os.environ["UVICORN_ACCESS_LOG"] = "False"  # Disable access logs
    
    print("\n" + "="*60)
    print("πŸš€ ARF Demo Starting on Hugging Face Spaces")
    print(f"πŸ“ Working directory: {os.getcwd()}")
    print(f"πŸ“Š Python version: {sys.version}")
    print("="*60 + "\n")
    
    # 3. Detect if we're running in Hugging Face Spaces
    is_huggingface_space = "SPACE_ID" in os.environ or "HF_SPACE" in os.environ
    if is_huggingface_space:
        print("βœ… Hugging Face Spaces environment detected")
        print("πŸ€– Using Spaces-optimized configuration")
    
    # 4. Check for required files with better error handling
    required_files = ["styles/modern.css", "styles/responsive.css", "ui/components.py"]
    missing_files = []
    
    for file in required_files:
        if not os.path.exists(file):
            missing_files.append(file)
            print(f"⚠️  Warning: {file} not found")
    
    if missing_files:
        print(f"⚠️  Missing {len(missing_files)} required files")
        print("⚠️  Some features may not work correctly")
        # Create minimal fallback CSS files if missing
        for css_file in ["styles/modern.css", "styles/responsive.css"]:
            if css_file in missing_files:
                try:
                    os.makedirs(os.path.dirname(css_file), exist_ok=True)
                    with open(css_file, "w") as f:
                        if "modern.css" in css_file:
                            f.write("/* Modern CSS Fallback */\n:root { --color-primary: #3b82f6; }\n")
                        else:
                            f.write("/* Responsive CSS Fallback */\n@media (max-width: 768px) { .container { padding: 1rem; } }\n")
                    print(f"βœ… Created fallback {css_file}")
                except Exception as e:
                    print(f"⚠️  Could not create {css_file}: {e}")
    
    # 5. Import gradio early to prevent threading issues
    try:
        import gradio as gr
        logger.info(f"βœ… Gradio {gr.__version__} loaded successfully")
    except Exception as e:
        logger.error(f"❌ Failed to load gradio: {e}")
        print("❌ CRITICAL: Gradio failed to load")
        raise
    
    # 6. Start the main application with better error handling
    try:
        main()
    except Exception as e:
        logger.error(f"❌ Main application crashed: {e}", exc_info=True)
        print(f"\n❌ FATAL ERROR: {e}")
        print("πŸ’‘ Troubleshooting tips:")
        print("1. Check all required files exist")
        print("2. Verify Python package versions")
        print("3. Check Hugging Face Spaces logs for details")
        
        # Try a minimal fallback launch if main() fails
        try:
            print("\nπŸ”„ Attempting minimal fallback launch...")
            import gradio as gr
            
            def fallback_app():
                with gr.Blocks(title="ARF Fallback") as demo:
                    gr.Markdown("# 🚨 ARF System Recovery")
                    gr.Markdown("The main application failed, but the system is still running.")
                    gr.Markdown("**Error:** " + str(e))
                return demo
            
            demo = fallback_app()
            demo.launch(
                server_name="0.0.0.0",
                server_port=7860,
                quiet=True,
                show_error=False
            )
        except Exception as fallback_error:
            print(f"❌ Fallback also failed: {fallback_error}")
            sys.exit(1)