File size: 206,141 Bytes
fc49c8c
 
 
b9892ff
12d9531
 
 
 
 
fc49c8c
 
5b481a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc49c8c
18b9531
 
 
b9892ff
12d9531
76897aa
f1a0f4d
 
12d9531
18b9531
4eba8ec
76897aa
 
 
 
18b9531
cea2220
18b9531
 
9f411df
b9892ff
 
 
 
 
 
 
 
76897aa
 
 
 
 
 
 
 
 
9f411df
76897aa
 
 
 
 
84b71cf
ffc5e7c
5ab6829
ffc5e7c
f3bd749
 
 
 
ffc5e7c
021b909
ffc5e7c
 
021b909
 
 
 
 
 
ffc5e7c
 
fc49c8c
7ae669f
 
 
 
 
c9f3367
 
 
f1d5053
 
 
5b481a8
18b9531
 
 
 
 
84b71cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76897aa
 
 
 
 
 
84b71cf
76897aa
84b71cf
 
 
76897aa
 
 
84b71cf
 
 
 
 
76897aa
 
 
 
 
 
12d9531
b9892ff
f85e1e8
76897aa
39d0dfb
 
b9892ff
e628e1f
 
 
 
 
7ae669f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12d9531
 
18b9531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12d9531
18b9531
 
 
 
 
 
 
fd8bbd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76897aa
 
 
 
 
18b9531
 
 
 
6d9f030
76897aa
18b9531
 
12d9531
18b9531
12d9531
 
 
 
 
18b9531
 
 
12d9531
 
76897aa
 
 
 
18b9531
53f9237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72878a
 
3109d12
d72878a
3109d12
d72878a
 
 
 
 
3109d12
 
 
53f9237
 
76897aa
 
 
 
 
 
6d9f030
18b9531
6d9f030
53f9237
12d9531
53f9237
 
fc49c8c
12d9531
53f9237
18b9531
 
 
12d9531
18b9531
 
d72878a
 
 
 
 
 
 
 
 
 
 
 
 
 
22e48cb
d72878a
22e48cb
d72878a
 
 
 
22e48cb
 
d72878a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53f9237
12d9531
f2c29a4
 
53f9237
12d9531
f2c29a4
 
12d9531
f2c29a4
53f9237
 
12d9531
 
 
53f9237
12d9531
 
 
53f9237
c97b229
 
 
 
 
 
12d9531
53f9237
 
21d4df0
 
 
 
 
 
 
 
 
 
 
12d9531
a762158
 
 
 
 
12d9531
 
 
c97b229
12d9531
 
c97b229
 
12d9531
f2c29a4
a762158
 
 
 
 
 
 
 
22e48cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53f9237
 
 
f2c29a4
12d9531
53f9237
 
 
 
 
f2c29a4
12d9531
f85e1e8
fc49c8c
12d9531
fc49c8c
22e48cb
53f9237
12d9531
 
 
 
 
53f9237
12d9531
 
 
18b9531
12d9531
 
 
18b9531
 
12d9531
18b9531
12d9531
 
 
 
 
18b9531
53f9237
 
 
12d9531
53f9237
18b9531
12d9531
 
18b9531
21d4df0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18b9531
53f9237
 
 
18b9531
12d9531
fc49c8c
 
76897aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12d9531
8d1fc6f
 
6d9f030
76897aa
12d9531
9ec4319
7ae669f
 
 
b9892ff
 
8d1fc6f
12d9531
6d9f030
76897aa
12d9531
b9892ff
12d9531
9ec4319
b9892ff
 
 
12d9531
 
7ae669f
12d9531
d72878a
9ec4319
 
12d9531
b9892ff
 
7ae669f
12d9531
b9892ff
12d9531
 
 
 
 
d72878a
9ec4319
 
12d9531
b9892ff
7ae669f
12d9531
b9892ff
70da74f
 
6fc3f10
60dd254
 
 
 
 
 
 
 
 
 
70da74f
 
 
 
 
 
 
 
 
 
 
223daa0
70da74f
 
 
 
 
223daa0
 
 
 
 
 
 
70da74f
223daa0
 
70da74f
 
cd320c1
53f9237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72878a
 
3109d12
d72878a
3109d12
d72878a
 
 
 
 
3109d12
 
 
53f9237
 
3109d12
b9892ff
76897aa
 
 
 
 
 
6d9f030
3109d12
 
 
 
 
 
 
 
 
 
 
 
 
53f9237
b9892ff
39d0dfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
70da74f
 
 
 
 
84b71cf
70da74f
84b71cf
70da74f
 
 
 
223daa0
 
 
70da74f
 
223daa0
70da74f
 
9f411df
12d9531
53f9237
d72878a
b9892ff
12d9531
b9892ff
12d9531
7ae669f
12d9531
d72878a
e628e1f
 
b9892ff
 
12d9531
 
 
 
 
d72878a
e877e4d
 
12d9531
b9892ff
 
4e50d9d
c97b229
4e50d9d
fd8bbd4
 
 
4e50d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd8bbd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c97b229
 
a6ff0c8
c4236c2
9122d00
c97b229
fd8bbd4
 
 
c97b229
9122d00
fd8bbd4
c97b229
 
fd8bbd4
 
 
 
 
c97b229
fd8bbd4
c97b229
 
c4236c2
 
 
c97b229
 
 
fd8bbd4
c97b229
 
 
 
fd8bbd4
c97b229
 
 
 
 
 
 
 
 
 
 
 
fd8bbd4
 
 
c97b229
 
 
 
 
 
 
 
 
 
 
 
 
 
fd8bbd4
 
c97b229
fd8bbd4
 
 
 
c97b229
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd8bbd4
c97b229
fd8bbd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e50d9d
 
a6ff0c8
dab47a1
9122d00
4e50d9d
fd8bbd4
 
4e50d9d
 
 
c4236c2
4e50d9d
9122d00
fd8bbd4
4e50d9d
 
fd8bbd4
 
 
 
c97b229
fd8bbd4
 
 
 
 
c97b229
 
fd8bbd4
c97b229
fd8bbd4
c97b229
 
4e50d9d
c97b229
c4236c2
c97b229
c4236c2
c97b229
 
fd8bbd4
 
 
 
c97b229
 
4e50d9d
fd8bbd4
c97b229
 
fd8bbd4
4e50d9d
fd8bbd4
4e50d9d
 
 
 
c97b229
4e50d9d
c97b229
 
4e50d9d
 
12d9531
 
b9892ff
 
12d9531
b9892ff
12d9531
b9892ff
12d9531
 
 
 
f1d5053
 
53f9237
 
 
f85e1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1d5053
53f9237
f1d5053
12d9531
b9892ff
12d9531
 
 
 
 
 
fc49c8c
53f9237
 
 
 
 
 
f1d5053
53f9237
 
 
 
 
 
f1d5053
12d9531
 
 
 
 
 
 
53f9237
 
 
 
 
f1d5053
53f9237
f1d5053
53f9237
 
 
f1d5053
 
53f9237
12d9531
4e50d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4236c2
 
4e50d9d
 
 
 
c4236c2
 
 
 
4e50d9d
c4236c2
 
 
 
4e50d9d
 
c4236c2
 
 
 
4e50d9d
 
c4236c2
4e50d9d
c4236c2
4e50d9d
c4236c2
4e50d9d
 
c4236c2
4e50d9d
c4236c2
 
4e50d9d
c4236c2
4e50d9d
 
c4236c2
 
 
4e50d9d
 
15d570b
d038452
 
 
 
 
 
 
15d570b
 
 
 
 
 
 
 
d038452
 
15d570b
 
d038452
 
 
 
15d570b
 
 
 
 
d038452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15d570b
 
 
 
 
d038452
 
 
 
15d570b
d038452
 
 
15d570b
 
 
 
 
d038452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4236c2
4e50d9d
 
 
 
 
c4236c2
fd8bbd4
eb98c5c
8dac111
c4236c2
 
a7678fd
 
fd8bbd4
47fd710
 
c4236c2
 
 
 
 
 
c97b229
c4236c2
 
 
 
 
 
 
 
 
 
c97b229
 
a6ff0c8
 
 
 
 
 
1586274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4236c2
 
c97b229
 
 
 
 
c4236c2
04170f7
c7d5b27
 
d1839af
d70f0b1
d1839af
04170f7
 
72e46b4
c97b229
 
04170f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4236c2
d1839af
 
 
c4236c2
c97b229
 
c4236c2
c97b229
 
47fd710
 
c7d5b27
 
 
280ed9e
 
c7d5b27
 
 
 
 
 
280ed9e
 
fd8bbd4
 
d70f0b1
c7d5b27
 
 
 
 
 
 
 
 
 
47fd710
 
72e46b4
bfaf40f
fd8bbd4
6baa32c
fd8bbd4
 
72e46b4
bfaf40f
 
 
280ed9e
 
bfaf40f
 
 
8dac111
 
 
57a9d38
8dac111
 
 
 
 
57a9d38
8dac111
 
57a9d38
 
 
8dac111
57a9d38
8dac111
57a9d38
 
 
 
 
 
8dac111
 
47fd710
 
 
 
 
 
 
 
 
 
 
4e50d9d
 
 
 
 
47fd710
 
 
 
 
 
 
 
 
 
 
4e50d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4236c2
 
 
 
 
 
 
 
4e50d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4236c2
4e50d9d
 
 
 
c4236c2
4e50d9d
 
5ab6829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc49c8c
b9892ff
fc49c8c
 
b9892ff
12d9531
 
fc49c8c
 
ffc5e7c
 
 
19221a0
 
 
 
ffc5e7c
21d4df0
4e50d9d
 
 
 
 
 
 
e628e1f
4e50d9d
 
 
 
 
 
 
 
 
 
 
 
b9892ff
ffc5e7c
 
 
 
 
 
 
f85e1e8
 
 
 
 
d1839af
f85e1e8
 
 
 
 
 
 
 
 
 
 
ffc5e7c
 
 
 
 
 
 
 
 
5ab6829
ffc5e7c
5ab6829
 
ffc5e7c
 
 
 
5ab6829
 
ffc5e7c
4f454b4
 
 
 
 
 
ffc5e7c
 
 
 
 
 
 
5ab6829
 
ffc5e7c
 
5ab6829
ffc5e7c
5ab6829
 
ffc5e7c
5ab6829
 
ffc5e7c
 
5ab6829
 
 
ffc5e7c
5ab6829
 
ffc5e7c
 
 
5ab6829
 
ffc5e7c
5ab6829
 
4f454b4
 
 
 
ffc5e7c
 
 
021b909
 
f85e1e8
021b909
f85e1e8
021b909
 
 
f85e1e8
021b909
ffc5e7c
4f454b4
 
 
 
 
 
5ab6829
4f454b4
5ab6829
 
4f454b4
 
 
8a1adf2
4f454b4
 
 
 
 
 
 
 
 
 
5ab6829
4f454b4
 
5ab6829
 
4f454b4
 
 
 
5ab6829
 
 
4f454b4
 
 
 
5ab6829
 
4f454b4
 
 
8a1adf2
4f454b4
 
d038452
 
 
 
d1839af
d038452
 
 
 
 
 
 
 
 
9cf801a
d038452
 
9cf801a
d038452
9cf801a
 
d038452
 
 
1586274
d038452
 
1586274
d038452
1586274
 
d038452
 
 
b5f969d
d038452
 
b5f969d
d038452
 
 
 
 
9cf801a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d110daf
 
 
 
 
 
 
 
 
 
9cf801a
 
 
e628e1f
 
 
 
 
 
 
 
e877e4d
 
 
 
 
 
 
e628e1f
9cf801a
 
 
1586274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d110daf
 
 
 
 
 
 
 
 
 
1586274
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e628e1f
 
 
 
 
 
 
 
e877e4d
 
 
 
 
 
 
e628e1f
1586274
 
 
 
b5f969d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffc5e7c
 
c4236c2
5c7581b
c4236c2
 
c97b229
 
 
 
 
 
 
6d9f030
7894dc2
 
 
 
 
 
 
 
19221a0
76897aa
 
 
 
 
 
 
 
 
 
 
 
 
 
6d9f030
 
 
 
76897aa
6d9f030
 
d1839af
 
 
 
 
 
 
 
 
 
 
 
 
 
c97b229
72e46b4
c4236c2
72e46b4
 
 
 
 
 
4e50d9d
c4236c2
 
4e50d9d
 
 
 
c97b229
 
6baa32c
72e46b4
6baa32c
c97b229
4e50d9d
4f454b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72e46b4
 
 
bc45c22
 
72e46b4
 
 
bc45c22
 
72e46b4
 
 
bc45c22
 
72e46b4
 
 
bc45c22
 
72e46b4
 
 
bc45c22
 
72e46b4
 
c4236c2
4e50d9d
 
c4236c2
4e50d9d
 
c4236c2
 
4e50d9d
c4236c2
4e50d9d
 
 
c4236c2
4e50d9d
 
c4236c2
 
4e50d9d
ae8d83f
4e50d9d
 
 
c4236c2
4e50d9d
 
c4236c2
 
 
 
4e50d9d
 
 
c4236c2
4e50d9d
 
c4236c2
 
4e50d9d
c4236c2
4e50d9d
 
 
12d9531
47fd710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae8d83f
47fd710
 
 
 
f85e1e8
12d9531
5ab6829
 
 
 
 
 
c199e75
 
5ab6829
f85e1e8
 
 
 
 
 
 
e628e1f
 
 
 
 
 
 
 
e877e4d
 
 
 
 
 
 
e628e1f
f85e1e8
 
 
 
 
 
 
 
 
 
 
 
 
11ca6e2
76897aa
f85e1e8
76897aa
f85e1e8
 
 
 
 
 
76897aa
f85e1e8
 
 
76897aa
9cbe743
f85e1e8
9cbe743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b12d20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cbe743
 
 
f85e1e8
 
 
 
76897aa
f85e1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19221a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f85e1e8
 
 
 
 
 
 
 
76897aa
19221a0
 
 
 
 
 
f85e1e8
 
76897aa
9f411df
 
 
 
 
 
 
19221a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
f85e1e8
 
9f411df
 
f85e1e8
 
9f411df
 
19221a0
 
 
 
 
 
9f411df
 
 
 
 
12d9531
 
 
d038452
12d9531
9f411df
9cf801a
1586274
b5f969d
 
12d9531
b9892ff
d038452
 
 
 
 
9cf801a
1586274
b5f969d
 
d038452
 
9cf801a
 
 
 
 
 
1586274
b5f969d
 
1586274
 
 
 
 
 
 
 
 
b5f969d
 
 
 
 
 
 
 
 
 
 
 
 
9cf801a
 
e628e1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e877e4d
 
 
 
 
 
 
e628e1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e877e4d
 
e628e1f
 
 
 
 
 
 
 
 
 
 
 
 
fc76d90
d110daf
9cf801a
 
 
 
 
 
 
d1839af
2f0f0e6
9cf801a
e628e1f
f1a0f4d
 
 
 
d1839af
f1a0f4d
d1839af
d110daf
d1839af
e877e4d
 
d1839af
 
 
 
f1a0f4d
9cf801a
 
 
 
 
 
 
5fd6564
 
 
 
f1a0f4d
 
 
d110daf
 
f1a0f4d
d110daf
f1a0f4d
d110daf
5fd6564
9cf801a
5fd6564
d110daf
f1a0f4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e877e4d
 
f1a0f4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d110daf
e628e1f
 
 
 
 
e877e4d
 
 
 
 
 
 
 
e628e1f
 
e877e4d
e628e1f
 
 
 
2f0f0e6
 
d1839af
d110daf
 
e628e1f
 
9cf801a
 
 
f1a0f4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1839af
d110daf
 
e877e4d
 
9cf801a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1586274
b5f969d
 
9cf801a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1586274
b5f969d
 
9cf801a
 
d110daf
 
1586274
 
 
 
 
d1839af
d110daf
 
1586274
e628e1f
d1839af
 
d110daf
d1839af
 
 
 
 
 
 
 
e877e4d
 
d1839af
 
1586274
d1839af
 
1586274
d1839af
 
d110daf
 
 
e877e4d
 
d1839af
 
1586274
d1839af
1586274
 
 
 
 
 
 
d110daf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e877e4d
 
d110daf
1586274
d110daf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e628e1f
 
 
 
 
 
 
 
 
 
 
 
d110daf
d1839af
d110daf
 
 
 
 
 
 
 
 
e628e1f
 
1586274
 
 
 
d1839af
d110daf
 
 
e877e4d
 
1586274
 
b5f969d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
70da74f
 
 
 
 
9f411df
84b71cf
 
70da74f
 
 
 
84b71cf
70da74f
 
 
 
84b71cf
70da74f
84b71cf
70da74f
 
84b71cf
9f411df
 
84b71cf
9f411df
 
84b71cf
 
9f411df
f85e1e8
 
 
 
9f411df
f85e1e8
9f411df
cd320c1
9f411df
 
e7fa673
9f411df
 
f85e1e8
9f411df
 
cd320c1
9f411df
 
 
 
 
 
 
 
 
 
 
 
19221a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7fa673
19221a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f85e1e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ab6829
39d0dfb
5ab6829
 
 
 
39d0dfb
5ab6829
39d0dfb
 
5ab6829
 
39d0dfb
 
5ab6829
 
39d0dfb
5ab6829
 
 
 
39d0dfb
5ab6829
39d0dfb
 
5ab6829
 
39d0dfb
 
5ab6829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
d038452
9f411df
 
 
 
 
9b12d20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
 
 
 
 
 
 
 
 
9b12d20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f411df
 
 
 
 
9b12d20
9f411df
 
 
 
 
 
 
 
 
 
 
7894dc2
 
 
caa412b
7894dc2
 
caa412b
7894dc2
 
 
caa412b
7894dc2
 
caa412b
7894dc2
caa412b
7894dc2
caa412b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7894dc2
 
 
 
 
 
caa412b
7894dc2
 
caa412b
7894dc2
caa412b
 
7894dc2
 
 
 
 
9f411df
ffc5e7c
 
 
 
 
 
 
 
 
 
 
 
 
7894dc2
39d0dfb
 
 
ffc5e7c
 
 
9f411df
 
 
84b71cf
9f411df
 
 
 
 
 
 
 
 
 
 
 
 
7894dc2
39d0dfb
 
 
9f411df
 
 
7894dc2
 
 
 
 
7d6a231
7894dc2
47fd710
 
 
 
 
 
 
d72878a
47fd710
 
 
 
7894dc2
39d0dfb
 
 
47fd710
 
 
e877e4d
8d1fc6f
12d9531
 
47fd710
12d9531
39d0dfb
47fd710
12d9531
47fd710
12d9531
47fd710
12d9531
d72878a
12d9531
 
 
 
7894dc2
e877e4d
39d0dfb
 
 
12d9531
 
47fd710
12d9531
47fd710
12d9531
47fd710
12d9531
d72878a
12d9531
 
 
 
7894dc2
e877e4d
39d0dfb
 
 
12d9531
 
4e50d9d
 
 
 
 
 
 
c97b229
 
 
 
 
 
 
7894dc2
caa412b
7894dc2
 
 
 
 
 
 
 
caa412b
7894dc2
 
 
 
 
 
 
 
12d9531
 
ffc5e7c
12d9531
 
47fd710
12d9531
47fd710
12d9531
d72878a
12d9531
 
 
 
7894dc2
39d0dfb
 
e628e1f
 
47fd710
 
12d9531
b9892ff
caa412b
5ab6829
 
c199e75
5ab6829
 
 
 
c199e75
5ab6829
 
d1839af
 
 
 
 
 
f85e1e8
 
 
 
 
 
9f411df
f85e1e8
 
9f411df
f85e1e8
9f411df
 
 
 
d038452
9f411df
 
f85e1e8
 
 
 
 
 
 
 
 
 
 
19221a0
 
 
 
bc45c22
 
19221a0
 
bc45c22
 
19221a0
 
 
 
 
bc45c22
 
19221a0
 
bc45c22
 
19221a0
 
 
 
 
bc45c22
 
19221a0
 
 
 
 
 
bc45c22
 
19221a0
 
 
bc45c22
 
19221a0
 
 
 
 
bc45c22
 
19221a0
 
 
bc45c22
 
19221a0
 
 
 
 
 
bc45c22
 
19221a0
 
bc45c22
 
19221a0
 
 
 
 
bc45c22
 
19221a0
 
bc45c22
 
19221a0
 
 
 
 
bc45c22
 
19221a0
 
 
 
 
 
bc45c22
 
19221a0
 
 
bc45c22
 
19221a0
 
 
 
 
bc45c22
 
19221a0
 
 
bc45c22
 
19221a0
 
9b12d20
 
 
 
 
 
 
9f411df
 
 
9b12d20
9f411df
12d9531
fc49c8c
76897aa
 
 
 
 
 
 
 
 
 
 
 
 
ffc5e7c
 
 
 
8fe6d31
ffc5e7c
 
 
 
 
 
7894dc2
038b8df
ffc5e7c
 
 
 
d038452
7894dc2
8fe6d31
 
 
ffc5e7c
 
8fe6d31
 
ffc5e7c
 
 
 
 
 
 
 
 
 
5ab6829
 
 
 
ffc5e7c
 
 
 
 
 
 
 
 
 
 
 
 
4f454b4
 
 
 
 
caa412b
4f454b4
ffc5e7c
4f454b4
 
 
 
 
ffc5e7c
 
4f454b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffc5e7c
4f454b4
 
 
d038452
4f454b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a369aa6
 
 
e8321b8
 
 
d110daf
e8321b8
 
 
 
 
 
 
d110daf
e8321b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffc5e7c
 
 
 
 
 
5ab6829
ffc5e7c
5ab6829
ffc5e7c
 
 
 
 
4f454b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ab6829
 
 
4f454b4
 
 
 
 
 
 
 
ffc5e7c
 
 
 
d038452
ffc5e7c
 
 
 
 
 
 
 
5ab6829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f454b4
 
 
bc45c22
 
4f454b4
 
 
 
bc45c22
 
4f454b4
 
 
 
bc45c22
 
4f454b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc45c22
 
4f454b4
 
 
 
 
 
 
 
 
 
 
 
 
 
bc45c22
 
4f454b4
 
021b909
 
 
 
 
 
 
 
 
 
 
 
 
d038452
021b909
8fe6d31
 
021b909
 
 
 
 
d038452
021b909
 
ffc5e7c
 
 
4f454b4
d038452
4f454b4
 
 
a369aa6
e8321b8
 
d110daf
2f0f0e6
e8321b8
d110daf
e8321b8
 
 
 
 
 
4f454b4
f85e1e8
 
 
 
d038452
b5f969d
d038452
 
 
 
f85e1e8
b5f969d
9cf801a
 
 
 
b5f969d
1586274
 
 
 
b5f969d
 
 
 
 
 
9cf801a
 
 
 
 
b5f969d
9cf801a
 
 
d1839af
fc76d90
9cf801a
d110daf
9cf801a
e628e1f
 
9cf801a
 
 
 
d1839af
fc76d90
9cf801a
c9ef9b1
9cf801a
f72d25e
 
9cf801a
f85e1e8
 
1586274
 
 
b5f969d
1586274
 
 
d1839af
1586274
 
d110daf
1586274
 
 
 
 
 
 
 
e628e1f
 
1586274
 
 
b5f969d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f85e1e8
 
d038452
f85e1e8
 
 
 
 
 
 
 
 
 
4f454b4
d038452
4f454b4
 
 
a369aa6
e8321b8
 
d110daf
2f0f0e6
e8321b8
d110daf
e8321b8
 
 
 
 
 
4f454b4
ffc5e7c
 
e628e1f
 
 
7763303
 
 
 
e628e1f
 
 
7763303
 
 
e628e1f
 
7763303
 
 
 
 
e628e1f
 
 
 
7763303
 
 
e628e1f
 
7763303
 
 
 
 
e628e1f
 
 
 
7763303
 
 
e628e1f
 
7763303
 
 
 
 
e628e1f
 
cea2220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc49c8c
 
 
 
 
4eba8ec
 
7ae669f
fc49c8c
 
ca0db99
4eba8ec
cea2220
ca0db99
fc49c8c
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
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
"""Portfolio Intelligence Platform - Gradio Interface.

Main application file for the hackathon demo.
Features:
- Single-page workflow (input β†’ loading β†’ results)
- Unified dashboard with responsive bento grid layout
- Auto-refreshing visualisations
- Full-screen responsive design
- Agent reasoning transparency
"""

import os
import warnings
from dotenv import load_dotenv

# Load environment variables first (before any other imports)
load_dotenv()

# Configure logging early (before other imports create loggers)
# Controlled via environment variables:
#   LOG_LEVEL: DEBUG, INFO, WARNING, ERROR, CRITICAL, OFF
#   LOGGING_ENABLED: true/false
from backend.logging_config import configure_logging
configure_logging()

# Disable telemetry on HuggingFace Spaces
if os.environ.get("SPACE_ID"):
    os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
    os.environ["HF_HUB_DISABLE_TELEMETRY"] = "true"

# Now import remaining modules
import gradio as gr
import asyncio
import re
import logging
import time
import random
import numpy as np
import traceback
import sys
from typing import List, Dict, Any, Tuple, Optional
from datetime import datetime

# Initialise Sentry monitoring early (before other imports that might raise errors)
from backend.monitoring import initialise_sentry
initialise_sentry()

from backend.mcp_router import mcp_router
from backend import mcp_tools
from backend.agents.workflow import PortfolioAnalysisWorkflow
from backend.models.agent_state import AgentState
from backend.database import db
from backend.theme import get_financial_theme, FINANCIAL_CSS
from backend.visualizations import (
    create_portfolio_allocation_chart,
    create_risk_metrics_dashboard,
    create_performance_chart,
    create_correlation_heatmap,
    create_optimization_comparison,
)
from backend.stress_testing import (
    PortfolioStressTest,
    STRESS_SCENARIOS,
    create_monte_carlo_paths_plot,
    create_scenario_comparison_chart,
    create_drawdown_analysis_chart,
    create_stress_test_dashboard,
)
from backend.agents.personas import get_available_personas
from backend.tax.interface import create_tax_analysis, format_tax_analysis_output
from backend.config import settings
from backend.rate_limiting import (
    GradioRateLimitMiddleware,
    UserTier,
)
from backend.rate_limiting.fixed_window import TieredFixedWindowLimiter
from backend.auth import auth, UserSession
from backend.export import export_analysis_to_csv, export_analysis_to_pdf

# Import ensemble predictor at startup so @spaces.GPU decorator is detected by ZeroGPU
# This module contains GPU-accelerated ML forecasting (Chronos, TTM, N-HiTS)
import backend.mcp_servers.ensemble_predictor_mcp  # noqa: F401

def check_authentication(session_state: Dict) -> bool:
    """Check if user is authenticated or in demo mode."""
    if not session_state:
        return False

    # Allow demo mode (rate-limited anonymous access)
    if session_state.get("is_demo", False):
        return True

    # Check regular authentication
    session = UserSession.from_dict(session_state)
    return session is not None and session.user_id is not None

# Suppress websockets deprecation warnings
# Note: websockets 15.0+ deprecated WebSocketServerProtocol used by uvicorn 0.38.0
# This is a known issue with no functionality impact. The legacy API is supported until 2030.
# To eliminate warnings: upgrade to uvicorn 0.35.0+ when available with SansIO implementation
# See: https://websockets.readthedocs.io/en/stable/project/changelog.html
warnings.filterwarnings("ignore", category=DeprecationWarning, module="websockets.legacy")
warnings.filterwarnings("ignore", category=DeprecationWarning, module="websockets.server")

# Suppress Gradio internal deprecation warnings
warnings.filterwarnings("ignore", category=DeprecationWarning, module="gradio.routes")

# Get logger for this module (logging already configured via configure_logging())
logger = logging.getLogger(__name__)

# Initialize workflow
workflow = PortfolioAnalysisWorkflow(mcp_router)

# Custom get_user_tier function for session-aware rate limiting
def get_user_tier_from_session(request: Optional[gr.Request], session_state: Optional[dict] = None):
    """Determine user tier from session state.

    Args:
        request: Gradio request object
        session_state: Session state dict containing user authentication info

    Returns:
        Tuple of (identifier, tier)
        - For authenticated users: (user_id, AUTHENTICATED)
        - For demo mode: (ip_hash, ANONYMOUS)
    """
    import hashlib

    # Check if user is authenticated via session state
    if session_state and isinstance(session_state, dict):
        user_id = session_state.get("user_id")
        is_demo = session_state.get("is_demo", False)

        # Authenticated user: use user_id for rate limiting
        if user_id and not is_demo:
            return str(user_id), UserTier.AUTHENTICATED

    # Demo mode or unauthenticated: use IP-based rate limiting
    # Extract client IP from request
    client_ip = "unknown"

    if request:
        try:
            if hasattr(request, "client") and request.client:
                if hasattr(request.client, "host"):
                    client_ip = request.client.host
                elif isinstance(request.client, str):
                    client_ip = request.client

            # Check headers for forwarded IPs (behind proxy)
            if hasattr(request, "headers"):
                forwarded = request.headers.get("X-Forwarded-For")
                if forwarded:
                    client_ip = forwarded.split(",")[0].strip()
        except Exception as e:
            logger.warning(f"Error extracting client IP: {e}")

    # Hash IP for privacy
    identifier = hashlib.sha256(client_ip.encode()).hexdigest()[:16]

    return identifier, UserTier.ANONYMOUS


# Initialize rate limiter
rate_limiter = None
rate_limit_middleware = None

if settings.rate_limit_enabled:
    try:
        rate_limiter = TieredFixedWindowLimiter(
            tier_limits={
                UserTier.ANONYMOUS: settings.rate_limit_anonymous_capacity,
                UserTier.AUTHENTICATED: settings.rate_limit_authenticated_capacity,
                UserTier.PREMIUM: settings.rate_limit_premium_capacity,
            },
            redis_url=settings.redis_url
        )
        rate_limit_middleware = GradioRateLimitMiddleware(
            rate_limiter,
            get_user_tier=get_user_tier_from_session
        )
        logger.info("Rate limiting enabled with fixed window (daily reset at midnight UTC)")
    except Exception as e:
        logger.error(f"Failed to initialise rate limiter: {e}")
        logger.warning("Continuing without rate limiting")
else:
    logger.info("Rate limiting disabled")

# Global state for visualisations
LAST_ANALYSIS_STATE = None
HISTORY_RECORDS = []  # Stores loaded history records for row selection
LAST_STRESS_TEST = None
LAST_EXPORT_PDF_PATH = None  # Pre-generated PDF export path
LAST_EXPORT_CSV_PATH = None  # Pre-generated CSV export path

# Global state for audio generation
LAST_ANALYSIS_TEXT = None  # Stores analysis text for audio generation
LAST_BUILD_RESULT = None  # Stores build portfolio result for audio
LAST_DEBATE_DATA = None  # Stores debate data for audio simulation

# Loading screen rotating messages with MCP phases and disclaimers
LOADING_MESSAGES = [
    "MCP Workflow: Initialising Model Context Protocol servers...",
    "Disclaimer: This is NOT financial advice - consult a professional!",
    "MCP: Aggregating context from multiple data sources...",
    "Humour: If in doubt, blame the algorithm!",
    "MCP Workflow: Processing portfolio through context pipeline...",
    "Warning: Past performance does not guarantee future results!",
    "MCP: Routing requests to specialised analysis servers...",
    "Remember: Markets can stay irrational longer than you can stay solvent!",
    "MCP Workflow: Extracting insights from financial context...",
    "Important: Not a substitute for professional financial guidance!",
    "MCP: Coordinating between data, analysis, and reporting contexts...",
    "Pro tip: Diversification - the only free lunch in investing!",
    "Phase 1: Fetching market data from Yahoo Finance, FMP, FRED...",
    "Phase 2: Running portfolio optimisation and risk analysis...",
    "Phase 3: Generating AI insights with Claude Sonnet 4.5...",
    "Data Collection: Retrieving real-time quotes and historical prices...",
    "Computation: Calculating portfolio metrics and risk indicators...",
    "Analysis: Synthesising comprehensive portfolio recommendations...",
]


def parse_portfolio_input(portfolio_text: str) -> List[Dict[str, Any]]:
    """Parse portfolio input text into structured holdings.

    Supports formats:
    - AAPL 50 (50 shares)
    - TSLA 25 shares
    - NVDA $5000 (dollar amount)
    - BTC 0.5 (fractional shares/crypto)

    Args:
        portfolio_text: Raw text input from user

    Returns:
        List of holding dictionaries
    """
    holdings = []
    lines = portfolio_text.strip().split('\n')

    for line in lines:
        line = line.strip()
        if not line:
            continue

        # Match patterns: TICKER QUANTITY [shares] or TICKER $AMOUNT
        match = re.match(r'([A-Za-z]+)\s+(\$)?([0-9.]+)\s*(shares)?', line, re.IGNORECASE)
        if match:
            ticker = match.group(1).upper()
            is_dollar = match.group(2) == '$'
            amount = float(match.group(3))

            holdings.append({
                'ticker': ticker,
                'quantity': amount if not is_dollar else 0,
                'dollar_amount': amount if is_dollar else 0,
                'cost_basis': 0
            })
        else:
            logger.warning(f"Could not parse line: {line}")

    return holdings


def aggregate_holdings(holdings: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
    """Aggregate holdings by ticker while preserving lot-level data.

    Groups multiple entries for the same ticker together and tracks
    individual tax lots. Useful for handling duplicate entries and
    mixed entry types (shares + dollars).

    Args:
        holdings: List of holding dictionaries from parse_portfolio_input

    Returns:
        Dictionary with ticker as key and aggregated data as value,
        containing: ticker, total_quantity, total_dollar_amount, lots, warnings
    """
    aggregated = {}

    for holding in holdings:
        ticker = holding['ticker']

        if ticker not in aggregated:
            aggregated[ticker] = {
                'ticker': ticker,
                'total_quantity': 0,
                'total_dollar_amount': 0,
                'lots': [],
                'warnings': []
            }

        aggregated[ticker]['total_quantity'] += holding.get('quantity', 0)
        aggregated[ticker]['total_dollar_amount'] += holding.get('dollar_amount', 0)
        aggregated[ticker]['lots'].append(holding)

    # Check for duplicates and mixed entry types
    for ticker, data in aggregated.items():
        if len(data['lots']) > 1:
            has_shares = any(lot['quantity'] > 0 for lot in data['lots'])
            has_dollars = any(lot['dollar_amount'] > 0 for lot in data['lots'])

            if has_shares and has_dollars:
                data['warnings'].append(
                    f"{ticker} has mixed entry types (shares and dollars). "
                    f"Total: {data['total_quantity']:.2f} sh + ${data['total_dollar_amount']:,.2f}"
                )
            else:
                data['warnings'].append(
                    f"{ticker} appears {len(data['lots'])} times. "
                    f"Aggregated: {data['total_quantity']:.2f} shares" if has_shares
                    else f"Aggregated: ${data['total_dollar_amount']:,.2f}"
                )

    return aggregated


async def run_analysis(
    portfolio_text: str,
    roast_mode: bool = False,
    persona: Optional[str] = None
) -> str:
    """Run portfolio analysis workflow.

    Args:
        portfolio_text: Raw portfolio input
        roast_mode: If True, use brutal honesty mode
        persona: Optional investor persona (e.g., 'warren_buffett')

    Returns:
        Formatted analysis result
    """
    global LAST_ANALYSIS_STATE

    if not portfolio_text.strip():
        return "❌ Please enter your portfolio holdings"

    try:
        holdings = parse_portfolio_input(portfolio_text)
        if not holdings:
            return "❌ Could not parse portfolio. Please use format: TICKER QUANTITY"

        logger.info(
            f"Starting analysis for {len(holdings)} holdings "
            f"(Roast Mode: {roast_mode}, Persona: {persona or 'None'})"
        )

        # Construct initial state
        portfolio_id = f"demo_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        initial_state: AgentState = {
            'portfolio_id': portfolio_id,
            'user_query': 'Analyse my portfolio',
            'risk_tolerance': 'moderate',
            'holdings': holdings,
            'historical_prices': {},
            'fundamentals': {},
            'economic_data': {},
            'realtime_data': {},
            'technical_indicators': {},
            'optimisation_results': {},
            'risk_analysis': {},
            'ai_synthesis': '',
            'recommendations': [],
            'reasoning_steps': [],
            'current_step': 'starting',
            'errors': [],
            'mcp_calls': [],
            'phase_1_duration_ms': None,
            'phase_1_5_duration_ms': None,
            'phase_2_duration_ms': None,
            'phase_2_5_duration_ms': None,
            'phase_3_duration_ms': None,
            'llm_input_tokens': None,
            'llm_output_tokens': None,
            'llm_total_tokens': None,
            'llm_request_count': None,
            'feature_vectors': {},
            'ensemble_forecasts': {},
            'sentiment_data': {},
        }

        # Create workflow with persona or roast mode
        # Note: persona takes precedence over roast mode
        if persona and persona != "standard":
            analysis_workflow = PortfolioAnalysisWorkflow(mcp_router, persona=persona)
        else:
            analysis_workflow = PortfolioAnalysisWorkflow(mcp_router, roast_mode=roast_mode)

        # Run workflow
        final_state = await analysis_workflow.run(initial_state)
        LAST_ANALYSIS_STATE = final_state

        if final_state.get("errors"):
            return f"❌ Analysis failed: {'; '.join(final_state['errors'])}"

        # Format result
        return format_analysis_result(final_state, holdings)

    except Exception as e:
        logger.error(f"Analysis error: {e}", exc_info=True)
        return f"❌ Error during analysis: {str(e)}"


def format_performance_metrics(final_state: AgentState) -> str:
    """Format performance metrics for reasoning display.

    Args:
        final_state: Final AgentState from workflow

    Returns:
        Formatted markdown string with performance metrics
    """
    metrics_md = "### Performance Metrics\n\n"

    # Phase Execution Times
    phase_1_ms = final_state.get("phase_1_duration_ms", 0) or 0
    phase_2_ms = final_state.get("phase_2_duration_ms", 0) or 0
    phase_2_5_ms = final_state.get("phase_2_5_duration_ms", 0) or 0
    phase_3_ms = final_state.get("phase_3_duration_ms", 0) or 0
    total_ms = phase_1_ms + phase_2_ms + phase_2_5_ms + phase_3_ms

    metrics_md += "**Execution Timeline:**\n\n"
    metrics_md += f"- Phase 1 (Data Collection): {phase_1_ms:,}ms\n"
    metrics_md += f"- Phase 2 (Computation): {phase_2_ms:,}ms\n"
    if phase_2_5_ms > 0:
        metrics_md += f"- Phase 2.5 (ML Predictions): {phase_2_5_ms:,}ms\n"
    metrics_md += f"- Phase 3 (LLM Synthesis): {phase_3_ms:,}ms\n"
    metrics_md += f"- **Total**: {total_ms:,}ms ({total_ms / 1000:.2f}s)\n\n"

    # LLM Token Usage
    input_tokens = final_state.get("llm_input_tokens", 0) or 0
    output_tokens = final_state.get("llm_output_tokens", 0) or 0
    total_tokens = final_state.get("llm_total_tokens", 0) or 0
    request_count = final_state.get("llm_request_count", 0) or 0

    # Anthropic Claude Sonnet 4.5 pricing (as of early 2025)
    # Input: $3 per million tokens, Output: $15 per million tokens
    input_cost = (input_tokens / 1_000_000) * 3.0
    output_cost = (output_tokens / 1_000_000) * 15.0
    total_cost = input_cost + output_cost

    metrics_md += "**LLM Token Usage (Claude Sonnet 4.5):**\n\n"
    metrics_md += f"- Input Tokens: {input_tokens:,} (${input_cost:.4f})\n"
    metrics_md += f"- Output Tokens: {output_tokens:,} (${output_cost:.4f})\n"
    metrics_md += f"- **Total**: {total_tokens:,} tokens (${total_cost:.4f})\n"
    metrics_md += f"- API Requests: {request_count}\n\n"

    # MCP Calls
    mcp_calls = final_state.get("mcp_calls", [])
    if mcp_calls:
        metrics_md += f"**MCP Operations:** {len(mcp_calls)} total calls\n\n"

        # Group by MCP server
        mcp_groups = {}
        for call in mcp_calls:
            server = call.get("mcp_server") or call.get("mcp", "unknown")
            if server not in mcp_groups:
                mcp_groups[server] = []
            mcp_groups[server].append(call)

        for server, calls in mcp_groups.items():
            metrics_md += f"- **{server}**: {len(calls)} call{'s' if len(calls) != 1 else ''}\n"

    return metrics_md


def format_analysis_result(final_state: AgentState, holdings: List[Dict[str, Any]]) -> str:
    """Format analysis result for display.

    Args:
        final_state: Final AgentState from workflow
        holdings: Original holdings list

    Returns:
        Formatted markdown string
    """
    # Calculate total portfolio value
    total_value = sum(h.get('market_value', 0) for h in final_state.get('holdings', holdings))

    # Format holdings
    holdings_md = "### Portfolio Holdings\n\n"
    for h in final_state.get('holdings', holdings):
        ticker = h.get("ticker", "N/A")
        shares = h.get("quantity", 0)
        value = h.get("market_value", 0)
        weight = (value / total_value * 100) if total_value > 0 else 0

        # Format differently based on whether entered by shares or dollar amount
        if shares > 0:
            holdings_md += f"- **{ticker}**: {shares:.2f} shares | ${value:,.2f} ({weight:.1f}%)\n"
        else:
            holdings_md += f"- **{ticker}**: ${value:,.2f} ({weight:.1f}%)\n"

    # Extract risk metrics from risk_analysis
    risk_analysis = final_state.get("risk_analysis", {})

    # Extract from nested dicts
    var_95_dict = risk_analysis.get("var_95", {})
    var_95 = abs(float(var_95_dict.get("var_absolute", 0))) if isinstance(var_95_dict, dict) else abs(float(var_95_dict))

    cvar_95_dict = risk_analysis.get("cvar_95", {})
    cvar_95 = abs(float(cvar_95_dict.get("cvar_absolute", 0))) if isinstance(cvar_95_dict, dict) else abs(float(cvar_95_dict))

    risk_metrics = risk_analysis.get("risk_metrics", {})
    sharpe = float(risk_metrics.get("sharpe_ratio", 0))
    volatility = float(risk_metrics.get("volatility_annual", 0)) * 100

    # Extract advanced metrics
    information_ratio = risk_metrics.get("information_ratio")
    calmar_ratio = risk_metrics.get("calmar_ratio")
    ulcer_index = risk_metrics.get("ulcer_index")

    metrics_md = f"""
### Key Metrics

- **Portfolio Value**: ${total_value:,.2f}
- **Sharpe Ratio**: {sharpe:.2f}
- **Volatility**: {volatility:.1f}% (annual)
- **VaR (95%)**: ${var_95:,.2f}
- **CVaR (95%)**: ${cvar_95:,.2f}
"""

    # Add advanced metrics if available
    if information_ratio is not None:
        metrics_md += f"- **Information Ratio**: {float(information_ratio):.2f}\n"
    if calmar_ratio is not None:
        metrics_md += f"- **Calmar Ratio**: {float(calmar_ratio):.2f}\n"
    if ulcer_index is not None:
        metrics_md += f"- **Ulcer Index**: {float(ulcer_index):.2f}\n"

    # Format ML forecasts if available
    forecasts_md = ""
    ensemble_forecasts = final_state.get("ensemble_forecasts", {})
    if ensemble_forecasts:
        forecasts_md = "### ML Price Forecasts (30-day)\n\n"
        for ticker, forecast_data in ensemble_forecasts.items():
            if isinstance(forecast_data, dict):
                models_used = forecast_data.get("models_used", [])
                num_models = len(models_used) if models_used else forecast_data.get("metadata", {}).get("num_models", "N/A")

                # Get first and last prediction (current vs 30-day)
                predictions = forecast_data.get("predictions", [])
                if predictions and len(predictions) > 0:
                    first_pred = float(predictions[0])
                    last_pred = float(predictions[-1])
                    change_pct = ((last_pred - first_pred) / first_pred * 100) if first_pred > 0 else 0

                    direction = "πŸ“ˆ" if change_pct > 0 else "πŸ“‰" if change_pct < 0 else "➑️"
                    forecasts_md += f"- **{ticker}**: {direction} {change_pct:+.1f}% (using {num_models} models)\n"

        forecasts_md += "\n*Note: Forecasts combine Chronos foundation model with statistical baselines.*\n\n"

    # Get LLM synthesis and recommendations
    ai_synthesis = final_state.get("ai_synthesis", "Analysis completed successfully.")
    recommendations = final_state.get("recommendations", [])

    recs_md = "### Recommendations\n\n"
    if recommendations:
        for i, rec in enumerate(recommendations, 1):
            recs_md += f"{i}. {rec}\n"
    else:
        recs_md += "*No specific recommendations generated.*\n"

    # Final output
    output = f"""{holdings_md}

{metrics_md}

{forecasts_md}
{ai_synthesis}

{recs_md}

---

*Interactive charts and detailed metrics are displayed below.*
"""

    return output


def create_visualisations() -> Tuple:
    """Create all visualisation charts from last analysis.

    Returns:
        Tuple of (allocation, risk, performance, correlation, optimization) plots
    """
    global LAST_ANALYSIS_STATE

    if not LAST_ANALYSIS_STATE:
        empty_fig = None
        return (empty_fig, empty_fig, empty_fig, empty_fig, empty_fig)

    # Extract data from AgentState
    holdings = LAST_ANALYSIS_STATE.get("holdings", [])
    historical_prices = LAST_ANALYSIS_STATE.get("historical_prices", {})
    risk_analysis = LAST_ANALYSIS_STATE.get("risk_analysis", {})
    optimisation_results = LAST_ANALYSIS_STATE.get("optimisation_results", {})

    # Create charts
    allocation_chart = create_portfolio_allocation_chart(holdings) if holdings else None

    # Extract nested risk metrics correctly
    if risk_analysis:
        var_95_dict = risk_analysis.get("var_95", {})
        var_value = float(var_95_dict.get("var_percentage", 0)) if isinstance(var_95_dict, dict) else float(var_95_dict)

        cvar_95_dict = risk_analysis.get("cvar_95", {})
        cvar_value = float(cvar_95_dict.get("cvar_percentage", 0)) if isinstance(cvar_95_dict, dict) else float(cvar_95_dict)

        risk_metrics = risk_analysis.get("risk_metrics", {})
        sharpe_value = float(risk_metrics.get("sharpe_ratio", 0))
        volatility_value = float(risk_metrics.get("volatility_annual", 0)) * 100

        risk_chart = create_risk_metrics_dashboard(
            sharpe=sharpe_value,
            var=var_value,
            cvar=cvar_value,
            volatility=volatility_value
        )
    else:
        risk_chart = None

    performance_chart = create_performance_chart(holdings, historical_prices) if historical_prices else None
    correlation_chart = create_correlation_heatmap(historical_prices) if historical_prices else None
    optimization_chart = create_optimization_comparison(optimisation_results) if optimisation_results else None

    return (allocation_chart, risk_chart, performance_chart, correlation_chart, optimization_chart)


async def run_stress_test(
    scenario_name: str,
    n_simulations: int = 10000,
    time_horizon_days: int = 252
) -> Tuple[str, Any, Any, Any, Any]:
    """Run stress test on current portfolio.

    Args:
        scenario_name: Name of stress scenario to apply
        n_simulations: Number of Monte Carlo simulations
        time_horizon_days: Simulation time horizon in days

    Returns:
        Tuple of (summary_text, dashboard_plot, mc_plot, scenario_plot, drawdown_plot)
    """
    global LAST_ANALYSIS_STATE, LAST_STRESS_TEST

    if not LAST_ANALYSIS_STATE:
        return (
            "Please run portfolio analysis first before stress testing.",
            None, None, None, None
        )

    try:
        # Extract portfolio data
        holdings = LAST_ANALYSIS_STATE.get("holdings", [])
        historical_prices = LAST_ANALYSIS_STATE.get("historical_prices", {})

        if not holdings or not historical_prices:
            return (
                "Insufficient portfolio data for stress testing.",
                None, None, None, None
            )

        # Initialise stress tester
        stress_tester = PortfolioStressTest(
            holdings=holdings,
            historical_prices=historical_prices,
            n_simulations=n_simulations
        )

        LAST_STRESS_TEST = stress_tester

        # Get portfolio value
        portfolio_value = sum(h.get('market_value', 0) for h in holdings)

        # Run selected scenario or Monte Carlo
        if scenario_name == "monte_carlo":
            result = stress_tester.run_monte_carlo(time_horizon_days=time_horizon_days)
            dashboard_plot = create_stress_test_dashboard(result, portfolio_value)
            mc_plot = create_monte_carlo_paths_plot(result.simulation_paths, portfolio_value=portfolio_value)
            drawdown_plot = create_drawdown_analysis_chart(result.simulation_paths, portfolio_value=portfolio_value)
            scenario_plot = None

            summary = f"""# Monte Carlo Stress Test Results

**Simulation Parameters:**
- Number of simulations: {n_simulations:,}
- Time horizon: {time_horizon_days} days (~{time_horizon_days/252:.1f} years)

**Key Metrics:**
- Mean return: {result.portfolio_return:.2f}%
- Value at Risk (95%): {result.var_95:.2f}%
- Conditional VaR (95%): {result.cvar_95:.2f}%
- Maximum drawdown: {result.max_drawdown:.2f}%

**Interpretation:**
- In 95% of scenarios, your portfolio loses less than {abs(result.var_95):.1f}%
- In the worst 5% of cases, average loss is {abs(result.cvar_95):.1f}%
"""

        elif scenario_name == "all_scenarios":
            all_results = stress_tester.run_all_scenarios()
            scenario_plot = create_scenario_comparison_chart(all_results)
            dashboard_plot = None
            mc_plot = None
            drawdown_plot = None

            summary = "# All Stress Scenarios Comparison\n\n"
            summary += "**Portfolio Performance Under Historical Crises:**\n\n"

            for scenario_id, result in all_results.items():
                recovery_text = f"{result.recovery_time_estimate} days (~{result.recovery_time_estimate/365:.1f} years)" if result.recovery_time_estimate else "N/A"
                summary += f"### {result.scenario_name}\n"
                summary += f"- Portfolio return: **{result.portfolio_return:.2f}%**\n"
                summary += f"- Value change: **${result.portfolio_value_change:,.0f}**\n"
                summary += f"- VaR 95%: {result.var_95:.2f}%\n"
                summary += f"- CVaR 95%: {result.cvar_95:.2f}%\n"
                summary += f"- Estimated recovery: {recovery_text}\n\n"

        else:
            # Run specific scenario
            scenario = STRESS_SCENARIOS.get(scenario_name)
            if not scenario:
                return (
                    f"Scenario '{scenario_name}' not found.",
                    None, None, None, None
                )

            result = stress_tester.apply_scenario(scenario)
            dashboard_plot = create_stress_test_dashboard(result, portfolio_value)
            mc_plot = None
            scenario_plot = None
            drawdown_plot = None

            recovery_text = f"{result.recovery_time_estimate} days (~{result.recovery_time_estimate/365:.1f} years)" if result.recovery_time_estimate else "Not estimated"

            summary = f"""# {result.scenario_name} - Stress Test Results

**Scenario Description:**
{scenario.description}

**Portfolio Impact:**
- Return under stress: **{result.portfolio_return:.2f}%**
- Dollar impact: **${result.portfolio_value_change:,.0f}**
- Current value: ${portfolio_value:,.0f}
- Stressed value: ${portfolio_value + result.portfolio_value_change:,.0f}

**Risk Metrics:**
- Value at Risk (95%): {result.var_95:.2f}%
- Conditional VaR (95%): {result.cvar_95:.2f}%
- Value at Risk (99%): {result.var_99:.2f}%
- Conditional VaR (99%): {result.cvar_99:.2f}%

**Recovery Estimate:**
- Estimated recovery time: {recovery_text}

**Asset Contributions:**
"""
            for ticker, contribution in sorted(result.asset_contributions.items(), key=lambda x: x[1]):
                summary += f"- {ticker}: {contribution:+.2f}%\n"

        return (summary, dashboard_plot, mc_plot, scenario_plot, drawdown_plot)

    except Exception as e:
        logger.error(f"Stress test error: {e}", exc_info=True)
        return (
            f"Error running stress test: {str(e)}",
            None, None, None, None
        )


async def run_analysis_with_ui_update(
    session_state: Optional[Dict] = None,
    portfolio_text: str = "",
    roast_mode: bool = False,
    persona: Optional[str] = None,
    progress=gr.Progress()
) -> Tuple[str, str, str, Any, Any, Any, Any, Any, Any]:
    """Run analysis and return results with loading progress overlay.

    Uses rotating messages from LOADING_MESSAGES to display progress updates.

    Args:
        session_state: Session state dict containing user authentication info
        portfolio_text: Portfolio input
        roast_mode: If True, use brutal honesty mode
        persona: Optional investor persona (e.g., 'warren_buffett')
        progress: Gradio progress tracker

    Returns:
        Tuple of (page_state, analysis_text, performance_metrics, 5 charts, audio_btn_update)
    """
    global LAST_ANALYSIS_STATE

    if not portfolio_text.strip():
        return (
            "input",
            "",
            "",
            None, None, None, None, None,
            gr.update(visible=False)
        )

    try:
        progress(0, desc=random.choice(LOADING_MESSAGES))
        await asyncio.sleep(0.3)

        holdings = parse_portfolio_input(portfolio_text)
        if not holdings:
            return (
                "input",
                "",
                "",
                None, None, None, None, None,
                gr.update(visible=False)
            )

        progress(0.1, desc=random.choice(LOADING_MESSAGES))
        await asyncio.sleep(0.5)

        # Check if this is a demo session
        is_demo = session_state.get("is_demo", False) if session_state else False

        # Generate portfolio ID with appropriate prefix
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        if is_demo:
            portfolio_id = f"demo_{timestamp}"
        else:
            # Authenticated users get portfolio IDs with user prefix
            session = UserSession.from_dict(session_state)
            user_prefix = session.username[:8] if session and session.username else "user"
            portfolio_id = f"{user_prefix}_{timestamp}"

        # Only save portfolio to database for authenticated users
        # Demo users get ephemeral portfolios that exist only for the current session
        if not is_demo:
            try:
                session = UserSession.from_dict(session_state)
                user_id = session.user_id if session and session.user_id else None

                if not user_id:
                    logger.error("No valid user_id available for portfolio creation")
                    raise ValueError("User ID not available")

                portfolio_saved = await db.save_portfolio(
                    portfolio_id=portfolio_id,
                    user_id=user_id,
                    name=f"Analysis {datetime.now().strftime('%Y-%m-%d %H:%M')}",
                    risk_tolerance='moderate'
                )

                if portfolio_saved:
                    logger.info(f"βœ“ Portfolio {portfolio_id} created for user {user_id}")
                else:
                    logger.error(f"βœ— Failed to create portfolio {portfolio_id} in database")
                    raise ValueError(f"Portfolio creation failed for {portfolio_id}")

            except Exception as e:
                logger.error(f"βœ— Failed to save portfolio: {e}")
                raise ValueError(f"Database error: {e}") from e
        else:
            logger.info(f"Demo mode: Portfolio {portfolio_id} created (ephemeral, not saved to database)")

        initial_state: AgentState = {
            'portfolio_id': portfolio_id,
            'user_query': 'Analyse my portfolio',
            'risk_tolerance': 'moderate',
            'holdings': holdings,
            'historical_prices': {},
            'fundamentals': {},
            'economic_data': {},
            'realtime_data': {},
            'technical_indicators': {},
            'optimisation_results': {},
            'risk_analysis': {},
            'ai_synthesis': '',
            'recommendations': [],
            'reasoning_steps': [],
            'current_step': 'starting',
            'errors': [],
            'mcp_calls': [],
            'phase_1_duration_ms': None,
            'phase_1_5_duration_ms': None,
            'phase_2_duration_ms': None,
            'phase_2_5_duration_ms': None,
            'phase_3_duration_ms': None,
            'llm_input_tokens': None,
            'llm_output_tokens': None,
            'llm_total_tokens': None,
            'llm_request_count': None,
            'feature_vectors': {},
            'ensemble_forecasts': {},
            'sentiment_data': {},
        }

        progress(0.2, desc="Phase 1: Fetching market data from Yahoo Finance, FMP, FRED...")

        # Create workflow with persona or roast mode
        # Note: persona takes precedence over roast mode
        if persona and persona != "standard":
            analysis_workflow = PortfolioAnalysisWorkflow(mcp_router, persona=persona)
        else:
            analysis_workflow = PortfolioAnalysisWorkflow(mcp_router, roast_mode=roast_mode)

        # Stream workflow execution with live progress updates
        final_state = None
        async for event in analysis_workflow.stream(initial_state):
            progress_val = event.get("progress", 0)
            message = event.get("message", "Processing...")
            progress(progress_val, desc=message)
            if event.get("event") == "complete":
                final_state = event.get("state")
                break
            final_state = event.get("state")

        if final_state is None:
            raise ValueError("Workflow did not return final state")
        LAST_ANALYSIS_STATE = final_state

        # Pre-generate export files immediately after analysis completes
        # This ensures DownloadButton has files ready on first click
        global LAST_EXPORT_PDF_PATH, LAST_EXPORT_CSV_PATH
        try:
            import tempfile

            # Generate PDF export
            pdf_bytes = export_analysis_to_pdf(final_state)
            with tempfile.NamedTemporaryFile(
                mode='wb',
                delete=False,
                suffix='.pdf',
                prefix='portfolio_analysis_',
                dir=tempfile.gettempdir()
            ) as f:
                f.write(pdf_bytes)
                LAST_EXPORT_PDF_PATH = f.name
                logger.info(f"Pre-generated PDF export: {LAST_EXPORT_PDF_PATH}")

            # Generate CSV export
            csv_content = export_analysis_to_csv(final_state)
            with tempfile.NamedTemporaryFile(
                mode='w',
                delete=False,
                suffix='.csv',
                prefix='portfolio_analysis_',
                dir=tempfile.gettempdir()
            ) as f:
                f.write(csv_content)
                LAST_EXPORT_CSV_PATH = f.name
                logger.info(f"Pre-generated CSV export: {LAST_EXPORT_CSV_PATH}")
        except Exception as e:
            logger.error(f"Failed to pre-generate export files: {e}")
            LAST_EXPORT_PDF_PATH = None
            LAST_EXPORT_CSV_PATH = None

        # Save analysis to database (Enhancement #4 - Historical Analysis Storage)
        # Only save for authenticated users - demo analyses are ephemeral
        if not is_demo:
            try:
                session = UserSession.from_dict(session_state)
                user_identifier = session.user_id if session and session.user_id else "unknown"

                logger.info(f"Saving analysis for portfolio {portfolio_id}, user: {user_identifier}")

                save_result = await db.save_analysis(portfolio_id, final_state)
                if save_result:
                    logger.info(f"βœ“ Successfully saved analysis for portfolio {portfolio_id}")
                else:
                    logger.error(f"βœ— Failed to save analysis for portfolio {portfolio_id} (returned False)")
                    # Note: We don't raise here because the analysis itself succeeded
                    # The user still gets their results even if database save fails
            except Exception as e:
                logger.error(f"βœ— Exception saving analysis for portfolio {portfolio_id}: {e}", exc_info=True)
                # Note: We don't raise here because the analysis itself succeeded
        else:
            logger.info(f"Demo mode: Analysis for portfolio {portfolio_id} not saved (ephemeral session)")

        charts = create_visualisations()
        analysis_text = format_analysis_result(final_state, holdings)
        performance_metrics = format_performance_metrics(final_state)

        progress(1.0, desc="Analysis complete!")

        return (
            "results",
            analysis_text,
            performance_metrics,
            *charts,
            gr.update(visible=True)  # analysis_audio_btn (show audio button)
        )

    except Exception as e:
        logger.error(f"Analysis error: {e}", exc_info=True)
        return (
            "input",
            f"❌ Error: {str(e)}",
            "",
            None, None, None, None, None,
            gr.update(visible=False)  # analysis_audio_btn (hide on error)
        )


def update_live_preview(portfolio_text: str) -> str:
    """Update live preview with parsed portfolio summary (without prices).

    Aggregates duplicate tickers and detects mixed entry types,
    displaying warnings for data quality issues.

    Args:
        portfolio_text: Raw portfolio input text

    Returns:
        HTML formatted preview of portfolio
    """
    if not portfolio_text.strip():
        return """
        <div style='text-align: center; padding: 2rem; color: #999;'>
            <p style='font-size: 14px;'>Enter portfolio holdings to see preview</p>
        </div>
        """

    try:
        holdings = parse_portfolio_input(portfolio_text)
        if not holdings:
            return """
            <div style='text-align: center; padding: 2rem; color: #ef4444;'>
                <p style='font-size: 14px;'>Unable to parse portfolio format</p>
            </div>
            """

        aggregated = aggregate_holdings(holdings)
        unique_tickers = len(aggregated)
        shares_tickers = sum(1 for d in aggregated.values() if d['total_quantity'] > 0)
        dollar_tickers = sum(1 for d in aggregated.values() if d['total_dollar_amount'] > 0)

        warnings = []
        for data in aggregated.values():
            warnings.extend(data['warnings'])

        warnings_html = ""
        if warnings:
            warnings_html = f"""
                <div style='margin-top: 0.75rem; padding: 0.75rem; background: rgba(251, 146, 60, 0.1); border: 1px solid rgba(251, 146, 60, 0.3); border-radius: 6px;'>
                    <p style='margin: 0 0 0.5rem 0; font-size: 11px; text-transform: uppercase; color: #fb923c; font-weight: 600;'>Duplicate/Mixed Entries</p>
            """
            for warning in warnings:
                warnings_html += f"<p style='margin: 0.25rem 0 0 0; font-size: 10px; opacity: 0.9;'>{warning}</p>"
            warnings_html += "</div>"

        html = f"""
        <div style='padding: 1.5rem; display: flex; flex-direction: column;'>
            <h3 style='color: #048CFC; margin-bottom: 1rem; margin-top: 0; font-size: 1.25rem;'>Portfolio Preview</h3>
            <div style='display: grid; gap: 1rem; grid-template-rows: auto 1fr auto; height: 100%;'>
                <div style='border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 0.75rem;'>
                    <p style='margin: 0; font-size: 12px; opacity: 0.7; text-transform: uppercase;'>Unique Tickers</p>
                    <p style='margin: 0.25rem 0 0 0; font-size: 28px; font-weight: 600;'>{unique_tickers}</p>
                    <p style='margin: 0.5rem 0 0 0; font-size: 11px; opacity: 0.6;'>{shares_tickers} by shares β€’ {dollar_tickers} by dollar</p>
                </div>
                <div style='padding-right: 0.5rem; overflow-y: auto; min-height: 0;'>
                    <p style='margin: 0 0 0.75rem 0; font-size: 12px; opacity: 0.7; text-transform: uppercase;'>Assets (Aggregated)</p>
        """

        for ticker, data in sorted(aggregated.items()):
            if data['total_dollar_amount'] > 0 and data['total_quantity'] > 0:
                value_text = f"{data['total_quantity']:.2f} sh + ${data['total_dollar_amount']:,.0f}"
            elif data['total_dollar_amount'] > 0:
                value_text = f"${data['total_dollar_amount']:,.0f}"
            else:
                value_text = f"{data['total_quantity']:.2f} sh"

            html += f"""
                    <div style='display: flex; justify-content: space-between; padding: 0.65rem 0; border-bottom: 1px solid rgba(255,255,255,0.05);'>
                        <span style='font-weight: 500; font-size: 0.95rem;'>{ticker}</span>
                        <span style='opacity: 0.7; font-size: 0.9rem;'>{value_text}</span>
                    </div>
            """

        html += f"""
                </div>
                <div style='margin-top: 0.5rem; padding: 0.75rem; background: rgba(4, 140, 252, 0.1); border-radius: 6px; text-align: center;'>
                    <p style='margin: 0; font-size: 11px; opacity: 0.8;'>Click "Get Current Prices" for live valuation</p>
                </div>
                {warnings_html}
            </div>
        </div>
        """
        return html
    except Exception as e:
        logger.error(f"Preview update error: {e}")
        return f"<div style='color: #ef4444; padding: 1rem;'><p style='font-size: 12px;'>Error: {str(e)}</p></div>"


async def fetch_and_update_preview(portfolio_text: str) -> str:
    """Fetch current prices and update preview with calculated values.

    Aggregates duplicate tickers and displays combined positions
    with pricing information from market data sources.

    Args:
        portfolio_text: Raw portfolio input text

    Returns:
        HTML formatted preview with current prices
    """
    if not portfolio_text.strip():
        return update_live_preview(portfolio_text)

    try:
        holdings = parse_portfolio_input(portfolio_text)
        if not holdings:
            return update_live_preview(portfolio_text)

        aggregated = aggregate_holdings(holdings)

        # Get tickers that need price lookup (have quantity but no dollar_amount)
        tickers_needing_prices = [
            ticker for ticker, data in aggregated.items()
            if data['total_quantity'] > 0 and data['total_dollar_amount'] == 0
        ]

        # Fetch current prices
        prices = {}
        if tickers_needing_prices:
            try:
                from backend.mcp_router import mcp_router
                quote_results = await mcp_router.call_yahoo_finance_mcp(
                    tool="get_quote",
                    params={"tickers": tickers_needing_prices}
                )

                if quote_results and isinstance(quote_results, list):
                    for quote in quote_results:
                        if isinstance(quote, dict) and 'ticker' in quote and 'price' in quote:
                            prices[quote['ticker']] = float(quote['price'])
            except Exception as e:
                logger.error(f"Error fetching prices: {e}")

        # Calculate aggregated values
        total_value = 0
        aggregated_values = {}

        for ticker, data in aggregated.items():
            if data['total_dollar_amount'] > 0:
                aggregated_values[ticker] = data['total_dollar_amount']
                total_value += data['total_dollar_amount']
            elif data['total_quantity'] > 0:
                price = prices.get(ticker, 0)
                value = data['total_quantity'] * price
                aggregated_values[ticker] = value
                total_value += value

        unique_tickers = len(aggregated)
        warnings = []
        for data in aggregated.values():
            warnings.extend(data['warnings'])

        warnings_html = ""
        if warnings:
            warnings_html = f"""
                <div style='margin-top: 0.75rem; padding: 0.75rem; background: rgba(251, 146, 60, 0.1); border: 1px solid rgba(251, 146, 60, 0.3); border-radius: 6px;'>
                    <p style='margin: 0 0 0.5rem 0; font-size: 11px; text-transform: uppercase; color: #fb923c; font-weight: 600;'>Duplicate/Mixed Entries</p>
            """
            for warning in warnings:
                warnings_html += f"<p style='margin: 0.25rem 0 0 0; font-size: 10px; opacity: 0.9;'>{warning}</p>"
            warnings_html += "</div>"

        html = f"""
        <div style='padding: 1.5rem; display: flex; flex-direction: column;'>
            <h3 style='color: #048CFC; margin-bottom: 1rem; margin-top: 0; font-size: 1.25rem;'>Portfolio Summary</h3>
            <div style='display: grid; gap: 1rem; grid-template-rows: auto auto 1fr auto; height: 100%;'>
                <div style='border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 0.75rem;'>
                    <p style='margin: 0; font-size: 12px; opacity: 0.7; text-transform: uppercase;'>Unique Tickers</p>
                    <p style='margin: 0.25rem 0 0 0; font-size: 28px; font-weight: 600;'>{unique_tickers}</p>
                </div>
                <div style='border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 0.75rem;'>
                    <p style='margin: 0; font-size: 12px; opacity: 0.7; text-transform: uppercase;'>Total Value</p>
                    <p style='margin: 0.25rem 0 0 0; font-size: 24px; font-weight: 600; color: #10b981;'>${total_value:,.2f}</p>
                </div>
                <div style='padding-right: 0.5rem; overflow-y: auto; min-height: 0;'>
                    <p style='margin: 0 0 0.75rem 0; font-size: 12px; opacity: 0.7; text-transform: uppercase;'>Holdings Breakdown (Aggregated)</p>
        """

        for ticker in sorted(aggregated.keys()):
            data = aggregated[ticker]
            current_value = aggregated_values.get(ticker, 0)
            weight = (current_value / total_value * 100) if total_value > 0 else 0

            if data['total_dollar_amount'] > 0 and data['total_quantity'] > 0:
                detail = f"{data['total_quantity']:.2f} sh + ${data['total_dollar_amount']:,.2f}"
            elif data['total_dollar_amount'] > 0:
                detail = f"${data['total_dollar_amount']:,.2f}"
            elif data['total_quantity'] > 0:
                price = prices.get(ticker, 0)
                if price > 0:
                    detail = f"{data['total_quantity']:.2f} sh Γ— ${price:.2f}"
                else:
                    detail = f"{data['total_quantity']:.2f} sh (price unavailable)"
            else:
                detail = "β€”"

            html += f"""
                    <div style='display: flex; justify-content: space-between; align-items: center; padding: 0.65rem 0; border-bottom: 1px solid rgba(255,255,255,0.05);'>
                        <div>
                            <div style='font-weight: 500; font-size: 0.95rem;'>{ticker}</div>
                            <div style='font-size: 11px; opacity: 0.6; margin-top: 2px;'>{detail}</div>
                        </div>
                        <div style='text-align: right;'>
                            <div style='font-weight: 600; color: #10b981; font-size: 0.95rem;'>${current_value:,.2f}</div>
                            <div style='font-size: 11px; opacity: 0.6; margin-top: 2px;'>{weight:.1f}%</div>
                        </div>
                    </div>
            """

        html += f"""
                </div>
                <div style='margin-top: 0.5rem; padding: 0.75rem; background: rgba(16, 185, 129, 0.1); border-radius: 6px; text-align: center;'>
                    <p style='margin: 0; font-size: 11px; color: #10b981;'>Prices updated</p>
                </div>
                {warnings_html}
            </div>
        </div>
        """
        return html

    except Exception as e:
        logger.error(f"Fetch preview error: {e}")
        return f"<div style='color: #ef4444; padding: 1rem;'><p style='font-size: 12px;'>Error fetching prices: {str(e)}</p></div>"


def create_interface() -> gr.Blocks:
    """Create the main Gradio interface with single-page workflow.

    Returns:
        Gradio Blocks interface
    """
    theme = get_financial_theme()

    # Custom CSS for full-width and responsive design
    custom_css = FINANCIAL_CSS + """
    /* Full-width container */
    .gradio-container {
        max-width: unset;
        width: 100%;
        padding: 1.5rem 2rem;
    }

    /* Sidebar Styling - Works with gr.Sidebar */
    #main-sidebar {
        background: linear-gradient(135deg, #1e3a5f 0%, #2d5a7b 100%) !important;
    }

    #main-sidebar .sidebar-header {
        color: white !important;
        border-bottom: 2px solid rgba(255,255,255,0.2);
        padding-bottom: 10px;
        margin-bottom: 20px;
    }

    .nav-btn {
        width: 100%;
        margin-bottom: 10px;
        text-align: left !important;
        justify-content: flex-start !important;
        background: rgba(255,255,255,0.05) !important;
        border: 1px solid rgba(255,255,255,0.1) !important;
        color: white !important;
    }

    .nav-btn:hover {
        background: rgba(255,255,255,0.15) !important;
        border-color: rgba(255,255,255,0.3) !important;
    }

    .sidebar-header {
        color: white !important;
        border-bottom: 2px solid rgba(255,255,255,0.2);
        padding-bottom: 10px;
        margin-bottom: 20px;
    }

    /* Ensure all large buttons have consistent font size */
    button.lg,
    .lg button {
        font-size: 1rem !important;
        font-weight: 600 !important;
    }

    /* Dark mode specific container adjustments - theme adaptive */
    .dark .gradio-container {
        background-color: var(--body-background-fill-dark);
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        .gradio-container {
            padding: 1rem;
        }
    }

    /* Better spacing for input section */
    .gr-group {
        padding: 24px;
        margin-bottom: 16px;
    }

    /* Format helper text styling - theme adaptive */
    .format-helper {
        font-size: 14px;
        margin-top: 8px;
    }

    .dark .format-helper {
        color: var(--body-text-color-subdued);
    }

    /* Chart containers with proper sizing */
    .plot-container {
        min-height: 400px;
    }

    /* Example buttons better spacing */
    .gr-examples {
        margin-top: 16px;
    }

    /* Improved markdown sections - theme adaptive */
    .dark .markdown-text {
        color: var(--body-text-color);
    }

    .dark .markdown-text h3 {
        color: var(--body-text-color);
        border-bottom: 1px solid var(--block-border-color);
        padding-bottom: 8px;
    }

    /* Hero section styling */
    #hero-section {
        background: linear-gradient(135deg, #05478A 0%, #048CFC 50%, #11C7AA 100%);
        padding: 3rem 2rem;
        border-radius: 16px;
        text-align: center;
        margin-bottom: 2rem;
        color: white;
    }

    #hero-section h2 {
        font-size: 2.5rem;
        font-weight: 700;
        margin: 0 0 0.5rem 0;
        letter-spacing: -0.025em;
    }

    #hero-section p {
        font-size: 1.125rem;
        opacity: 0.95;
        margin: 0 0 1.5rem 0;
        font-weight: 400;
    }

    #hero-section .value-props {
        display: flex;
        justify-content: center;
        gap: 2rem;
        flex-wrap: wrap;
        margin-top: 1.5rem;
    }

    #hero-section .value-prop {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.95rem;
        font-weight: 500;
    }

    /* Compact feature cards for 1x4 layout */
    .feature-card-compact {
        background: rgba(255, 255, 255, 0.05);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 8px;
        padding: 1rem 0.75rem;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
        text-align: center;
        min-height: 130px;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .feature-card-compact:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        border-color: rgba(4, 140, 252, 0.4);
    }

    .feature-card-compact h4 {
        color: #048CFC;
        margin: 0.5rem 0 0.25rem 0;
        font-weight: 600;
        font-size: 0.9rem;
    }

    .feature-card-compact p {
        color: var(--body-text-color);
        opacity: 0.75;
        font-size: 0.75rem;
        margin: 0;
        line-height: 1.4;
    }

    .feature-icon-compact {
        font-size: 1.5rem;
        margin-bottom: 0.25rem;
    }

    /* Task selection cards - Light mode (default) */
    .task-card {
        min-height: 160px;
        padding: 1.5rem 1rem;
        text-align: center;
        white-space: pre-line;
        transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
        border-radius: 12px;
        background: white;
        border: 1px solid #e5e7eb;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        color: #1f2937;
    }

    /* Dark mode task cards */
    .dark .task-card {
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(255, 255, 255, 0.2);
        box-shadow: none;
        color: inherit;
    }

    .task-card:hover:not(:disabled) {
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        border-color: #288cfa;
    }

    .dark .task-card:hover:not(:disabled) {
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
        border-color: rgba(4, 140, 252, 0.5);
    }

    .task-card:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .task-card-icon {
        font-size: 2.5rem;
        margin-bottom: 0.75rem;
    }

    .task-card-title {
        font-size: 1.1rem;
        font-weight: 600;
        margin-bottom: 0.5rem;
        color: #1f2937;
    }

    .dark .task-card-title {
        color: inherit;
    }

    .task-card-description {
        font-size: 0.85rem;
        color: #4b5563;
        line-height: 1.4;
    }

    .dark .task-card-description {
        color: inherit;
        opacity: 0.8;
    }

    .coming-soon-badge {
        font-size: 0.7rem;
        background: rgba(255, 255, 255, 0.1);
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
        margin-top: 0.5rem;
        display: inline-block;
    }

    /* Task page container */
    .task-selection-container {
        max-width: 900px;
        margin: 0 auto;
        padding: 2rem;
    }

    /* Preview card - scrollable with wider layout */
    .preview-card {
        background: rgba(255, 255, 255, 0.05);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 12px;
        padding: 0;
        flex: 1 1 auto !important;
        max-height: 800px !important;
        min-height: 0;
        overflow-y: auto;
        overflow-x: hidden;
        display: flex !important;
        flex-direction: column !important;
        box-sizing: border-box !important;
    }

    /* Custom scrollbar for preview card */
    .preview-card::-webkit-scrollbar {
        width: 8px;
    }

    .preview-card::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 4px;
    }

    .preview-card::-webkit-scrollbar-thumb {
        background: rgba(4, 140, 252, 0.3);
        border-radius: 4px;
    }

    .preview-card::-webkit-scrollbar-thumb:hover {
        background: rgba(4, 140, 252, 0.5);
    }

    /* Firefox */
    .preview-card {
        scrollbar-width: thin;
        scrollbar-color: rgba(4, 140, 252, 0.3) rgba(255, 255, 255, 0.05);
    }

    /* Scrollable markdown for bull/bear cases */
    .scrollable-markdown {
        max-height: 400px;
        overflow-y: auto;
        padding-right: 10px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 8px;
        padding: 1rem;
        background: rgba(255, 255, 255, 0.02);
    }

    .scrollable-markdown::-webkit-scrollbar {
        width: 6px;
    }

    .scrollable-markdown::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 3px;
    }

    .scrollable-markdown::-webkit-scrollbar-thumb {
        background: rgba(4, 140, 252, 0.3);
        border-radius: 3px;
    }

    /* Input card - unified with examples */
    .input-card {
        background: rgba(255, 255, 255, 0.05);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 0;
        flex: 1 1 auto !important;
        display: flex !important;
        flex-direction: column !important;
        overflow-y: visible !important;
        overflow-x: visible !important;
        max-height: none !important;
        min-height: 0;
        box-sizing: border-box !important;
        gap: 0 !important;
    }

    /* Custom scrollbar for input card */
    .input-card::-webkit-scrollbar {
        width: 8px;
    }

    .input-card::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 4px;
    }

    .input-card::-webkit-scrollbar-thumb {
        background: rgba(4, 140, 252, 0.3);
        border-radius: 4px;
    }

    .input-card::-webkit-scrollbar-thumb:hover {
        background: rgba(4, 140, 252, 0.5);
    }

    /* Firefox scrollbar */
    .input-card {
        scrollbar-width: thin;
        scrollbar-color: rgba(4, 140, 252, 0.3) rgba(255, 255, 255, 0.05);
    }

    .examples-header {
        margin-top: 0.25rem;
        margin-bottom: 0.25rem;
        padding-top: 0.5rem;
        border-top: 1px solid rgba(255, 255, 255, 0.1);
        color: #048CFC;
        font-weight: 600;
        font-size: 1rem;
    }

    /* Portfolio row - natural heights without stretching */
    .portfolio-row {
        display: flex !important;
        flex-direction: row !important;
        align-items: stretch !important;
        height: 100% !important;
        min-height: 600px !important;
    }

    .portfolio-row > .gr-column {
        display: flex !important;
        flex-direction: column !important;
        flex: 1 1 0% !important;
        height: 100% !important;
        min-height: 100% !important;
        max-height: 100% !important;
        gap: 0 !important;
        overflow: visible !important;
    }

    .portfolio-row > * {
        flex: 1 !important;
    }

    .portfolio-row .block {
        display: flex !important;
        flex-direction: column !important;
        flex: 1 !important;
    }

    /* Button fixed sizing - prevent vertical expansion */
    .portfolio-row button {
        flex: 0 0 45px !important;
        width: 100% !important;
        height: 45px !important;
        min-height: 45px !important;
        max-height: 45px !important;
    }

    /* Flex items min-height to prevent overflow */
    .input-card > *:not([class*="dropdown"]),
    .preview-card > *:not([class*="dropdown"]) {
        min-height: 0;
    }

    /* Dropdown styling and z-index */
    .gr-dropdown {
        z-index: 999 !important;
        position: relative !important;
    }

    .gr-dropdown-container {
        z-index: 999 !important;
        overflow: visible !important;
        position: relative !important;
    }

    /* Dropdown menu positioning - appear below button */
    .gr-dropdown ul[role="listbox"],
    .gr-dropdown .options,
    .gr-dropdown-menu {
        z-index: 9999 !important;
        overflow: visible !important;
        position: absolute !important;
        top: 100% !important;
        left: 0 !important;
        width: 100% !important;
        max-height: 300px !important;
        overflow-y: auto !important;
    }

    /* Loading page styling */
    .loading-header {
        animation: fadeIn 0.5s ease-in;
    }

    .loading-message {
        text-align: center;
        font-size: 1.1rem;
        color: #048CFC;
        padding: 2rem;
        min-height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* Example buttons styling */
    .gr-examples button {
        background: linear-gradient(135deg, rgba(4, 140, 252, 0.1), rgba(17, 199, 170, 0.1));
        border: 1px solid rgba(4, 140, 252, 0.3);
        border-radius: 8px;
        padding: 0.75rem 1rem;
        font-size: 0.9rem;
        transition: all 0.2s ease;
    }

    .gr-examples button:hover {
        background: linear-gradient(135deg, rgba(4, 140, 252, 0.2), rgba(17, 199, 170, 0.2));
        border-color: rgba(4, 140, 252, 0.6);
        transform: translateY(-2px);
    }

    /* Mobile responsive - feature cards stack on small screens */
    @media (max-width: 1024px) {
        .feature-card-compact {
            padding: 1.25rem;
            min-height: auto;
        }
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        #hero-section {
            padding: 2rem 1rem;
        }

        #hero-section h2 {
            font-size: 1.75rem;
        }

        #hero-section p {
            font-size: 1rem;
        }

        #hero-section .value-props {
            gap: 1rem;
        }

        .feature-card-compact {
            padding: 1.25rem;
        }

        .preview-card {
            max-height: 400px;
        }
    }

    /* Accessibility - WCAG AA Colour Contrast Improvements */
    .demo-subtitle {
        color: rgba(255, 255, 255, 0.95) !important;  /* Increased from 0.7 for better contrast */
        font-size: 14px;
    }

    .disclaimer-text {
        color: rgba(255, 255, 255, 0.95) !important;  /* Increased contrast */
        font-size: 13px;
    }

    /* Update all placeholder text for better visibility */
    input::placeholder, textarea::placeholder {
        color: rgba(255, 255, 255, 0.7) !important;  /* Increased from 0.5 */
    }

    /* Add focus indicators for keyboard navigation */
    input:focus, textarea:focus, button:focus, select:focus {
        outline: 3px solid #4A9EFF !important;
        outline-offset: 2px;
    }

    /* Validation message colours with better contrast */
    #signup-email-validation, #password-match-validation {
        font-size: 0.85rem;
        margin-top: 0.25rem;
        font-weight: 500;
    }
    """

    with gr.Blocks(
        title="Portfolio Intelligence Platform",
        theme=theme,
        css=custom_css,
        fill_width=True,
        fill_height=True
    ) as demo:
        # Session state for authentication
        session_state = gr.State({})

        # Pagination state for history views
        history_current_page = gr.State(1)
        history_current_page_results = gr.State(1)

        # Hero Section with auth status
        with gr.Row():
            gr.HTML(
                """
                <div id="hero-section">
                    <h2>Portfolio Intelligence Platform</h2>
                    <p>AI-powered portfolio analysis with transparent multi-agent MCP orchestration</p>
                    <div class="value-props">
                        <div class="value-prop">
                            <span>9 MCP Servers</span>
                        </div>
                        <div class="value-prop">
                            <span>Quantitative Models</span>
                        </div>
                        <div class="value-prop">
                            <span>Claude Sonnet 4.5</span>
                        </div>
                    </div>
                </div>
                """,
                elem_classes="hero-container"
            )

        # User info and logout button
        with gr.Row():
            with gr.Column(scale=4):
                user_info = gr.Markdown("Not logged in", elem_id="user-info")
            with gr.Column(scale=1):
                logout_btn = gr.Button("Sign Out", variant="secondary", size="sm", visible=False)

        # Navigation sidebar using Gradio's native component
        with gr.Sidebar(position="left", open=False, visible=False, elem_id="main-sidebar") as sidebar:
            gr.Markdown("## Navigation", elem_classes="sidebar-header")

            # Navigation options
            nav_new_analysis = gr.Button("🏠 Home", variant="secondary", size="lg", elem_classes="nav-btn")
            nav_view_history = gr.Button("πŸ“œ View History", variant="secondary", size="lg", elem_classes="nav-btn")

            gr.Markdown("---")

            # User section (when logged in)
            with gr.Group(visible=False) as sidebar_user_section:
                gr.Markdown("### Account")
                sidebar_user_email = gr.Markdown("")
                nav_profile_btn = gr.Button("πŸ‘€ Profile", variant="secondary", size="sm")
                nav_signout_btn = gr.Button("πŸšͺ Sign Out", variant="secondary", size="sm")

        # Authentication container
        with gr.Group(visible=True, elem_id="auth-container") as login_container:
            gr.Markdown("## πŸ” Sign In to Continue")
            gr.Markdown("Please sign in or create an account to analyse your portfolio")

            with gr.Tabs():
                # Login Tab
                with gr.Tab("Sign In"):
                    login_email = gr.Textbox(
                        label="Email Address",
                        placeholder="your.email@example.com",
                        type="email",
                        elem_id="login-email"
                    )
                    login_password = gr.Textbox(
                        label="Password",
                        placeholder="Enter your password",
                        type="password",
                        elem_id="login-password"
                    )
                    forgot_password_btn = gr.Button(
                        "Forgot password?",
                        variant="secondary",
                        size="sm",
                        elem_classes="forgot-password-link"
                    )
                    login_btn = gr.Button("Sign In", variant="primary", size="lg")
                    login_message = gr.Markdown("")

                # Signup Tab
                with gr.Tab("Create Account"):
                    signup_username = gr.Textbox(
                        label="Username (optional)",
                        placeholder="Choose a username",
                        elem_id="signup-username"
                    )
                    signup_email = gr.Textbox(
                        label="Email Address",
                        placeholder="your.email@example.com",
                        type="email",
                        elem_id="signup-email"
                    )
                    signup_email_validation = gr.Markdown("", elem_id="signup-email-validation")

                    signup_password = gr.Textbox(
                        label="Password",
                        placeholder="At least 15 characters (NIST 2024 requirement)",
                        type="password",
                        elem_id="signup-password"
                    )
                    signup_password_strength = gr.Markdown("", elem_id="password-strength")

                    signup_confirm = gr.Textbox(
                        label="Confirm Password",
                        placeholder="Re-enter your password",
                        type="password",
                        elem_id="signup-confirm-password"
                    )
                    signup_password_match = gr.Markdown("", elem_id="password-match-validation")

                    gr.Markdown(
                        "*By signing up, you agree this is for educational purposes only and not financial advice.*",
                        elem_classes="disclaimer-text"
                    )
                    signup_btn = gr.Button("Create Account", variant="primary", size="lg")
                    signup_message = gr.Markdown("")

            # Demo mode option
            gr.Markdown("---")
            gr.Markdown("## 🎯 Or Try Without Signing Up")
            demo_btn = gr.Button(
                "Try Demo",
                variant="secondary",
                size="lg"
            )
            gr.Markdown("*1 free analysis per day β€’ No account required*", elem_classes="demo-subtitle")
            demo_message = gr.Markdown("")

        # Modal 1: Request password reset (only email input)
        with gr.Group(visible=False, elem_id="password-reset-modal") as password_reset_modal:
            gr.Markdown("## Request Password Reset")
            gr.Markdown("Enter your email address and we'll send you a password reset link.")

            reset_email = gr.Textbox(
                label="Email Address",
                placeholder="your.email@example.com",
                type="email",
                elem_id="reset-email"
            )
            with gr.Row():
                reset_submit_btn = gr.Button("Send Reset Link", variant="primary", size="lg")
                reset_cancel_btn = gr.Button("Cancel", variant="secondary", size="lg")
            reset_message = gr.Markdown("")

        # Modal 2: Set new password (only appears after clicking email link)
        with gr.Group(visible=False, elem_id="password-update-modal") as password_update_modal:
            gr.Markdown("## Set New Password")
            gr.Markdown("Enter your new password below.")

            # Hidden fields to store recovery token_hash and email (populated by JavaScript)
            recovery_token_hash = gr.Textbox(visible=False, elem_id="recovery-token-hash")
            recovery_email = gr.Textbox(
                label="Email Address",
                placeholder="your.email@example.com",
                type="email",
                info="Enter the email address you used to request the password reset",
                elem_id="recovery-email"
            )

            new_password = gr.Textbox(
                label="New Password",
                placeholder="At least 15 characters (NIST 2024 requirement)",
                type="password",
                elem_id="new-password"
            )
            confirm_new_password = gr.Textbox(
                label="Confirm New Password",
                placeholder="Re-enter your new password",
                type="password",
                elem_id="confirm-new-password"
            )
            with gr.Row():
                update_password_btn = gr.Button("Update Password", variant="primary", size="lg")
                update_cancel_btn = gr.Button("Cancel", variant="secondary", size="lg")
            update_password_message = gr.Markdown("")

        # Task Selection Page (shown after authentication)
        with gr.Group(visible=False, elem_classes="task-selection-container") as task_page:
            gr.Markdown("## What would you like to do?", elem_classes="section-title")

            with gr.Row(equal_height=True):
                # Analyse Portfolio - enabled
                with gr.Column(scale=1, min_width=200):
                    task_analyse_btn = gr.Button(
                        value="πŸ“Š\n\nAnalyse Portfolio\n\nGet comprehensive analysis of your current holdings",
                        elem_classes=["task-card"],
                        variant="primary",
                        size="lg"
                    )

                # Build Portfolio - enabled
                with gr.Column(scale=1, min_width=200):
                    task_build_btn = gr.Button(
                        value="πŸ—οΈ\n\nBuild Portfolio\n\nAI helps construct a portfolio based on your goals",
                        elem_classes=["task-card"],
                        variant="primary",
                        interactive=True,
                        size="lg"
                    )

                # Compare Strategies - enabled
                with gr.Column(scale=1, min_width=200):
                    task_compare_btn = gr.Button(
                        value="βš”οΈ\n\nCompare Strategies\n\nSee bull vs bear perspectives on your investments",
                        elem_classes=["task-card"],
                        variant="primary",
                        interactive=True,
                        size="lg"
                    )

                # Test Changes
                with gr.Column(scale=1, min_width=200):
                    task_test_btn = gr.Button(
                        value="πŸ”¬\n\nTest Changes\n\nPreview impact before making portfolio changes",
                        elem_classes=["task-card"],
                        variant="secondary",
                        size="lg"
                    )

        # Build Portfolio Page (shown when Build Portfolio task selected)
        with gr.Group(visible=False, elem_classes="build-portfolio-container") as build_page:
            gr.Markdown("## Build Your Portfolio", elem_classes="section-title")
            gr.Markdown("Tell us about your investment goals and we'll build a portfolio for you.")

            with gr.Row(equal_height=True):
                # Left column: Goal settings
                with gr.Column(scale=2):
                    with gr.Group(elem_classes="input-card"):
                        build_goals = gr.CheckboxGroup(
                            choices=["Growth", "Income", "Capital Preservation", "Speculation"],
                            label="Investment Goals",
                            info="Select one or more investment objectives"
                        )

                        build_risk_tolerance = gr.Slider(
                            minimum=1,
                            maximum=10,
                            value=5,
                            step=1,
                            label="Risk Tolerance",
                            info="1 = Very Conservative, 10 = Very Aggressive"
                        )

                        build_constraints = gr.Textbox(
                            label="Constraints (Optional)",
                            placeholder="e.g., 'No crypto, ESG focused, minimum 10 stocks, max 5% per position'",
                            lines=3,
                            info="Any specific requirements or restrictions"
                        )

                        with gr.Row():
                            build_submit_btn = gr.Button(
                                "Build My Portfolio",
                                variant="primary",
                                size="lg"
                            )
                            build_back_btn = gr.Button(
                                "Back",
                                variant="secondary",
                                size="lg"
                            )

                # Right column: Results
                with gr.Column(scale=3):
                    # Agent activity stream
                    build_agent_chat = gr.Chatbot(
                        label="πŸ€– Agent Activity",
                        type="messages",
                        height=400,
                        visible=False,
                        show_copy_button=True,
                        elem_classes="agent-chat"
                    )

                    with gr.Group(elem_classes="preview-card", visible=False) as build_results_container:
                        build_status = gr.Markdown("", elem_classes="build-status")

                        # Audio narration button and player
                        with gr.Row():
                            build_audio_btn = gr.Button(
                                "πŸ”Š Listen to Portfolio",
                                variant="secondary",
                                size="sm",
                                visible=False
                            )
                        with gr.Row():
                            build_audio_player = gr.Audio(
                                label="Portfolio Summary Audio",
                                interactive=False,
                                visible=False,
                                show_download_button=True
                            )

                        with gr.Row():
                            build_regenerate_btn = gr.Button("Regenerate", variant="secondary", size="sm")

        # Compare Strategies Page (shown when Compare Strategies task selected)
        with gr.Group(visible=False, elem_classes="compare-strategies-container") as compare_page:
            gr.Markdown("## Compare Strategies", elem_classes="section-title")
            gr.Markdown("Get bull and bear perspectives on your portfolio through multi-agent debate.")

            with gr.Row(equal_height=True):
                # Left column: Portfolio input
                with gr.Column(scale=2):
                    with gr.Group(elem_classes="input-card"):
                        compare_portfolio_input = gr.Textbox(
                            placeholder="AAPL 50\nTSLA 25 shares\nNVDA $5000",
                            label="Portfolio Holdings",
                            lines=6,
                            info="Enter your holdings to analyse"
                        )

                        with gr.Row():
                            compare_submit_btn = gr.Button(
                                "Run Analysis",
                                variant="primary",
                                size="lg"
                            )
                            compare_back_btn = gr.Button(
                                "Back",
                                variant="secondary",
                                size="lg"
                            )

                # Right column: Results
                with gr.Column(scale=3):
                    # Debate activity stream
                    compare_debate_chat = gr.Chatbot(
                        label="🎭 Advisory Council Debate",
                        type="messages",
                        height=500,
                        visible=False,
                        show_copy_button=True,
                        elem_classes="debate-chat"
                    )

                    with gr.Group(elem_classes="preview-card", visible=False) as compare_results_container:
                        compare_status = gr.Markdown("", elem_classes="compare-status")

                        # Bull vs Bear side-by-side
                        with gr.Row():
                            with gr.Column():
                                gr.Markdown("### Bull Case")
                                compare_bull_case = gr.Markdown("", elem_classes="scrollable-markdown")
                                compare_bull_confidence = gr.Number(label="Confidence %", interactive=False)

                            with gr.Column():
                                gr.Markdown("### Bear Case")
                                compare_bear_case = gr.Markdown("", elem_classes="scrollable-markdown")
                                compare_bear_confidence = gr.Number(label="Confidence %", interactive=False)

                        # Consensus
                        gr.Markdown("### Consensus Recommendation")
                        compare_consensus = gr.Markdown("")
                        compare_stance = gr.Textbox(label="Stance", interactive=False)

                        # Audio debate button and player
                        with gr.Row():
                            compare_audio_btn = gr.Button(
                                "🎭 Listen to Debate",
                                variant="secondary",
                                size="sm",
                                visible=False
                            )
                        with gr.Row():
                            compare_audio_player = gr.Audio(
                                label="Advisory Council Debate Audio",
                                interactive=False,
                                visible=False,
                                show_download_button=True
                            )

                        # Debate transcript
                        with gr.Accordion("View Full Debate", open=False):
                            compare_debate_transcript = gr.JSON(label="Debate Rounds")

        # Test Changes Page (shown when Test Changes task selected)
        with gr.Group(visible=False, elem_classes="test-changes-container") as test_page:
            gr.Markdown("## Test Portfolio Changes", elem_classes="section-title")
            gr.Markdown("Preview the impact of changes before making them.")

            with gr.Row(equal_height=True):
                # Left column: Portfolio and changes input
                with gr.Column(scale=2):
                    with gr.Group(elem_classes="input-card"):
                        test_portfolio_input = gr.Textbox(
                            placeholder="AAPL 30%\nTSLA 25%\nNVDA 25%\nBND 20%",
                            label="Current Portfolio (ticker weight%)",
                            lines=6,
                            info="Enter your current portfolio allocations"
                        )

                        test_changes_input = gr.Textbox(
                            placeholder="sell TSLA 10\nbuy VTI 10",
                            label="Proposed Changes",
                            lines=4,
                            info="Format: action ticker amount (e.g., 'sell TSLA 10' or 'buy VTI 15')"
                        )

                        test_portfolio_value = gr.Number(
                            label="Portfolio Value ($)",
                            value=100000,
                            info="Total portfolio value for calculations"
                        )

                        with gr.Row():
                            test_submit_btn = gr.Button(
                                "Run Simulation",
                                variant="primary",
                                size="lg"
                            )
                            test_back_btn = gr.Button(
                                "Back",
                                variant="secondary",
                                size="lg"
                            )

                # Right column: Results
                with gr.Column(scale=3):
                    with gr.Group(elem_classes="preview-card", visible=False) as test_results_container:
                        test_status = gr.Markdown("", elem_classes="test-status")

                        # Side-by-side metrics comparison
                        with gr.Row():
                            with gr.Column():
                                gr.Markdown("### Current Portfolio")
                                test_current_metrics = gr.Dataframe(
                                    headers=["Metric", "Value"],
                                    label="Current Metrics",
                                    interactive=False
                                )

                            with gr.Column():
                                gr.Markdown("### After Changes")
                                test_simulated_metrics = gr.Dataframe(
                                    headers=["Metric", "Value"],
                                    label="Simulated Metrics",
                                    interactive=False
                                )

                        # Impact summary
                        gr.Markdown("### Impact Analysis")
                        test_impact_summary = gr.Dataframe(
                            headers=["Metric", "Current", "Simulated", "Change", "% Change"],
                            label="Impact Summary",
                            interactive=False
                        )

                        # Stress test comparison
                        with gr.Accordion("Stress Test Comparison", open=False):
                            test_stress_comparison = gr.Dataframe(
                                headers=["Scenario", "Shock %", "Current Loss", "Simulated Loss", "Improvement"],
                                label="Stress Tests",
                                interactive=False
                            )

                        # Recommendations and assessment
                        test_assessment = gr.Markdown("", elem_classes="test-assessment")
                        test_recommendations = gr.Markdown("", label="Recommendations")

        # Input Page with side-by-side layout (hidden until authenticated)
        with gr.Group(visible=False) as input_page:
            # Side-by-side input and preview (2:3 ratio for wider preview)
            with gr.Row(equal_height=True, elem_classes="portfolio-row"):
                # Left column: Input + Examples (unified card)
                with gr.Column(scale=2):
                    with gr.Group(elem_classes="input-card"):
                        portfolio_input = gr.Textbox(
                            placeholder="AAPL 50\nTSLA 25 shares\nNVDA $5000\nGLD 10 shares",
                            label="Portfolio Holdings",
                            lines=8,
                            info="Enter your holdings below (see examples for format)"
                        )

                        # Load past portfolio
                        load_past_portfolio_dropdown = gr.Dropdown(
                            choices=[],
                            label="Load Past Portfolio (Last 3)",
                            interactive=True,
                            elem_id="load-past-portfolio-dropdown",
                            info="Your 3 most recent portfolios"
                        )

                        # Persona Selection
                        persona_choices = [
                            ("Standard Analysis", "standard"),
                            ("Warren Buffett - Value Investing", "warren_buffett"),
                            ("Cathie Wood - Innovation & Growth", "cathie_wood"),
                            ("Ray Dalio - Macro & Diversification", "ray_dalio"),
                        ]
                        persona_dropdown = gr.Dropdown(
                            choices=persona_choices,
                            value="standard",
                            label="Analysis Persona",
                            info="Choose an investor perspective for the analysis"
                        )

                        # Roast Mode Toggle
                        roast_mode_toggle = gr.Checkbox(
                            label="Roast Mode",
                            value=False,
                            info="Enable brutal honesty mode for portfolio critique (only works with Standard Analysis)"
                        )

                        # Action buttons
                        with gr.Row():
                            analyse_btn = gr.Button(
                                "Analyse Portfolio",
                                variant="primary",
                                size="lg",
                                min_width=290
                            )
                            input_back_btn = gr.Button(
                                "Back",
                                variant="secondary",
                                size="lg",
                                min_width=290
                            )

                        # Examples integrated as simple buttons
                        gr.Markdown("### Example Portfolios", elem_classes="examples-header")
                        with gr.Row():
                            tech_btn = gr.Button("Tech Growth", size="sm", scale=1)
                            conservative_btn = gr.Button("Conservative Income", size="sm", scale=1)
                            balanced_btn = gr.Button("Balanced 60/40", size="sm", scale=1)
                            global_btn = gr.Button("Global Diversified", size="sm", scale=1)
                            risk_btn = gr.Button("Single Stock Risk", size="sm", scale=1)

                # Right column: Live preview (wider at scale=3)
                with gr.Column(scale=3):
                    preview_output = gr.HTML(
                        value=update_live_preview(""),
                        elem_classes="preview-card"
                    )
                    refresh_prices_btn = gr.Button(
                        "πŸ”„ Get Current Prices",
                        variant="primary",
                        size="sm",
                        scale=1
                    )

            # JavaScript to detect password reset token_hash in URL and populate hidden fields
            # This runs on page load and checks for recovery token in query parameters
            demo.load(
                fn=None,  # No Python processing needed - JavaScript directly sets the value
                inputs=[],
                outputs=[recovery_token_hash],
                js="""
                function() {
                    // Check for recovery token_hash in URL query parameters (PKCE flow)
                    const params = new URLSearchParams(window.location.search);
                    const tokenHash = params.get('token_hash') || '';
                    const typeParam = params.get('type') || '';

                    if (tokenHash && typeParam === 'recovery') {
                        console.log('Password reset token detected');

                        // Clean up URL (remove query parameters)
                        window.history.replaceState({}, document.title, window.location.pathname);

                        return tokenHash;
                    }

                    return '';
                }
                """
            )

            # Add click handlers for example buttons
            tech_btn.click(
                fn=lambda: "AAPL 50 shares\nTSLA 25 shares\nNVDA 30 shares\nMETA 20 shares",
                outputs=portfolio_input,
                show_api=False
            )
            conservative_btn.click(
                fn=lambda: "VOO 100 shares\nVTI 75 shares\nSCHD 50 shares\nTLT 40 shares\nVXUS 60 shares",
                outputs=portfolio_input,
                show_api=False
            )
            balanced_btn.click(
                fn=lambda: "VTI $25000\nVXUS $15000\nBND $15000\nGLD $5000",
                outputs=portfolio_input,
                show_api=False
            )
            global_btn.click(
                fn=lambda: "VTI $15000\nVXUS $10000\nVWO $5000\nBND $10000\nGLD $3000\nVNQ $2000",
                outputs=portfolio_input,
                show_api=False
            )
            risk_btn.click(
                fn=lambda: "TSLA 100 shares",
                outputs=portfolio_input,
                show_api=False
            )

            # Feature highlights grid (1x4 compact layout)
            gr.Markdown("### Key Features", elem_classes="section-title")
            with gr.Row():
                with gr.Column(scale=1, min_width=200):
                    gr.HTML(
                        """
                        <div class="feature-card-compact">
                            <div class="feature-icon-compact">🧠</div>
                            <h4>Smart Analysis</h4>
                            <p>HRP, Black-Litterman, VaR/CVaR</p>
                        </div>
                        """
                    )
                with gr.Column(scale=1, min_width=200):
                    gr.HTML(
                        """
                        <div class="feature-card-compact">
                            <div class="feature-icon-compact">⚑</div>
                            <h4>Fast Results</h4>
                            <p>1-2 minutes</p>
                        </div>
                        """
                    )
                with gr.Column(scale=1, min_width=200):
                    gr.HTML(
                        """
                        <div class="feature-card-compact">
                            <div class="feature-icon-compact">πŸ”’</div>
                            <h4>Secure</h4>
                            <p>No data stored</p>
                        </div>
                        """
                    )
                with gr.Column(scale=1, min_width=200):
                    gr.HTML(
                        """
                        <div class="feature-card-compact">
                            <div class="feature-icon-compact">✨</div>
                            <h4>AI Powered</h4>
                            <p>Claude Sonnet 4.5</p>
                        </div>
                        """
                    )

        # Loading Page
        with gr.Group(visible=False) as loading_page:
            with gr.Row():
                with gr.Column():
                    gr.HTML(
                        """
                        <div style='text-align: center; padding: 4rem 2rem;'>
                            <div style='font-size: 3rem; margin-bottom: 1rem;'>⚑</div>
                            <h2 style='color: #048CFC; margin-bottom: 1rem;'>Analysing Your Portfolio</h2>
                        </div>
                        """,
                        elem_classes="loading-header"
                    )
                    loading_message = gr.Markdown(
                        value="Initialising analysis...",
                        elem_classes="loading-message",
                    )
                    gr.HTML(
                        """
                        <div style='text-align: center; padding: 2rem; color: #999; font-size: 14px;'>
                            <p>This may take 1-2 minutes as we run deep learning models on your portfolio</p>
                        </div>
                        """
                    )

        # Results Page (tabbed interface)
        with gr.Group(visible=False) as results_page:
            # Header with actions (always visible)
            with gr.Row(elem_id="results-header"):
                with gr.Column(scale=3):
                    gr.Markdown("# Portfolio Analysis Results", elem_classes="page-title")
                with gr.Column(scale=1):
                    with gr.Row():
                        export_pdf_btn = gr.DownloadButton("πŸ“„ Export PDF", size="sm")
                        export_csv_btn = gr.DownloadButton("πŸ“Š Export CSV", size="sm")

            # Main tabbed interface
            with gr.Tabs() as results_tabs:
                # Tab 1: Analysis Results
                with gr.Tab("πŸ“Š Analysis Results"):
                    with gr.Column():
                        analysis_output = gr.Markdown("")

                        # Audio narration button and player
                        with gr.Row():
                            analysis_audio_btn = gr.Button(
                                "πŸ”Š Listen to Analysis",
                                variant="secondary",
                                size="sm",
                                visible=False
                            )
                        with gr.Row():
                            analysis_audio_player = gr.Audio(
                                label="Audio Summary",
                                interactive=False,
                                visible=False,
                                show_download_button=True
                            )

                        # Performance Metrics Accordion (progressive disclosure)
                        with gr.Accordion("Performance Metrics & Reasoning", open=False):
                            performance_metrics_output = gr.Markdown("")

                # Tab 2: Dashboard
                with gr.Tab("πŸ“ˆ Dashboard"):
                    # Top row - Portfolio allocation + Risk metrics
                    with gr.Row(equal_height=True):
                        with gr.Column(scale=1, min_width=400):
                            allocation_plot = gr.Plot(label="Portfolio Allocation", container=True)
                        with gr.Column(scale=1, min_width=400):
                            risk_plot = gr.Plot(label="Risk Metrics Dashboard", container=True)

                    # Middle row - Performance chart
                    with gr.Row():
                        performance_plot = gr.Plot(label="Historical Performance", container=True)

                    # Bottom row - Correlation + Optimisation
                    with gr.Row(equal_height=True):
                        with gr.Column(scale=1, min_width=400):
                            correlation_plot = gr.Plot(label="Asset Correlation Matrix", container=True)
                        with gr.Column(scale=1, min_width=400):
                            optimization_plot = gr.Plot(label="Optimisation Methods Comparison", container=True)

                # Tab 3: Tax Analysis
                with gr.Tab("πŸ’° Tax Analysis"):
                    gr.Markdown("Analyse tax implications and identify tax-loss harvesting opportunities.")

                    # Top row: Input controls
                    with gr.Row():
                        tax_filing_status = gr.Dropdown(
                            choices=[
                                ("Single", "single"),
                                ("Married Filing Jointly", "married_joint"),
                                ("Married Filing Separately", "married_separate"),
                                ("Head of Household", "head_of_household"),
                            ],
                            value="single",
                            label="Filing Status",
                            info="Your tax filing status"
                        )
                        tax_annual_income = gr.Slider(
                            minimum=0,
                            maximum=1000000,
                            value=75000,
                            step=5000,
                            label="Annual Income ($)",
                            info="Total taxable income"
                        )
                        tax_cost_basis_method = gr.Dropdown(
                            choices=[
                                ("First In, First Out (FIFO)", "fifo"),
                                ("Last In, First Out (LIFO)", "lifo"),
                                ("Highest In, First Out (HIFO)", "hifo"),
                                ("Average Cost", "average"),
                            ],
                            value="fifo",
                            label="Cost Basis Method",
                            info="Method for calculating gains/losses"
                        )

                    # Cost basis input section
                    gr.Markdown("### Purchase Information")
                    gr.Markdown(
                        "Enter your purchase details for accurate tax calculations. "
                        "Click 'Load Holdings' to pre-populate with current holdings, then fill in purchase prices and dates."
                    )
                    with gr.Row():
                        tax_load_holdings_btn = gr.Button("Load Holdings", size="sm")
                        gr.Markdown(
                            "*Accepted date formats: 9/3/17, Sep 3, 2017, 2017-09-03, etc.*",
                            elem_classes="text-muted"
                        )

                    tax_cost_basis_input = gr.Dataframe(
                        headers=["Ticker", "Shares", "Purchase Price", "Purchase Date"],
                        datatype=["str", "number", "number", "str"],
                        col_count=(4, "fixed"),
                        row_count=(5, "dynamic"),
                        interactive=True,
                        label="Cost Basis Information",
                        value=[],
                    )

                    tax_calculate_btn = gr.Button("Calculate Tax Impact", variant="primary")

                    # Bottom row: Analysis output
                    tax_analysis_output = gr.Markdown("")

                # Tab 4: Stress Testing
                with gr.Tab("🎲 Stress Testing"):
                    gr.Markdown("Test your portfolio's resilience against historical crises and market scenarios.")

                    with gr.Row():
                        with gr.Column(scale=1):
                            scenario_choices = [
                                ("Monte Carlo Simulation (10,000 paths)", "monte_carlo"),
                                ("All Scenarios Comparison", "all_scenarios"),
                                ("2008 Financial Crisis", "2008_financial_crisis"),
                                ("COVID-19 Pandemic (2020)", "covid_2020"),
                                ("Dot-com Bubble (2000-2002)", "dotcom_bubble"),
                                ("European Debt Crisis (2011)", "european_debt_2011"),
                                ("China Devaluation (2015)", "china_2015"),
                                ("Inflation Shock (2022)", "inflation_2022"),
                                ("Severe Recession (Hypothetical)", "severe_recession"),
                                ("Stagflation (Hypothetical)", "stagflation"),
                                ("Flash Crash (Hypothetical)", "flash_crash"),
                            ]
                            stress_scenario_dropdown = gr.Dropdown(
                                choices=scenario_choices,
                                value="monte_carlo",
                                label="Select Stress Scenario",
                                info="Choose a historical crisis or simulation method"
                            )

                            with gr.Row():
                                stress_n_sims = gr.Slider(
                                    minimum=1000,
                                    maximum=50000,
                                    value=10000,
                                    step=1000,
                                    label="Monte Carlo Simulations",
                                    info="More simulations = more accuracy (slower)"
                                )
                                stress_horizon = gr.Slider(
                                    minimum=30,
                                    maximum=756,
                                    value=252,
                                    step=30,
                                    label="Time Horizon (days)",
                                    info="1 year = 252 trading days"
                                )

                            stress_test_btn = gr.Button("Run Stress Test", variant="primary", size="lg")

                    # Stress test results
                    with gr.Column():
                        stress_summary = gr.Markdown("", visible=True)

                        with gr.Tabs():
                            with gr.Tab("Dashboard"):
                                stress_dashboard_plot = gr.Plot(label="Stress Test Dashboard")

                            with gr.Tab("Monte Carlo Paths"):
                                stress_mc_plot = gr.Plot(label="Monte Carlo Simulation Paths")

                            with gr.Tab("Scenario Comparison"):
                                stress_scenario_plot = gr.Plot(label="All Scenarios Comparison")

                            with gr.Tab("Drawdown Analysis"):
                                stress_drawdown_plot = gr.Plot(label="Maximum Drawdown Distribution")

                # Tab 5: History (embedded)
                with gr.Tab("πŸ“œ History"):
                    gr.Markdown("View your previous portfolio analyses")

                    # Search and filters
                    with gr.Row():
                        history_search_results = gr.Textbox(
                            placeholder="Search by ticker, date...",
                            label="Search",
                            scale=3,
                            elem_id="history-search-results"
                        )
                        history_date_filter_results = gr.Dropdown(
                            choices=[
                                ("All Time", "all"),
                                ("Last 7 Days", "7d"),
                                ("Last 30 Days", "30d"),
                                ("Last 90 Days", "90d"),
                            ],
                            value="all",
                            label="Date Range",
                            scale=1
                        )
                        history_refresh_btn_results = gr.Button("πŸ”„ Refresh", size="sm", scale=1)

                    history_table_results = gr.Dataframe(
                        headers=["ID", "Date", "Holdings", "Risk Tolerance", "AI Synthesis Preview"],
                        datatype=["str", "str", "str", "str", "str"],
                        interactive=False,
                        wrap=True,
                        elem_id="history-table-results",
                        column_widths=["5%", "15%", "25%", "15%", "40%"]
                    )

                    # Pagination controls
                    with gr.Row():
                        history_prev_btn_results = gr.Button("← Previous", size="sm", scale=1)
                        history_page_info_results = gr.Markdown("Page 1 of 1", elem_id="history-page-info-results")
                        history_next_btn_results = gr.Button("Next β†’", size="sm", scale=1)

                    with gr.Accordion("Selected Analysis Details", open=False):
                        history_details_output_results = gr.Markdown("")

        # History Page (Enhancement #4 - Historical Analysis Storage)
        with gr.Group(visible=False) as history_page:
            gr.Markdown("### Analysis History")
            gr.Markdown("View your previous portfolio analyses")

            with gr.Row():
                with gr.Column(scale=4):
                    # Search and filters
                    with gr.Row():
                        history_search = gr.Textbox(
                            placeholder="Search by ticker, date...",
                            label="Search",
                            scale=3,
                            elem_id="history-search"
                        )
                        history_date_filter = gr.Dropdown(
                            choices=[
                                ("All Time", "all"),
                                ("Last 7 Days", "7d"),
                                ("Last 30 Days", "30d"),
                                ("Last 90 Days", "90d"),
                            ],
                            value="all",
                            label="Date Range",
                            scale=1
                        )
                        history_refresh_btn = gr.Button("πŸ”„ Refresh", size="sm", scale=1)
                with gr.Column(scale=1):
                    back_to_input_btn = gr.Button("New Analysis", variant="secondary")

            history_table = gr.Dataframe(
                headers=["ID", "Date", "Holdings", "Risk Tolerance", "AI Synthesis Preview"],
                datatype=["str", "str", "str", "str", "str"],
                interactive=False,
                wrap=True,
                elem_id="history-table",
                column_widths=["5%", "15%", "25%", "15%", "40%"]
            )

            # Pagination controls
            with gr.Row():
                history_prev_btn = gr.Button("← Previous", size="sm", scale=1)
                history_page_info = gr.Markdown("Page 1 of 1", elem_id="history-page-info")
                history_next_btn = gr.Button("Next β†’", size="sm", scale=1)

            with gr.Accordion("Selected Analysis Details", open=False) as history_details:
                history_details_output = gr.Markdown("")

            view_history_btn = gr.Button("View Analysis History", variant="secondary", visible=False)

        # Event handlers
        def show_input_page():
            return {
                task_page: gr.update(visible=False),
                input_page: gr.update(visible=True),
                results_page: gr.update(visible=False),
                history_page: gr.update(visible=False),
                build_page: gr.update(visible=False),
                compare_page: gr.update(visible=False),
                test_page: gr.update(visible=False)
            }

        def show_task_page():
            return {
                task_page: gr.update(visible=True),
                input_page: gr.update(visible=False),
                results_page: gr.update(visible=False),
                history_page: gr.update(visible=False),
                build_page: gr.update(visible=False),
                compare_page: gr.update(visible=False),
                test_page: gr.update(visible=False)
            }

        def show_build_page():
            return {
                task_page: gr.update(visible=False),
                input_page: gr.update(visible=False),
                results_page: gr.update(visible=False),
                history_page: gr.update(visible=False),
                build_page: gr.update(visible=True),
                compare_page: gr.update(visible=False),
                test_page: gr.update(visible=False)
            }

        def show_compare_page():
            return {
                task_page: gr.update(visible=False),
                input_page: gr.update(visible=False),
                results_page: gr.update(visible=False),
                history_page: gr.update(visible=False),
                build_page: gr.update(visible=False),
                compare_page: gr.update(visible=True),
                test_page: gr.update(visible=False)
            }

        def show_test_page():
            return {
                task_page: gr.update(visible=False),
                input_page: gr.update(visible=False),
                results_page: gr.update(visible=False),
                history_page: gr.update(visible=False),
                build_page: gr.update(visible=False),
                compare_page: gr.update(visible=False),
                test_page: gr.update(visible=True)
            }

        # ============================================================
        # AUDIO GENERATION HANDLERS
        # ============================================================

        async def generate_analysis_audio():
            """Generate audio narration for portfolio analysis on-demand."""
            global LAST_ANALYSIS_STATE

            if not LAST_ANALYSIS_STATE:
                logger.warning("No analysis state available for audio generation")
                return (
                    gr.update(visible=False),  # audio_player
                    gr.update(visible=True),   # button
                )

            try:
                from backend.audio.tts_service import TTSService

                tts = TTSService()
                if not tts.is_available():
                    logger.warning("TTS service not available")
                    return (
                        gr.update(visible=False),
                        gr.update(visible=True),
                    )

                # Extract analysis text
                ai_synthesis = LAST_ANALYSIS_STATE.get("ai_synthesis", "")
                recommendations = LAST_ANALYSIS_STATE.get("recommendations", [])

                if not ai_synthesis and not recommendations:
                    logger.warning("No analysis content available")
                    return (
                        gr.update(visible=False),
                        gr.update(visible=True),
                    )

                logger.info("Generating audio for analysis...")

                # Generate audio
                audio_path = await tts.generate_analysis_narration(
                    analysis_text=ai_synthesis[:1000],  # Limit to 1000 chars
                    recommendations=recommendations
                )

                logger.info(f"Audio generated: {audio_path}")

                return (
                    gr.update(value=audio_path, visible=True),  # Show audio player
                    gr.update(visible=True),  # Keep button visible
                )

            except Exception as e:
                logger.error(f"Audio generation failed: {e}")
                return (
                    gr.update(visible=False),
                    gr.update(visible=True),
                )

        async def generate_build_audio():
            """Generate audio narration for built portfolio on-demand."""
            global LAST_BUILD_RESULT

            if not LAST_BUILD_RESULT:
                logger.warning("No build result available for audio generation")
                return (
                    gr.update(visible=False),
                    gr.update(visible=True),
                )

            try:
                from backend.audio.tts_service import TTSService

                tts = TTSService()
                if not tts.is_available():
                    logger.warning("TTS service not available")
                    return (
                        gr.update(visible=False),
                        gr.update(visible=True),
                    )

                # Extract portfolio summary
                portfolio_summary = LAST_BUILD_RESULT.get("summary", "")
                holdings = LAST_BUILD_RESULT.get("holdings", [])

                if not portfolio_summary:
                    logger.warning("No portfolio summary available")
                    return (
                        gr.update(visible=False),
                        gr.update(visible=True),
                    )

                logger.info("Generating audio for portfolio...")

                # Generate audio
                audio_path = await tts.generate_portfolio_narration(
                    portfolio_summary=portfolio_summary[:1000],
                    holdings=holdings
                )

                logger.info(f"Audio generated: {audio_path}")

                return (
                    gr.update(value=audio_path, visible=True),
                    gr.update(visible=True),
                )

            except Exception as e:
                logger.error(f"Audio generation failed: {e}")
                return (
                    gr.update(visible=False),
                    gr.update(visible=True),
                )

        async def generate_debate_audio():
            """Generate multi-speaker debate audio on-demand."""
            global LAST_DEBATE_DATA

            logger.info(f"generate_debate_audio called. LAST_DEBATE_DATA exists: {LAST_DEBATE_DATA is not None}")
            if LAST_DEBATE_DATA:
                logger.info(f"Debate data keys: {LAST_DEBATE_DATA.keys()}")
                logger.info(f"Bull case length: {len(LAST_DEBATE_DATA.get('bull_case', ''))}")
                logger.info(f"Bear case length: {len(LAST_DEBATE_DATA.get('bear_case', ''))}")
                logger.info(f"Consensus length: {len(LAST_DEBATE_DATA.get('consensus', ''))}")

            if not LAST_DEBATE_DATA:
                logger.warning("No debate data available for audio generation")
                return (
                    gr.update(visible=False),
                    gr.update(visible=True),
                )

            try:
                from backend.audio.tts_service import DebateAudioGenerator

                debate_gen = DebateAudioGenerator()
                if not debate_gen.is_available():
                    logger.warning("Debate audio generator not available")
                    return (
                        gr.update(visible=False),
                        gr.update(visible=True),
                    )

                # Extract debate data
                bull_case = LAST_DEBATE_DATA.get("bull_case", "")
                bear_case = LAST_DEBATE_DATA.get("bear_case", "")
                consensus = LAST_DEBATE_DATA.get("consensus", "")
                bull_confidence = LAST_DEBATE_DATA.get("bull_confidence")
                bear_confidence = LAST_DEBATE_DATA.get("bear_confidence")
                stance = LAST_DEBATE_DATA.get("stance")

                if not bull_case or not bear_case or not consensus:
                    logger.warning("Incomplete debate data")
                    return (
                        gr.update(visible=False),
                        gr.update(visible=True),
                    )

                logger.info("Generating debate audio...")

                # Generate multi-speaker debate audio
                audio_path = await debate_gen.generate_debate_audio(
                    bull_case=bull_case[:1000],
                    bear_case=bear_case[:1000],
                    consensus=consensus[:1000],
                    bull_confidence=bull_confidence,
                    bear_confidence=bear_confidence,
                    stance=stance
                )

                logger.info(f"Debate audio generated: {audio_path}")
                logger.info(f"Audio file exists: {os.path.exists(audio_path) if audio_path else False}")
                logger.info(f"Returning audio player update with visible=True")

                return (
                    gr.update(value=audio_path, visible=True),
                    gr.update(visible=True),
                )

            except Exception as e:
                logger.error(f"Debate audio generation failed: {e}")
                return (
                    gr.update(visible=False),
                    gr.update(visible=True),
                )

        async def handle_build_portfolio(goals, risk_tolerance, constraints, session_state):
            """Handle the Build Portfolio workflow with streaming updates.

            Args:
                goals: List of selected investment goals
                risk_tolerance: Risk tolerance score 1-10
                constraints: User constraints text
                session_state: User session

            Yields:
                Tuple of UI updates: (agent_chat, results_container, status)
            """
            global LAST_BUILD_RESULT
            logger.info(f"handle_build_portfolio called")
            logger.info(f"Input types - goals: {type(goals).__name__}, risk_tolerance: {type(risk_tolerance).__name__}, constraints: {type(constraints).__name__}")
            logger.info(f"Input values - goals: {goals!r}, risk_tolerance: {risk_tolerance!r}, constraints: {constraints!r}")

            if not goals:
                logger.warning(f"No goals provided")
                yield (
                    gr.update(value=[], visible=False),  # build_agent_chat (empty, hidden)
                    gr.update(visible=True),  # build_results_container
                    "Please select at least one investment goal.",  # build_status
                    gr.update(visible=False)  # build_audio_btn (hide on error)
                )
                return

            try:
                logger.info(f"Initialising MCP and workflow routers")
                # Initialise MCP router and workflow router
                from backend.mcp_router import MCPRouter
                from backend.agents.workflow_router import WorkflowRouter

                mcp_router = MCPRouter()
                workflow_router = WorkflowRouter(mcp_router)

                # Normalise input types
                goals_list = goals if isinstance(goals, list) else [goals] if goals else []
                constraints_str = ", ".join(constraints) if isinstance(constraints, list) else (constraints or "")

                logger.info(f"After normalisation - goals_list: {goals_list!r} (type: {type(goals_list).__name__})")
                logger.info(f"After normalisation - constraints_str: {constraints_str!r} (type: {type(constraints_str).__name__})")

                # Stream the build workflow
                chat_messages = []
                message_count = 0

                logger.info(f"Starting stream from route_build_stream")
                async for message in workflow_router.route_build_stream(
                    goals=goals_list,
                    risk_tolerance=int(risk_tolerance),
                    constraints=constraints_str
                ):
                    try:
                        message_count += 1
                        logger.debug(f"Received message #{message_count} from stream")
                        logger.debug(f"Message type: {type(message).__name__}")
                        logger.debug(f"Message keys: {message.keys() if isinstance(message, dict) else 'N/A'}")
                        logger.debug(f"Message content type: {type(message.get('content')).__name__ if isinstance(message, dict) else 'N/A'}")
                        logger.debug(f"Message: {message!r}")

                        chat_messages.append(message)
                        logger.debug(f"Message appended to chat_messages. Total messages: {len(chat_messages)}")

                        try:
                            # Stream each message to the chatbot in real-time
                            logger.debug(f"About to yield UI update with {len(chat_messages)} messages")
                            yield (
                                gr.update(value=chat_messages, visible=True),  # build_agent_chat (visible, growing list)
                                gr.update(visible=False),  # build_results_container (hidden during streaming)
                                "",  # build_status
                                gr.update(visible=False)  # build_audio_btn (hide during streaming)
                            )
                            logger.debug(f"UI update yielded successfully")
                        except Exception as e:
                            logger.error(f"Error yielding UI update: {e}")
                            logger.error(f"chat_messages type: {type(chat_messages).__name__}")
                            logger.error(f"chat_messages length: {len(chat_messages)}")
                            logger.error(f"Last message: {chat_messages[-1] if chat_messages else 'N/A'}")
                            raise

                    except Exception as e:
                        logger.error(f"Error processing message #{message_count}")
                        logger.error(f"Message: {message!r}")
                        logger.error(f"Error type: {type(e).__name__}")
                        logger.error(f"Error message: {str(e)}")
                        logger.error(f"Full traceback:\n{traceback.format_exc()}")
                        raise

                # Store build result for audio generation
                if chat_messages:
                    final_message = chat_messages[-1]
                    if isinstance(final_message, dict) and "metadata" in final_message:
                        portfolio_data = final_message.get("metadata", {}).get("portfolio", {})
                        # Handle both dict and list formats
                        if isinstance(portfolio_data, list):
                            holdings = portfolio_data
                        elif isinstance(portfolio_data, dict):
                            holdings = portfolio_data.get("holdings", [])
                        else:
                            holdings = []

                        LAST_BUILD_RESULT = {
                            "summary": final_message.get("content", ""),
                            "holdings": holdings,
                            "reasoning": final_message.get("metadata", {}).get("reasoning_trace", [])
                        }
                        logger.info("Build result stored for audio generation")

                # Final yield: Show results container
                logger.info(f"Completed streaming. Yielding final result with {len(chat_messages)} messages")
                yield (
                    gr.update(value=chat_messages, visible=True),  # build_agent_chat (final state, visible)
                    gr.update(visible=True),  # build_results_container (show results)
                    "Portfolio built successfully!",  # build_status
                    gr.update(visible=True)  # build_audio_btn (show audio button)
                )

            except Exception as e:
                logger.error(f"=== BUILD PORTFOLIO ERROR ===")
                logger.error(f"Error type: {type(e).__name__}")
                logger.error(f"Error message: {str(e)}")

                # Extract detailed traceback information
                import traceback
                import sys
                tb = sys.exc_info()[2]
                if tb:
                    tb_list = traceback.extract_tb(tb)
                    for frame_summary in tb_list:
                        logger.error(f"  File: {frame_summary.filename}")
                        logger.error(f"  Function: {frame_summary.name}")
                        logger.error(f"  Line {frame_summary.lineno}: {frame_summary.line}")

                logger.error(f"Full traceback:\n{traceback.format_exc()}")
                logger.error(f"message_count at error: {message_count if 'message_count' in locals() else 'N/A'}")
                logger.error(f"chat_messages at error: {len(chat_messages) if 'chat_messages' in locals() else 'N/A'} messages")
                logger.error(f"=== END BUILD PORTFOLIO ERROR ===")

                yield (
                    gr.update(value=[], visible=False),  # build_agent_chat (empty, hidden on error)
                    gr.update(visible=True),  # build_results_container
                    f"Error building portfolio: {str(e)}",  # build_status
                    gr.update(visible=False)  # build_audio_btn (hide on error)
                )

        def handle_build_accept(portfolio_table):
            """Accept built portfolio and populate input for analysis.

            Args:
                portfolio_table: DataFrame with ticker and allocation data

            Returns:
                Tuple of values for each output component
            """
            if portfolio_table is None or len(portfolio_table) == 0:
                return (
                    "",  # portfolio_input
                    gr.update(visible=False),  # task_page
                    gr.update(visible=True),  # input_page
                    gr.update(visible=False),  # results_page
                    gr.update(visible=False),  # history_page
                    gr.update(visible=False),  # build_page
                    gr.update(visible=False),  # compare_page
                    gr.update(visible=False)  # test_page
                )

            # Convert portfolio table to input format
            lines = []
            for row in portfolio_table:
                ticker = row[0] if len(row) > 0 else ""
                allocation = row[1] if len(row) > 1 else 0
                if ticker:
                    lines.append(f"{ticker} {allocation}%")

            portfolio_text = "\n".join(lines)

            return (
                portfolio_text,  # portfolio_input
                gr.update(visible=False),  # task_page
                gr.update(visible=True),  # input_page
                gr.update(visible=False),  # results_page
                gr.update(visible=False),  # history_page
                gr.update(visible=False),  # build_page
                gr.update(visible=False),  # compare_page
                gr.update(visible=False)  # test_page
            )

        async def handle_compare_portfolio(portfolio_text, session_state):
            """Handle the Compare Strategies workflow with streaming debate.

            Args:
                portfolio_text: Raw portfolio text input
                session_state: User session

            Yields:
                Tuple of UI updates: (debate_chat, results_container, status, bull_case, bull_conf,
                                      bear_case, bear_conf, consensus, stance, debate_transcript)
            """
            global LAST_DEBATE_DATA
            if not portfolio_text or not portfolio_text.strip():
                yield (
                    gr.update(value=[], visible=False),  # compare_debate_chat (empty, hidden)
                    gr.update(visible=True),  # compare_results_container
                    "Please enter your portfolio holdings.",  # compare_status
                    "",  # compare_bull_case
                    0,  # compare_bull_confidence
                    "",  # compare_bear_case
                    0,  # compare_bear_confidence
                    "",  # compare_consensus
                    "",  # compare_stance
                    [],  # compare_debate_transcript
                    gr.update(visible=False)  # compare_audio_btn (hide on error)
                )
                return

            # Parse portfolio
            holdings = parse_portfolio_input(portfolio_text)

            if not holdings:
                yield (
                    gr.update(value=[], visible=False),  # compare_debate_chat (empty, hidden)
                    gr.update(visible=True),  # compare_results_container
                    "Could not parse portfolio. Please check format.",  # compare_status
                    "", 0, "", 0, "", "", [],
                    gr.update(visible=False)  # compare_audio_btn (hide on error)
                )
                return

            try:
                # Initialise MCP router and workflow router
                from backend.mcp_router import MCPRouter
                from backend.agents.workflow_router import WorkflowRouter

                mcp_router = MCPRouter()
                workflow_router = WorkflowRouter(mcp_router)

                # Stream the compare workflow
                chat_messages = []
                bull_case_data = {}
                bear_case_data = {}
                consensus_data = {}
                debate_transcript = []

                async for message in workflow_router.route_compare_stream(holdings=holdings):
                    chat_messages.append(message)

                    # Stream each message to the chatbot in real-time
                    yield (
                        gr.update(value=chat_messages, visible=True),  # compare_debate_chat (visible, growing list)
                        gr.update(visible=False),  # compare_results_container (hidden during streaming)
                        "",  # compare_status
                        "",  # compare_bull_case
                        0,  # compare_bull_confidence
                        "",  # compare_bear_case
                        0,  # compare_bear_confidence
                        "",  # compare_consensus
                        "",  # compare_stance
                        [],  # compare_debate_transcript
                        gr.update(visible=False)  # compare_audio_btn (hide during streaming)
                    )

                    # Extract data from final consensus message
                    metadata = message.get("metadata", {})
                    if metadata and "Consensus" in metadata.get("title", ""):
                        # This is the final consensus - parse it
                        content = message.get("content", "")
                        # Store for final display
                        consensus_data = {"recommendation": content, "stance": "Mixed"}

                        # Extract bull/bear from previous messages
                        for msg in chat_messages:
                            msg_meta = msg.get("metadata", {})
                            title = msg_meta.get("title", "")
                            if "Bull Researcher" in title:
                                bull_case_data = {
                                    "thesis": msg.get("content", ""),
                                    "confidence": 65  # Default, could parse from title
                                }
                            elif "Bear Researcher" in title:
                                bear_case_data = {
                                    "thesis": msg.get("content", ""),
                                    "confidence": 60  # Default, could parse from title
                                }

                # Store debate data for audio generation
                if consensus_data and bull_case_data and bear_case_data:
                    LAST_DEBATE_DATA = {
                        "bull_case": bull_case_data.get("thesis", ""),
                        "bear_case": bear_case_data.get("thesis", ""),
                        "consensus": consensus_data.get("recommendation", ""),
                        "bull_confidence": bull_case_data.get("confidence"),
                        "bear_confidence": bear_case_data.get("confidence"),
                        "stance": consensus_data.get("stance", "Mixed")
                    }
                    logger.info("Debate data stored for audio generation")

                # Final yield: Show results container with analysis
                yield (
                    gr.update(value=chat_messages, visible=True),  # compare_debate_chat (final state, visible)
                    gr.update(visible=True),  # compare_results_container (show results)
                    "Analysis complete!",  # compare_status
                    bull_case_data.get("thesis", ""),  # compare_bull_case
                    bull_case_data.get("confidence", 0),  # compare_bull_confidence
                    bear_case_data.get("thesis", ""),  # compare_bear_case
                    bear_case_data.get("confidence", 0),  # compare_bear_confidence
                    consensus_data.get("recommendation", ""),  # compare_consensus
                    consensus_data.get("stance", "Mixed"),  # compare_stance
                    chat_messages,  # compare_debate_transcript (use chat messages)
                    gr.update(visible=True)  # compare_audio_btn (show audio button)
                )

            except Exception as e:
                logger.error(f"Compare portfolio error: {e}")
                yield (
                    gr.update(value=[], visible=False),  # compare_debate_chat (empty, hidden on error)
                    gr.update(visible=True),  # compare_results_container
                    f"Error: {str(e)}",  # compare_status
                    "", 0, "", 0, "", "", [],
                    gr.update(visible=False)  # compare_audio_btn (hide on error)
                )

        async def handle_test_changes(portfolio_text, changes_text, portfolio_value, session_state):
            """Handle the Test Changes workflow.

            Args:
                portfolio_text: Current portfolio as text (ticker weight%)
                changes_text: Proposed changes as text
                portfolio_value: Total portfolio value
                session_state: User session

            Returns:
                Tuple of UI updates for test results
            """
            try:
                if not portfolio_text.strip():
                    return (
                        gr.update(visible=True),
                        "Please enter your current portfolio.",
                        [],
                        [],
                        [],
                        [],
                        "",
                        ""
                    )

                if not changes_text.strip():
                    return (
                        gr.update(visible=True),
                        "Please enter proposed changes.",
                        [],
                        [],
                        [],
                        [],
                        "",
                        ""
                    )

                # Parse current portfolio
                current_portfolio = {}
                for line in portfolio_text.strip().split("\n"):
                    line = line.strip()
                    if not line:
                        continue
                    parts = line.replace("%", "").split()
                    if len(parts) >= 2:
                        ticker = parts[0].upper()
                        try:
                            weight = float(parts[1])
                            current_portfolio[ticker] = {"weight": weight}
                        except ValueError:
                            continue

                # Parse proposed changes
                proposed_changes = []
                for line in changes_text.strip().split("\n"):
                    line = line.strip().lower()
                    if not line:
                        continue
                    parts = line.split()
                    if len(parts) >= 3:
                        action = parts[0]
                        ticker = parts[1].upper()
                        try:
                            amount = float(parts[2])
                            if action in ["buy", "sell"]:
                                proposed_changes.append({
                                    "action": action,
                                    "ticker": ticker,
                                    "amount": amount
                                })
                        except ValueError:
                            continue

                if not current_portfolio:
                    return (
                        gr.update(visible=True),
                        "Could not parse portfolio. Use format: TICKER WEIGHT%",
                        [],
                        [],
                        [],
                        [],
                        "",
                        ""
                    )

                if not proposed_changes:
                    return (
                        gr.update(visible=True),
                        "Could not parse changes. Use format: buy/sell TICKER AMOUNT",
                        [],
                        [],
                        [],
                        [],
                        "",
                        ""
                    )

                # Initialise MCP router and workflow router
                from backend.mcp_router import MCPRouter
                from backend.agents.workflow_router import WorkflowRouter

                mcp_router = MCPRouter()
                workflow_router = WorkflowRouter(mcp_router)

                # Run the test workflow
                result = await workflow_router.route_test(
                    current_portfolio=current_portfolio,
                    proposed_changes=proposed_changes,
                    portfolio_value=float(portfolio_value)
                )

                # Format current metrics for display
                current_metrics_data = []
                for metric, value in result.get("current", {}).get("metrics", {}).items():
                    if isinstance(value, (int, float)):
                        current_metrics_data.append([metric.replace("_", " ").title(), f"{value:.4f}"])

                # Format simulated metrics for display
                simulated_metrics_data = []
                for metric, value in result.get("simulated", {}).get("metrics", {}).items():
                    if isinstance(value, (int, float)):
                        simulated_metrics_data.append([metric.replace("_", " ").title(), f"{value:.4f}"])

                # Format impact summary
                impact_data = []
                for metric, impact in result.get("impact", {}).items():
                    impact_data.append([
                        metric.replace("_", " ").title(),
                        f"{impact.get('current', 0):.4f}",
                        f"{impact.get('simulated', 0):.4f}",
                        f"{impact.get('delta', 0):+.4f}",
                        f"{impact.get('pct_change', 0):+.2f}%"
                    ])

                # Format stress test comparison
                stress_data = []
                for scenario, data in result.get("stress_comparison", {}).items():
                    stress_data.append([
                        scenario.replace("_", " ").title(),
                        f"{data.get('shock', 0):.0f}%",
                        f"${data.get('current_loss', 0):,.0f}",
                        f"${data.get('simulated_loss', 0):,.0f}",
                        f"${data.get('improvement', 0):+,.0f}"
                    ])

                # Format recommendations
                recommendations_text = "### Recommendations\n\n"
                for rec in result.get("recommendations", []):
                    recommendations_text += f"- {rec}\n"

                # Format assessment
                assessment_text = f"### Overall Assessment\n\n**{result.get('overall_assessment', 'No assessment')}**"

                return (
                    gr.update(visible=True),
                    "Simulation complete!",
                    current_metrics_data,
                    simulated_metrics_data,
                    impact_data,
                    stress_data,
                    assessment_text,
                    recommendations_text
                )

            except Exception as e:
                logger.error(f"Test changes error: {e}")
                return (
                    gr.update(visible=True),
                    f"Error running simulation: {str(e)}",
                    [],
                    [],
                    [],
                    [],
                    "",
                    ""
                )

        def sync_handle_test_changes(portfolio_text, changes_text, portfolio_value, session_state):
            """Synchronous wrapper for handle_test_changes."""
            return asyncio.run(handle_test_changes(portfolio_text, changes_text, portfolio_value, session_state))

        async def load_history(session_state):
            """Load analysis history from database.

            Demo users do not have persistent history - their analyses are ephemeral
            and only exist for the current session.
            """
            try:
                is_demo = session_state.get("is_demo", False) if session_state else False

                # Demo users don't have persistent history
                if is_demo:
                    logger.info("Demo mode: No persistent history available (analyses are ephemeral)")
                    return [], "Demo mode does not save history. Sign up for a free account to save your analyses!"

                session = UserSession.from_dict(session_state)

                # Must be authenticated user with valid user_id
                if not session or not session.user_id:
                    logger.error("No valid user_id for loading history")
                    return [], "Please sign in to view your analysis history"

                user_id = session.user_id
                logger.info(f"Loading history for user: {user_id}")
                history = await db.get_analysis_history(user_id, limit=20)

                if not history:
                    logger.info(f"No history found for user {user_id}")
                    return [], "No previous analyses found"

                logger.info(f"Loaded {len(history)} analyses for user {user_id}")

                # Format history for dataframe
                # Store analysis records globally for row selection
                global HISTORY_RECORDS
                HISTORY_RECORDS = history

                rows = []
                for i, record in enumerate(history):
                    # Format holdings as comma-separated tickers
                    holdings_str = ", ".join([h.get("ticker", "?") for h in record.get("holdings_snapshot", [])])

                    # Truncate AI synthesis for preview
                    synthesis_preview = record.get("ai_synthesis", "")

                    rows.append([
                        str(i),  # Row index for selection
                        record.get("created_at", "").split("T")[0],  # Date only
                        holdings_str,
                        record.get("portfolios", {}).get("risk_tolerance", "moderate"),
                        synthesis_preview
                    ])

                return rows, f"Loaded {len(history)} previous analyses"
            except Exception as e:
                logger.error(f"Failed to load history: {e}")
                return [], f"Error loading history: {str(e)}"

        def sync_load_history(session_state):
            """Synchronous wrapper for load_history."""
            return asyncio.run(load_history(session_state))

        async def filter_history(session_state, search_query: str, date_filter: str, page: int = 1, page_size: int = 10):
            """Filter and paginate history based on search query and date range.

            Args:
                session_state: User session dictionary
                search_query: Search string to filter by ticker or date
                date_filter: Date range filter ("all", "7d", "30d", "90d")
                page: Current page number (1-indexed)
                page_size: Number of items per page

            Returns:
                Tuple of (filtered_rows, page_info_message)
            """
            from datetime import datetime, timedelta

            try:
                is_demo = session_state.get("is_demo", False) if session_state else False

                if is_demo:
                    return [], "Page 1 of 1"

                session = UserSession.from_dict(session_state)
                if not session or not session.user_id:
                    return [], "Page 1 of 1"

                user_id = session.user_id

                # Load full history (increased limit for filtering)
                full_history = await db.get_analysis_history(user_id, limit=100)

                if not full_history:
                    return [], "Page 1 of 1"

                # Apply date filter
                filtered_history = []
                now = datetime.now()
                cutoff = None

                if date_filter == "7d":
                    cutoff = now - timedelta(days=7)
                elif date_filter == "30d":
                    cutoff = now - timedelta(days=30)
                elif date_filter == "90d":
                    cutoff = now - timedelta(days=90)

                for record in full_history:
                    # Apply date filter
                    if cutoff:
                        try:
                            created_at_str = record.get('created_at', '')
                            if created_at_str:
                                # Handle both ISO format with and without timezone
                                if 'T' in created_at_str:
                                    created_at_str = created_at_str.split('.')[0]  # Remove microseconds
                                    created_at_str = created_at_str.replace('Z', '')  # Remove timezone
                                    analysis_date = datetime.fromisoformat(created_at_str)
                                else:
                                    analysis_date = datetime.fromisoformat(created_at_str)

                                if analysis_date < cutoff:
                                    continue
                        except Exception as e:
                            logger.warning(f"Date parsing error: {e}")
                            continue

                    # Apply search filter
                    if search_query and search_query.strip():
                        query_lower = search_query.lower().strip()

                        # Search in tickers
                        holdings = record.get('holdings_snapshot', [])
                        tickers = ' '.join([h.get('ticker', '') for h in holdings]).lower()

                        # Search in date
                        date_str = record.get('created_at', '').lower()

                        # Search in risk tolerance
                        risk = record.get('portfolios', {}).get('risk_tolerance', '').lower()

                        # If query not found in any field, skip this record
                        if query_lower not in tickers and query_lower not in date_str and query_lower not in risk:
                            continue

                    filtered_history.append(record)

                # Store filtered records globally for row selection
                global HISTORY_RECORDS
                HISTORY_RECORDS = filtered_history

                # Calculate pagination
                total_items = len(filtered_history)
                total_pages = max(1, (total_items + page_size - 1) // page_size)
                page = max(1, min(page, total_pages))  # Clamp page to valid range

                start_idx = (page - 1) * page_size
                end_idx = min(start_idx + page_size, total_items)

                page_items = filtered_history[start_idx:end_idx]

                # Format for display
                rows = []
                for i, record in enumerate(page_items, start=start_idx):
                    holdings_str = ", ".join([h.get("ticker", "?") for h in record.get("holdings_snapshot", [])])
                    synthesis_preview = record.get("ai_synthesis", "")

                    rows.append([
                        str(i),  # Global index for selection
                        record.get("created_at", "").split("T")[0],
                        holdings_str,
                        record.get("portfolios", {}).get("risk_tolerance", "moderate"),
                        synthesis_preview
                    ])

                page_info = f"Page {page} of {total_pages} ({total_items} total)"
                return rows, page_info

            except Exception as e:
                logger.error(f"Failed to filter history: {e}")
                return [], "Page 1 of 1"

        def sync_filter_history(session_state, search_query: str, date_filter: str, page: int = 1, page_size: int = 10):
            """Synchronous wrapper for filter_history."""
            return asyncio.run(filter_history(session_state, search_query, date_filter, page, page_size))

        def view_historical_analysis(evt: gr.SelectData):
            """View full details of a selected historical analysis.

            Args:
                evt: Gradio SelectData event containing row index

            Returns:
                Markdown string with full analysis details
            """
            global HISTORY_RECORDS

            try:
                # Get the row index from the selected row
                row_index = int(evt.value)  # First column contains the index

                if not HISTORY_RECORDS or row_index >= len(HISTORY_RECORDS):
                    return "**Error**: Could not load analysis. Please refresh the history table."

                record = HISTORY_RECORDS[row_index]

                # Format detailed analysis view
                details = f"""# Analysis Details

**Date**: {record.get('created_at', 'Unknown').split('T')[0]}
**Portfolio**: {record.get('portfolios', {}).get('name', 'Unnamed Portfolio')}
**Risk Tolerance**: {record.get('portfolios', {}).get('risk_tolerance', 'moderate')}

---

## Holdings Snapshot
"""
                # Format holdings as table
                holdings = record.get('holdings_snapshot', [])
                if holdings:
                    details += "\n| Ticker | Shares | Value |\n|--------|--------|-------|\n"
                    for holding in holdings:
                        details += f"| {holding.get('ticker', '?')} | {holding.get('shares', 0)} | ${holding.get('value', 0):,.2f} |\n"
                else:
                    details += "\n*No holdings data available*\n"

                details += f"""

---

## AI Analysis

{record.get('ai_synthesis', '*No analysis available*')}

---

## Recommendations
"""
                recommendations = record.get('recommendations', [])
                if recommendations:
                    for i, rec in enumerate(recommendations, 1):
                        details += f"\n{i}. {rec}"
                else:
                    details += "\n*No recommendations available*"

                details += f"""

---

**Model**: {record.get('model_version', 'Unknown')}
**Execution Time**: {record.get('execution_time_ms', 0):,.0f}ms
"""

                return details

            except Exception as e:
                logger.error(f"Failed to view historical analysis: {e}")
                return f"**Error**: Failed to load analysis details: {str(e)}"

        def export_current_analysis_csv():
            """Return pre-generated CSV file path.

            Returns:
                Path to temporary CSV file, or None if no analysis available
            """
            global LAST_EXPORT_CSV_PATH

            if not LAST_EXPORT_CSV_PATH:
                logger.warning("No CSV export available")
                return None

            logger.info(f"Returning pre-generated CSV: {LAST_EXPORT_CSV_PATH}")
            return LAST_EXPORT_CSV_PATH

        def export_current_analysis_pdf():
            """Return pre-generated PDF file path.

            Returns:
                Path to temporary PDF file, or None if no analysis available
            """
            global LAST_EXPORT_PDF_PATH

            if not LAST_EXPORT_PDF_PATH:
                logger.warning("No PDF export available")
                return None

            logger.info(f"Returning pre-generated PDF: {LAST_EXPORT_PDF_PATH}")
            return LAST_EXPORT_PDF_PATH

        def validate_email_format(email: str) -> str:
            """Validate email format in real-time.

            Args:
                email: Email address to validate

            Returns:
                Validation message
            """
            import re

            if not email:
                return ""

            email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

            if re.match(email_regex, email):
                return "βœ“ Valid email format"
            else:
                return "❌ Invalid email format"

        def validate_password_match(password: str, confirm: str) -> str:
            """Check if passwords match in real-time.

            Args:
                password: Password field value
                confirm: Confirmation field value

            Returns:
                Validation message
            """
            if not confirm:
                return ""

            if password == confirm:
                return "βœ“ Passwords match"
            else:
                return "❌ Passwords do not match"

        def check_password_strength(password: str) -> str:
            """Real-time password strength indicator.

            Args:
                password: Password to evaluate

            Returns:
                Strength indicator with feedback
            """
            import re

            if not password:
                return ""

            score = 0
            feedback = []

            # Length check (main NIST requirement)
            if len(password) >= 15:
                score += 3  # Length is most important
            elif len(password) >= 12:
                score += 2
                feedback.append("15+ characters")
            elif len(password) >= 8:
                score += 1
                feedback.append("15+ characters")
            else:
                feedback.append("15+ characters")

            # Optional complexity (not required by NIST)
            if re.search(r'[A-Z]', password):
                score += 1
            if re.search(r'[a-z]', password):
                score += 1
            if re.search(r'\d', password):
                score += 1
            if re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
                score += 1

            # Generate feedback message
            if score <= 2:
                return "πŸ”΄ **Weak** - Add: " + ", ".join(feedback) if feedback else "πŸ”΄ **Weak**"
            elif score <= 4:
                return "🟠 **Moderate** - " + (("Add: " + ", ".join(feedback)) if feedback else "Consider 15+ characters")
            elif score <= 6:
                return "🟑 **Good** - " + (("Add: " + ", ".join(feedback)) if feedback else "Meets requirements")
            else:
                return "🟒 **Strong** - Exceeds requirements"

        def show_history_page():
            """Navigate to history page."""
            return {
                task_page: gr.update(visible=False),
                input_page: gr.update(visible=False),
                results_page: gr.update(visible=False),
                history_page: gr.update(visible=True)
            }

        def load_tax_holdings():
            """Load current portfolio holdings into the cost basis dataframe.

            Returns:
                List of lists with [ticker, shares, "", ""] for each holding.
            """
            global LAST_ANALYSIS_STATE

            if not LAST_ANALYSIS_STATE or "holdings" not in LAST_ANALYSIS_STATE:
                return []

            holdings = LAST_ANALYSIS_STATE.get("holdings", [])
            dataframe_data = []

            for holding in holdings:
                ticker = holding.get("ticker", "")
                quantity = holding.get("quantity", 0)
                if ticker and quantity > 0:
                    dataframe_data.append([ticker, quantity, None, ""])

            return dataframe_data

        def calculate_tax_impact(
            filing_status: str,
            annual_income: float,
            cost_basis_method: str,
            cost_basis_data: list
        ):
            """Calculate tax impact for current portfolio holdings.

            Args:
                filing_status: Tax filing status
                annual_income: Annual taxable income
                cost_basis_method: Cost basis calculation method
                cost_basis_data: Dataframe rows with ticker, shares, purchase_price, purchase_date

            Returns:
                Formatted markdown tax analysis report
            """
            global LAST_ANALYSIS_STATE

            if not LAST_ANALYSIS_STATE or "holdings" not in LAST_ANALYSIS_STATE:
                return """# Tax Impact Analysis

**Error**: Please run a portfolio analysis first before calculating tax impact.

Use the "Analyse Portfolio" button to analyse your portfolio, then return here to view tax implications.
"""

            try:
                holdings = LAST_ANALYSIS_STATE.get("holdings", [])

                # Parse cost basis dataframe into structured format
                user_cost_basis = []

                # Handle pandas DataFrame from Gradio
                import pandas as pd
                if isinstance(cost_basis_data, pd.DataFrame):
                    logger.info(f"Received DataFrame with {len(cost_basis_data)} rows")
                    if not cost_basis_data.empty:
                        # Convert DataFrame to list of lists
                        cost_basis_rows = cost_basis_data.values.tolist()
                        logger.info(f"DataFrame data: {cost_basis_rows}")
                    else:
                        cost_basis_rows = []
                        logger.info("DataFrame is empty")
                elif cost_basis_data is not None:
                    # Already a list
                    cost_basis_rows = cost_basis_data
                    logger.info(f"Received list with {len(cost_basis_rows)} rows")
                else:
                    cost_basis_rows = []
                    logger.info("No cost basis data provided")

                for row in cost_basis_rows:
                    if len(row) >= 4:
                        # Handle pandas nan values
                        ticker_val = row[0]
                        if pd.isna(ticker_val) or not str(ticker_val).strip():
                            continue

                        ticker = str(ticker_val).strip().upper()
                        shares = None if pd.isna(row[1]) else row[1]
                        purchase_price = None if pd.isna(row[2]) else row[2]
                        purchase_date = "" if pd.isna(row[3]) else str(row[3]).strip()

                        # Only include rows with meaningful data
                        if ticker and purchase_price is not None and purchase_date:
                            user_cost_basis.append({
                                "ticker": ticker,
                                "shares": shares,
                                "purchase_price": purchase_price,
                                "purchase_date": purchase_date,
                            })

                logger.info(f"Parsed {len(user_cost_basis)} valid cost basis entries: {user_cost_basis}")

                report = create_tax_analysis(
                    holdings=holdings,
                    filing_status=filing_status,
                    annual_income=annual_income,
                    cost_basis_method=cost_basis_method,
                    user_cost_basis=user_cost_basis if user_cost_basis else None,
                )
                return format_tax_analysis_output(report)
            except Exception as e:
                logger.error(f"Tax calculation error: {e}", exc_info=True)
                return f"""# Tax Impact Analysis

**Error**: {str(e)}

Please try again with different parameters.
"""

        async def save_portfolio_input_text(user_id: str, portfolio_text: str):
            """Save portfolio input text for quick reload.

            Automatically keeps only last 3 entries per user via database trigger.
            """
            try:
                await db.save_portfolio_input(user_id, portfolio_text)
            except Exception as e:
                logger.error(f"Failed to save portfolio input: {e}")

        async def get_past_portfolios_for_dropdown(user_id: str):
            """Get last 3 portfolio inputs formatted for dropdown."""
            try:
                portfolios = await db.get_portfolio_inputs(user_id, limit=3)

                # Format for dropdown: (display_text, index)
                choices = []
                for i, portfolio in enumerate(portfolios):
                    # Generate preview from first few lines of description
                    lines = [line.strip() for line in portfolio['description'].split('\n') if line.strip()][:3]
                    tickers = []
                    for line in lines:
                        parts = line.split()
                        if parts:
                            tickers.append(parts[0])

                    preview = ', '.join(tickers)
                    total_lines = len([l for l in portfolio['description'].split('\n') if l.strip()])
                    if total_lines > 3:
                        preview += f' +{total_lines - 3} more'

                    choices.append((preview, i))

                return choices
            except Exception as e:
                logger.error(f"Failed to load past portfolios: {e}")
                return []

        async def load_portfolio_text(user_id: str, index: int):
            """Load portfolio text by index (0 = most recent)."""
            try:
                portfolios = await db.get_portfolio_inputs(user_id, limit=3)

                if 0 <= index < len(portfolios):
                    return portfolios[index].get('description', '')
                return ""
            except Exception as e:
                logger.error(f"Failed to load portfolio text: {e}")
                return ""

        async def handle_analysis(session_state, portfolio_text, roast_mode, persona, request: gr.Request, progress=gr.Progress()):
            # Check authentication
            if not check_authentication(session_state):
                yield {
                    input_page: gr.update(visible=False),
                    loading_page: gr.update(visible=False),
                    results_page: gr.update(visible=False),
                    loading_message: "❌ Please sign in to analyse your portfolio",
                    analysis_output: "",
                    performance_metrics_output: "",
                    allocation_plot: None,
                    risk_plot: None,
                    performance_plot: None,
                    correlation_plot: None,
                    optimization_plot: None,
                    load_past_portfolio_dropdown: gr.skip(),
                    export_pdf_btn: gr.skip(),
                    export_csv_btn: gr.skip()
                }
                return

            # Enforce rate limiting
            if rate_limit_middleware:
                try:
                    rate_limit_middleware.enforce(request, session_state=session_state)
                except Exception as e:
                    logger.warning(f"Rate limit exceeded: {e}")
                    yield {
                        input_page: gr.update(visible=False),
                        loading_page: gr.update(visible=False),
                        results_page: gr.update(visible=False),
                        loading_message: f"❌ {str(e)}",
                        analysis_output: "",
                        performance_metrics_output: "",
                        allocation_plot: None,
                        risk_plot: None,
                        performance_plot: None,
                        correlation_plot: None,
                        optimization_plot: None,
                        load_past_portfolio_dropdown: gr.skip(),
                        export_pdf_btn: gr.skip(),
                        export_csv_btn: gr.skip()
                    }
                    return

            # Auto-save portfolio input for quick reload (keep last 3)
            session = UserSession.from_dict(session_state)
            dropdown_choices = []
            if session and session.user_id and portfolio_text.strip():
                await save_portfolio_input_text(session.user_id, portfolio_text)
                dropdown_choices = await get_past_portfolios_for_dropdown(session.user_id)

            # Show loading page immediately
            yield {
                input_page: gr.update(visible=False),
                loading_page: gr.update(visible=True),
                results_page: gr.update(visible=False),
                loading_message: random.choice(LOADING_MESSAGES),
                analysis_output: "",
                performance_metrics_output: "",
                allocation_plot: None,
                risk_plot: None,
                performance_plot: None,
                correlation_plot: None,
                optimization_plot: None,
                load_past_portfolio_dropdown: gr.update(choices=dropdown_choices) if dropdown_choices else gr.skip(),
                export_pdf_btn: gr.skip(),
                export_csv_btn: gr.skip()
            }

            # Run analysis with progress updates
            page, analysis, perf_metrics, alloc, risk, perf, corr, opt, audio_btn = await run_analysis_with_ui_update(
                session_state, portfolio_text, roast_mode, persona, progress
            )

            # Show results or return to input
            if page == "results":
                global LAST_EXPORT_PDF_PATH, LAST_EXPORT_CSV_PATH
                yield {
                    input_page: gr.update(visible=False),
                    loading_page: gr.update(visible=False),
                    results_page: gr.update(visible=True),
                    loading_message: "Analysis complete!",
                    analysis_output: analysis,
                    performance_metrics_output: perf_metrics,
                    allocation_plot: alloc,
                    risk_plot: risk,
                    performance_plot: perf,
                    correlation_plot: corr,
                    optimization_plot: opt,
                    analysis_audio_btn: audio_btn,
                    load_past_portfolio_dropdown: gr.update(choices=dropdown_choices) if dropdown_choices else gr.skip(),
                    export_pdf_btn: LAST_EXPORT_PDF_PATH,
                    export_csv_btn: LAST_EXPORT_CSV_PATH
                }
            else:
                yield {
                    input_page: gr.update(visible=True),
                    loading_page: gr.update(visible=False),
                    results_page: gr.update(visible=False),
                    loading_message: "",
                    analysis_output: analysis,
                    performance_metrics_output: "",
                    allocation_plot: None,
                    risk_plot: None,
                    performance_plot: None,
                    correlation_plot: None,
                    optimization_plot: None,
                    analysis_audio_btn: audio_btn,
                    load_past_portfolio_dropdown: gr.skip(),
                    export_pdf_btn: gr.skip(),
                    export_csv_btn: gr.skip()
                }

        # Wire up live preview on input change
        portfolio_input.change(
            update_live_preview,
            inputs=[portfolio_input],
            outputs=[preview_output]
        )

        # Wire up refresh prices button
        refresh_prices_btn.click(
            fetch_and_update_preview,
            inputs=[portfolio_input],
            outputs=[preview_output]
        )

        # Wire up past portfolio dropdown to load selected portfolio
        async def handle_load_past_portfolio(index, session):
            """Load selected past portfolio into input field."""
            if index is None:
                return gr.skip()

            session_obj = UserSession.from_dict(session)
            if not session_obj or not session_obj.user_id:
                return ""

            portfolio_text = await load_portfolio_text(session_obj.user_id, index)
            return portfolio_text

        load_past_portfolio_dropdown.change(
            handle_load_past_portfolio,
            inputs=[load_past_portfolio_dropdown, session_state],
            outputs=[portfolio_input]
        )

        analyse_btn.click(
            handle_analysis,
            inputs=[session_state, portfolio_input, roast_mode_toggle, persona_dropdown],
            outputs=[
                input_page,
                loading_page,
                results_page,
                loading_message,
                analysis_output,
                performance_metrics_output,
                allocation_plot,
                risk_plot,
                performance_plot,
                correlation_plot,
                optimization_plot,
                load_past_portfolio_dropdown,
                export_pdf_btn,
                export_csv_btn,
                analysis_audio_btn  # Audio button
            ],
            show_progress="full"
        )

        # Export buttons - download directly (DownloadButton triggers browser download automatically)
        export_pdf_btn.click(
            export_current_analysis_pdf,
            outputs=export_pdf_btn
        )

        export_csv_btn.click(
            export_current_analysis_csv,
            outputs=export_csv_btn
        )

        # Back button from input page to task page
        input_back_btn.click(
            show_task_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        # Auto-load history when History tab is selected
        def load_history_if_selected(evt: gr.SelectData, session):
            """Load history only when History tab is selected."""
            if evt.index == 4:  # History tab is index 4 (0-indexed: Analysis, Dashboard, Tax, Stress, History)
                return sync_load_history(session)
            return gr.skip(), gr.skip()

        results_tabs.select(
            load_history_if_selected,
            inputs=[session_state],
            outputs=[history_table_results, history_details_output_results]
        )

        back_to_input_btn.click(
            show_input_page,
            outputs=[task_page, input_page, results_page, history_page]
        )

        # History table selection handlers
        history_table.select(
            view_historical_analysis,
            outputs=[history_details_output]
        )

        history_table_results.select(
            view_historical_analysis,
            outputs=[history_details_output_results]
        )

        # History search and filter handlers (standalone history page)
        history_search.change(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search, history_date_filter, history_current_page],
            outputs=[history_table, history_page_info],
            show_api=False
        ).then(
            lambda: 1,  # Reset to page 1 on search
            outputs=[history_current_page],
            show_api=False
        )

        history_date_filter.change(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search, history_date_filter, history_current_page],
            outputs=[history_table, history_page_info],
            show_api=False
        ).then(
            lambda: 1,  # Reset to page 1 on filter change
            outputs=[history_current_page],
            show_api=False
        )

        history_refresh_btn.click(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search, history_date_filter, history_current_page],
            outputs=[history_table, history_page_info],
            show_api=False
        )

        # Pagination handlers (standalone)
        history_prev_btn.click(
            lambda page: max(1, page - 1),
            inputs=[history_current_page],
            outputs=[history_current_page],
            show_api=False
        ).then(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search, history_date_filter, history_current_page],
            outputs=[history_table, history_page_info],
            show_api=False
        )

        history_next_btn.click(
            lambda page: page + 1,
            inputs=[history_current_page],
            outputs=[history_current_page],
            show_api=False
        ).then(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search, history_date_filter, history_current_page],
            outputs=[history_table, history_page_info],
            show_api=False
        )

        # History search and filter handlers (results page tab)
        history_search_results.change(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search_results, history_date_filter_results, history_current_page_results],
            outputs=[history_table_results, history_page_info_results],
            show_api=False
        ).then(
            lambda: 1,  # Reset to page 1 on search
            outputs=[history_current_page_results],
            show_api=False
        )

        history_date_filter_results.change(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search_results, history_date_filter_results, history_current_page_results],
            outputs=[history_table_results, history_page_info_results],
            show_api=False
        ).then(
            lambda: 1,  # Reset to page 1 on filter change
            outputs=[history_current_page_results],
            show_api=False
        )

        history_refresh_btn_results.click(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search_results, history_date_filter_results, history_current_page_results],
            outputs=[history_table_results, history_page_info_results],
            show_api=False
        )

        # Pagination handlers (results page)
        history_prev_btn_results.click(
            lambda page: max(1, page - 1),
            inputs=[history_current_page_results],
            outputs=[history_current_page_results],
            show_api=False
        ).then(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search_results, history_date_filter_results, history_current_page_results],
            outputs=[history_table_results, history_page_info_results],
            show_api=False
        )

        history_next_btn_results.click(
            lambda page: page + 1,
            inputs=[history_current_page_results],
            outputs=[history_current_page_results],
            show_api=False
        ).then(
            lambda sess, query, date_filter, page: sync_filter_history(sess, query, date_filter, page),
            inputs=[session_state, history_search_results, history_date_filter_results, history_current_page_results],
            outputs=[history_table_results, history_page_info_results],
            show_api=False
        )

        # Tax load holdings button
        tax_load_holdings_btn.click(
            load_tax_holdings,
            inputs=[],
            outputs=[tax_cost_basis_input]
        )

        # Tax calculator button (Enhancement #5)
        tax_calculate_btn.click(
            calculate_tax_impact,
            inputs=[tax_filing_status, tax_annual_income, tax_cost_basis_method, tax_cost_basis_input],
            outputs=[tax_analysis_output]
        )

        # Wire up stress test button
        stress_test_btn.click(
            run_stress_test,
            inputs=[stress_scenario_dropdown, stress_n_sims, stress_horizon],
            outputs=[
                stress_summary,
                stress_dashboard_plot,
                stress_mc_plot,
                stress_scenario_plot,
                stress_drawdown_plot
            ]
        )

        # Authentication event handlers
        async def handle_login(email: str, password: str, current_session: Dict):
            """Handle user login."""
            if not email or not password:
                return current_session, "Please enter email and password", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()

            success, message, session = await auth.login(email, password)

            if success and session:
                # Update session state
                session_dict = session.to_dict()
                # Get past portfolio dropdown choices
                dropdown_choices = await get_past_portfolios_for_dropdown(session.user_id)
                return (
                    session_dict,
                    f"βœ… {message}",
                    gr.update(visible=False),  # Hide login form
                    gr.update(visible=True),   # Show task selection
                    gr.update(value=f"πŸ‘€ {session.username} | {session.email}"),  # Update user info
                    gr.update(choices=dropdown_choices),  # Update past portfolio dropdown
                    gr.update(visible=True),  # Show logout button
                    gr.update(visible=True)   # Show sidebar
                )
            else:
                # On failure, don't show logout_btn or sidebar
                return current_session, f"❌ {message}", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()

        async def handle_signup(email: str, password: str, confirm_password: str, username: str, current_session: Dict):
            """Handle user signup."""
            # Validation
            if not email or not password:
                return current_session, "❌ Please enter email and password"

            if password != confirm_password:
                return current_session, "❌ Passwords do not match"

            # NIST SP 800-63B-4: Minimum 15 characters for single-factor auth
            # No composition rules (uppercase, numbers, symbols) required
            if len(password) < 15:
                return current_session, "❌ Password must be at least 15 characters (NIST 2024 requirement)"

            success, message, session = await auth.signup(email, password, username)

            if success:
                if session:
                    # Auto-login after signup (if email confirmation disabled)
                    return session.to_dict(), f"βœ… {message}"
                else:
                    return current_session, f"βœ… {message}"
            else:
                return current_session, f"❌ {message}"

        async def handle_logout(current_session: Dict):
            """Handle user logout and reset all UI components.

            Security: Clears all global state and user-specific cache to prevent
            data leakage between user sessions.
            """
            global LAST_ANALYSIS_STATE, HISTORY_RECORDS, LAST_STRESS_TEST

            session = UserSession.from_dict(current_session)

            # Extract user ID before clearing session (for cache cleanup)
            user_id = session.user_id if session else None

            # 1. Clear backend authentication
            success, message = await auth.logout(session)

            # 2. Clear global state variables (CRITICAL for data security)
            LAST_ANALYSIS_STATE = None
            HISTORY_RECORDS = []
            LAST_STRESS_TEST = None

            # 3. Clear user-specific cache entries
            if user_id:
                try:
                    from backend.caching.factory import cache_manager
                    # Clear user-specific data from cache
                    cache_manager.invalidation.invalidate_by_event("user_update", user_id)
                    logger.info(f"Cleared cache for user {user_id}")
                except Exception as e:
                    logger.error(f"Failed to clear user cache on logout: {e}")

            # 4. Clear session and reset ALL UI components to initial state
            return (
                {},  # Clear session state
                f"βœ… {message}",  # Login message
                gr.update(visible=True),   # Show login container
                gr.update(visible=False),  # Hide task page
                gr.update(visible=False),  # Hide input page
                gr.update(value="Not logged in"),  # Clear user info
                gr.update(visible=False),  # Hide logout button
                gr.update(visible=False),  # Hide sidebar
                gr.update(visible=False),  # Hide results page
                gr.update(visible=False),  # Hide loading page
                gr.update(visible=False),  # Hide history page
                # Clear all analysis outputs
                gr.update(value=""),  # analysis_output
                gr.update(value=None),  # allocation_plot
                gr.update(value=None),  # risk_plot
                gr.update(value=None),  # performance_plot
                gr.update(value=None),  # correlation_plot
                gr.update(value=None),  # optimization_plot
                # Clear history
                gr.update(value=[]),  # history_table
                # Clear password reset modals
                gr.update(visible=False),  # password_reset_modal
                gr.update(visible=False),  # password_update_modal
                # Clear user input data (SECURITY: prevent data leakage)
                gr.update(value=""),  # portfolio_input
                gr.update(choices=[], value=None),  # load_past_portfolio_dropdown
                # Clear build page
                gr.update(visible=False),  # Hide build_page
                gr.update(visible=False),  # Hide build_results_container
                gr.update(value=[]),  # Clear build_agent_chat
                gr.update(value=[]),  # Clear build_goals
                gr.update(value=5),  # Reset build_risk_tolerance to middle value
                gr.update(value=""),  # Clear build_constraints
                gr.update(value=""),  # Clear build_status
                # Clear compare page
                gr.update(visible=False),  # Hide compare_page
                gr.update(visible=False),  # Hide compare_results_container
                gr.update(value=[]),  # Clear compare_debate_chat
                gr.update(value=""),  # Clear compare_portfolio_input
                gr.update(value=""),  # Clear compare_status
                gr.update(value=""),  # Clear compare_bull_case
                gr.update(value=0),  # Reset compare_bull_confidence
                gr.update(value=""),  # Clear compare_bear_case
                gr.update(value=0),  # Reset compare_bear_confidence
                gr.update(value=""),  # Clear compare_consensus
                gr.update(value=""),  # Clear compare_stance
                gr.update(value=[]),  # Clear compare_debate_transcript
                # Clear test page
                gr.update(visible=False),  # Hide test_page
                gr.update(visible=False),  # Hide test_results_container
                gr.update(value=""),  # Clear test_portfolio_input
                gr.update(value=""),  # Clear test_changes_input
                gr.update(value=100000),  # Reset test_portfolio_value to default
                gr.update(value=""),  # Clear test_status
                gr.update(value=[]),  # Clear test_current_metrics
                gr.update(value=[]),  # Clear test_simulated_metrics
                gr.update(value=[]),  # Clear test_impact_summary
                gr.update(value=[]),  # Clear test_stress_comparison
                gr.update(value=""),  # Clear test_assessment
                gr.update(value=""),  # Clear test_recommendations
            )

        def sync_login(email: str, password: str, current_session: Dict):
            """Synchronous wrapper for login."""
            return asyncio.run(handle_login(email, password, current_session))

        def sync_signup(email: str, password: str, confirm_password: str, username: str, current_session: Dict):
            """Synchronous wrapper for signup."""
            return asyncio.run(handle_signup(email, password, confirm_password, username, current_session))

        def sync_logout(current_session: Dict):
            """Synchronous wrapper for logout."""
            return asyncio.run(handle_logout(current_session))

        async def handle_password_reset(email: str):
            """Handle password reset request."""
            if not email:
                return "", "❌ Please enter your email address"

            success, message = await auth.request_password_reset(email)

            # Simple success message
            if success:
                return "", f"{message}\n\nCheck your email and click the reset link to set your new password."

            return "", message

        def sync_password_reset(email: str):
            """Synchronous wrapper for password reset."""
            return asyncio.run(handle_password_reset(email))

        async def handle_password_update(password: str, confirm: str, email: str, token_hash: str):
            """Handle password update after reset with recovery token_hash."""
            if not email:
                return "❌ Please enter your email address"

            if not password or not confirm:
                return "❌ Please enter both password fields"

            if password != confirm:
                return "❌ Passwords do not match"

            # NIST SP 800-63B-4: Minimum 15 characters for single-factor auth
            if len(password) < 15:
                return "❌ Password must be at least 15 characters (NIST 2024 requirement)"

            success, message = await auth.update_password(password, email, token_hash)
            return message

        def sync_password_update(password: str, confirm: str, email: str, token_hash: str):
            """Synchronous wrapper for password update."""
            return asyncio.run(handle_password_update(password, confirm, email, token_hash))

        # Connect authentication handlers
        login_btn.click(
            sync_login,
            inputs=[login_email, login_password, session_state],
            outputs=[session_state, login_message, login_container, task_page, user_info, load_past_portfolio_dropdown, logout_btn, sidebar]
        )

        signup_btn.click(
            sync_signup,
            inputs=[signup_email, signup_password, signup_confirm, signup_username, session_state],
            outputs=[session_state, signup_message]
        )

        # Real-time email validation
        signup_email.change(
            validate_email_format,
            inputs=[signup_email],
            outputs=[signup_email_validation]
        )

        # Real-time password strength meter
        signup_password.change(
            check_password_strength,
            inputs=[signup_password],
            outputs=[signup_password_strength]
        )

        # Real-time password match validation
        signup_confirm.change(
            validate_password_match,
            inputs=[signup_password, signup_confirm],
            outputs=[signup_password_match]
        )

        # Password reset handlers
        forgot_password_btn.click(
            lambda: (gr.update(visible=False), gr.update(visible=True)),
            outputs=[login_container, password_reset_modal],
            show_api=False
        )

        reset_cancel_btn.click(
            lambda: (gr.update(visible=True), gr.update(visible=False), ""),
            outputs=[login_container, password_reset_modal, reset_message],
            show_api=False
        )

        update_cancel_btn.click(
            lambda: (gr.update(visible=True), gr.update(visible=False), ""),
            outputs=[login_container, password_update_modal, update_password_message],
            show_api=False
        )

        reset_submit_btn.click(
            sync_password_reset,
            inputs=[reset_email],
            outputs=[reset_email, reset_message]
        )

        # Show password update modal when recovery token_hash is detected
        recovery_token_hash.change(
            fn=lambda token: (
                gr.update(visible=False) if token else gr.update(visible=True),
                gr.update(visible=True) if token else gr.update(visible=False)
            ),
            inputs=[recovery_token_hash],
            outputs=[login_container, password_update_modal],
            show_api=False
        )

        # Password update handler (separate modal after email link click)
        update_password_btn.click(
            sync_password_update,
            inputs=[new_password, confirm_new_password, recovery_email, recovery_token_hash],
            outputs=[update_password_message]
        ).then(
            # On success, hide modal and show login form
            lambda msg: (
                gr.update(visible=False) if "βœ…" in msg else gr.update(visible=True),
                gr.update(visible=True) if "βœ…" in msg else gr.update(visible=False)
            ),
            inputs=[update_password_message],
            outputs=[password_update_modal, login_container],
            show_api=False
        )

        def handle_demo_mode(current_session: Dict):
            """Handle demo mode activation (anonymous with rate limiting)."""
            # Create a demo session (not authenticated)
            demo_session = {
                "authenticated": False,
                "is_demo": True,
                "user_id": None,  # No user ID for anonymous
            }

            return (
                demo_session,  # session_state
                "",  # demo_message (cleared)
                gr.update(visible=False),  # Hide login container
                gr.update(visible=True),  # Show task selection
                "Demo Mode - 1 free analysis per day",  # user_info
                gr.update(visible=False),  # Hide logout button for demo
                gr.update(visible=True)  # Show sidebar
            )

        demo_btn.click(
            handle_demo_mode,
            inputs=[session_state],
            outputs=[session_state, demo_message, login_container, task_page, user_info, logout_btn, sidebar]
        )

        logout_btn.click(
            sync_logout,
            inputs=[session_state],
            outputs=[
                session_state, login_message, login_container, task_page, input_page, user_info,
                logout_btn, sidebar, results_page, loading_page, history_page,
                analysis_output, allocation_plot, risk_plot, performance_plot,
                correlation_plot, optimization_plot, history_table,
                password_reset_modal, password_update_modal,
                portfolio_input, load_past_portfolio_dropdown,
                # Build page components
                build_page, build_results_container, build_agent_chat,
                build_goals, build_risk_tolerance, build_constraints, build_status,
                # Compare page components
                compare_page, compare_results_container, compare_debate_chat, compare_portfolio_input, compare_status,
                compare_bull_case, compare_bull_confidence, compare_bear_case, compare_bear_confidence,
                compare_consensus, compare_stance, compare_debate_transcript,
                # Test page components
                test_page, test_results_container, test_portfolio_input, test_changes_input,
                test_portfolio_value, test_status, test_current_metrics, test_simulated_metrics,
                test_impact_summary, test_stress_comparison, test_assessment, test_recommendations
            ]
        )

        # Navigation event handlers
        nav_new_analysis.click(
            show_task_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        # Task card event handlers
        task_analyse_btn.click(
            show_input_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        task_build_btn.click(
            show_build_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        task_compare_btn.click(
            show_compare_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        task_test_btn.click(
            show_test_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        # Build page event handlers
        build_back_btn.click(
            show_task_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        build_submit_btn.click(
            handle_build_portfolio,
            inputs=[build_goals, build_risk_tolerance, build_constraints, session_state],
            outputs=[
                build_agent_chat,
                build_results_container,
                build_status,
                build_audio_btn  # Audio button
            ]
        )

        build_regenerate_btn.click(
            handle_build_portfolio,
            inputs=[build_goals, build_risk_tolerance, build_constraints, session_state],
            outputs=[
                build_agent_chat,
                build_results_container,
                build_status,
                build_audio_btn
            ]
        )

        # Compare page event handlers
        compare_back_btn.click(
            show_task_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        compare_submit_btn.click(
            handle_compare_portfolio,
            inputs=[compare_portfolio_input, session_state],
            outputs=[
                compare_debate_chat,
                compare_results_container,
                compare_status,
                compare_bull_case,
                compare_bull_confidence,
                compare_bear_case,
                compare_bear_confidence,
                compare_consensus,
                compare_stance,
                compare_debate_transcript,
                compare_audio_btn  # Audio button
            ]
        )

        # Test page event handlers
        test_back_btn.click(
            show_task_page,
            outputs=[task_page, input_page, results_page, history_page, build_page, compare_page, test_page]
        )

        test_submit_btn.click(
            sync_handle_test_changes,
            inputs=[test_portfolio_input, test_changes_input, test_portfolio_value, session_state],
            outputs=[
                test_results_container,
                test_status,
                test_current_metrics,
                test_simulated_metrics,
                test_impact_summary,
                test_stress_comparison,
                test_assessment,
                test_recommendations
            ]
        )

        nav_view_history.click(
            show_history_page,
            outputs=[task_page, input_page, results_page, history_page]
        ).then(
            sync_load_history,
            inputs=[session_state],
            outputs=[history_table, history_details_output]
        )

        # Sidebar sign out button (mirrors main logout button)
        nav_signout_btn.click(
            sync_logout,
            inputs=[session_state],
            outputs=[
                session_state, login_message, login_container, task_page, input_page, user_info,
                logout_btn, sidebar, results_page, loading_page, history_page,
                analysis_output, allocation_plot, risk_plot, performance_plot,
                correlation_plot, optimization_plot, history_table,
                password_reset_modal, password_update_modal,
                portfolio_input, load_past_portfolio_dropdown,
                # Build page components
                build_page, build_results_container, build_agent_chat,
                build_goals, build_risk_tolerance, build_constraints, build_status,
                # Compare page components
                compare_page, compare_results_container, compare_debate_chat, compare_portfolio_input, compare_status,
                compare_bull_case, compare_bull_confidence, compare_bear_case, compare_bear_confidence,
                compare_consensus, compare_stance, compare_debate_transcript,
                # Test page components
                test_page, test_results_container, test_portfolio_input, test_changes_input,
                test_portfolio_value, test_status, test_current_metrics, test_simulated_metrics,
                test_impact_summary, test_stress_comparison, test_assessment, test_recommendations
            ]
        )

        # ============================================================
        # AUDIO BUTTON EVENT HANDLERS
        # ============================================================
        # Use event chaining to show loading state during audio generation:
        # 1. Disable button and change text to "Generating..."
        # 2. Run async audio generation with progress indicator
        # 3. Restore button to original state

        # Analysis audio button
        analysis_audio_btn.click(
            fn=lambda: gr.update(value="Generating...", interactive=False),
            outputs=analysis_audio_btn
        ).then(
            fn=generate_analysis_audio,
            inputs=[],
            outputs=[analysis_audio_player, analysis_audio_btn],
            show_progress="minimal"
        ).then(
            fn=lambda: gr.update(value="πŸ”Š Listen to Analysis", interactive=True),
            outputs=analysis_audio_btn
        )

        # Build portfolio audio button
        build_audio_btn.click(
            fn=lambda: gr.update(value="Generating...", interactive=False),
            outputs=build_audio_btn
        ).then(
            fn=generate_build_audio,
            inputs=[],
            outputs=[build_audio_player, build_audio_btn],
            show_progress="minimal"
        ).then(
            fn=lambda: gr.update(value="πŸ”Š Listen to Portfolio", interactive=True),
            outputs=build_audio_btn
        )

        # Compare/debate audio button
        compare_audio_btn.click(
            fn=lambda: gr.update(value="Generating...", interactive=False),
            outputs=compare_audio_btn
        ).then(
            fn=generate_debate_audio,
            inputs=[],
            outputs=[compare_audio_player, compare_audio_btn],
            show_progress="minimal"
        ).then(
            fn=lambda: gr.update(value="🎭 Listen to Debate", interactive=True),
            outputs=compare_audio_btn
        )

        # MCP Tool Registrations (API/MCP only - no UI components)
        # Market Data Tools
        gr.api(mcp_tools.market_get_quote, api_name="market_get_quote")
        gr.api(mcp_tools.market_get_historical_data, api_name="market_get_historical_data")
        gr.api(mcp_tools.market_get_fundamentals, api_name="market_get_fundamentals")
        gr.api(mcp_tools.market_get_company_profile, api_name="market_get_company_profile")
        gr.api(mcp_tools.market_get_income_statement, api_name="market_get_income_statement")
        gr.api(mcp_tools.market_get_balance_sheet, api_name="market_get_balance_sheet")
        gr.api(mcp_tools.market_get_cash_flow_statement, api_name="market_get_cash_flow_statement")
        gr.api(mcp_tools.market_get_financial_ratios, api_name="market_get_financial_ratios")
        gr.api(mcp_tools.market_get_key_metrics, api_name="market_get_key_metrics")
        gr.api(mcp_tools.market_get_economic_series, api_name="market_get_economic_series")

        # Technical Analysis Tools
        gr.api(mcp_tools.technical_get_indicators, api_name="technical_get_indicators")
        gr.api(mcp_tools.technical_extract_features, api_name="technical_extract_features")
        gr.api(mcp_tools.technical_normalise_features, api_name="technical_normalise_features")
        gr.api(mcp_tools.technical_select_features, api_name="technical_select_features")
        gr.api(mcp_tools.technical_compute_feature_vector, api_name="technical_compute_feature_vector")

        # Portfolio Optimisation Tools
        gr.api(mcp_tools.portfolio_optimize_hrp, api_name="portfolio_optimize_hrp")
        gr.api(mcp_tools.portfolio_optimize_black_litterman, api_name="portfolio_optimize_black_litterman")
        gr.api(mcp_tools.portfolio_optimize_mean_variance, api_name="portfolio_optimize_mean_variance")

        # Risk Analysis Tools
        gr.api(mcp_tools.risk_analyze, api_name="risk_analyze")
        gr.api(mcp_tools.risk_forecast_volatility_garch, api_name="risk_forecast_volatility_garch")

        # ML Forecasting Tools
        gr.api(mcp_tools.ml_forecast_ensemble, api_name="ml_forecast_ensemble")

        # Sentiment Analysis Tools
        gr.api(mcp_tools.sentiment_get_news, api_name="sentiment_get_news")

    return demo


if __name__ == "__main__":
    demo = create_interface()
    # Suppress console output on HF Spaces for cleaner logs
    is_hf_space = os.environ.get("SPACE_ID") is not None
    demo.queue().launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        quiet=is_hf_space,  # Suppress verbose output on HF Spaces
        mcp_server=True,  # Native MCP server at /gradio_api/mcp/
        allowed_paths=["/tmp"]  # Allow serving export files from temp directory
    )