Spaces:
Sleeping

File size: 177,784 Bytes
5b5a20d
0c09885
 
 
 
5b5a20d
 
893ae76
 
5b5a20d
 
02a1c61
5b5a20d
02a1c61
893ae76
 
5b5a20d
 
 
 
 
 
a9de05b
0c09885
a9de05b
 
 
 
0c09885
 
449fffb
0c09885
 
 
 
 
 
 
449fffb
5b5a20d
0c09885
 
 
5b5a20d
 
d176097
0c09885
 
 
 
d176097
7070b94
2a95ee9
0c09885
 
2a95ee9
0c09885
 
2a95ee9
5b5a20d
 
014b03e
0c09885
795a91a
893ae76
 
 
0c09885
014b03e
 
0c09885
014b03e
 
 
 
 
 
0c09885
014b03e
0c09885
 
 
 
 
 
014b03e
 
 
 
5b5a20d
795a91a
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795a91a
 
 
a873f76
795a91a
 
0c09885
 
 
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
893ae76
 
 
 
d176097
 
 
 
de4e37c
 
 
 
 
 
 
 
 
 
 
0c09885
 
 
 
 
893ae76
0c09885
 
a873f76
0c09885
a873f76
0c09885
893ae76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a873f76
893ae76
0c09885
 
 
893ae76
5b5a20d
893ae76
6dc4dd3
 
0c09885
6dc4dd3
0c09885
 
 
6dc4dd3
 
 
0c09885
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
 
6dc4dd3
 
 
 
 
 
 
 
0c09885
6dc4dd3
0c09885
 
 
6dc4dd3
 
0c09885
6dc4dd3
0c09885
6dc4dd3
0c09885
5b5a20d
0c09885
a9de05b
 
0c09885
 
a9de05b
 
0c09885
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
a9de05b
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
 
0c09885
 
 
 
5b5a20d
0c09885
 
 
 
 
 
a9de05b
893ae76
 
a873f76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
a873f76
 
c045122
 
a873f76
c045122
0c09885
c045122
a873f76
c045122
 
a873f76
c045122
a873f76
 
 
 
c045122
 
 
a873f76
 
c045122
 
 
a873f76
 
 
c045122
a873f76
c045122
 
 
893ae76
0c09885
 
 
 
02a1c61
0c09885
02a1c61
 
 
0c09885
 
 
 
 
 
 
 
 
02a1c61
 
0c09885
02a1c61
0c09885
02a1c61
0c09885
02a1c61
0c09885
 
02a1c61
0c09885
 
02a1c61
0c09885
 
02a1c61
0c09885
 
 
 
 
 
 
 
 
 
 
02a1c61
0c09885
 
 
02a1c61
0c09885
 
5b5a20d
0c09885
 
 
 
 
 
 
5b5a20d
 
0c09885
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
5b5a20d
0c09885
 
 
 
5b5a20d
34890bc
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34890bc
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a1c61
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34890bc
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
34890bc
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34890bc
a9de05b
0c09885
 
 
 
 
a9de05b
0c09885
 
 
34890bc
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
a9de05b
0c09885
 
 
 
a9de05b
0c09885
 
 
 
 
02a1c61
0c09885
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02a1c61
0c09885
02a1c61
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
02a1c61
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
02a1c61
0c09885
e605ae7
 
0c09885
 
 
 
a9de05b
0c09885
 
 
e605ae7
0c09885
 
 
 
 
 
 
 
 
 
 
e605ae7
0c09885
 
 
a9de05b
0c09885
 
 
 
e605ae7
 
0c09885
 
 
 
 
 
e605ae7
0c09885
e605ae7
0c09885
 
 
 
 
 
 
 
 
 
e605ae7
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e605ae7
0c09885
 
 
 
 
 
e605ae7
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e605ae7
0c09885
 
 
 
 
 
e605ae7
 
0c09885
 
a873f76
0c09885
 
a873f76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
a873f76
 
0c09885
 
 
 
 
 
 
 
a873f76
 
 
 
 
0c09885
 
 
 
 
 
 
 
a873f76
 
 
0c09885
 
 
 
 
 
 
5b5a20d
0c09885
 
 
 
 
 
 
 
 
 
 
77b1d4b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
 
77b1d4b
 
 
0c09885
 
 
5b5a20d
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
0c09885
 
 
 
 
5b5a20d
 
0c09885
a9de05b
0c09885
 
 
 
 
 
 
a9de05b
893ae76
5b5a20d
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7070b94
 
 
 
0c09885
 
 
 
7070b94
0c09885
 
 
7070b94
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
893ae76
a873f76
0c09885
a873f76
 
0c09885
a873f76
 
0c09885
 
5b5a20d
 
 
d176097
 
 
 
a873f76
d176097
a873f76
5b5a20d
 
 
 
0c09885
d176097
0c09885
d176097
5b5a20d
 
0c09885
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
0c09885
5b5a20d
 
0c09885
 
 
 
 
5b5a20d
a9de05b
 
0c09885
a9de05b
 
 
 
 
0c09885
a9de05b
 
 
 
 
0c09885
de4e37c
 
 
 
 
 
0c09885
 
 
 
 
6dc4dd3
 
 
a9de05b
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
a9de05b
5b5a20d
da4b58e
0c09885
 
 
da4b58e
0c09885
 
a9de05b
0c09885
 
 
a9de05b
 
0c09885
 
 
a9de05b
0c09885
a9de05b
0c09885
 
 
 
 
a9de05b
da4b58e
0c09885
a9de05b
 
0c09885
 
 
 
 
 
201f02a
 
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
201f02a
 
0c09885
 
 
 
 
 
 
 
 
201f02a
0c09885
201f02a
 
0c09885
 
 
 
201f02a
0c09885
 
 
 
 
 
 
 
 
 
 
da4b58e
 
 
e612a97
 
 
 
 
da4b58e
e612a97
 
 
 
 
 
da4b58e
e612a97
 
 
 
 
 
 
0c09885
201f02a
 
e612a97
 
 
0c09885
e612a97
 
 
0c09885
e612a97
 
 
 
da4b58e
e612a97
 
201f02a
0c09885
 
e612a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b58e
 
0c09885
 
 
 
 
 
 
 
 
201f02a
77b1d4b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
e612a97
 
 
 
 
0c09885
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b58e
0c09885
da4b58e
de4e37c
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4b58e
 
de4e37c
 
 
 
 
 
0c09885
de4e37c
0c09885
 
de4e37c
 
 
 
5b5a20d
0c09885
de4e37c
02a1c61
de4e37c
a873f76
0c09885
de4e37c
0c09885
 
de4e37c
 
 
 
a873f76
 
de4e37c
a9de05b
5b5a20d
0c09885
5b5a20d
0c09885
5b5a20d
0c09885
 
a9de05b
0c09885
 
de4e37c
5b5a20d
0c09885
 
de4e37c
 
0c09885
 
de4e37c
0c09885
5b5a20d
de4e37c
0c09885
 
5b5a20d
 
0c09885
de4e37c
 
 
5b5a20d
 
de4e37c
f5ce139
de4e37c
f5ce139
 
de4e37c
 
f5ce139
 
de4e37c
 
f5ce139
de4e37c
f5ce139
 
 
 
 
 
 
 
 
de4e37c
 
 
 
f5ce139
 
 
 
 
de4e37c
f5ce139
 
 
de4e37c
 
 
 
 
 
 
 
 
 
7070b94
de4e37c
 
 
 
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
 
0c09885
 
 
 
 
 
 
 
de4e37c
 
0c09885
 
 
 
de4e37c
 
0c09885
de4e37c
0c09885
 
de4e37c
 
0c09885
02a1c61
0c09885
02a1c61
0c09885
5b5a20d
de4e37c
0c09885
de4e37c
0c09885
 
 
 
de4e37c
0c09885
de4e37c
 
0c09885
 
 
 
 
 
02a1c61
0c09885
 
 
02a1c61
0c09885
 
 
 
 
 
de4e37c
0c09885
de4e37c
0c09885
 
 
 
 
 
de4e37c
0c09885
 
 
de4e37c
0c09885
de4e37c
5b5a20d
de4e37c
 
5b5a20d
 
 
 
de4e37c
 
 
0c09885
 
 
 
de4e37c
0c09885
5b5a20d
a873f76
de4e37c
 
 
 
5b5a20d
 
 
de4e37c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
 
5b5a20d
0c09885
 
 
 
5b5a20d
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e605ae7
0c09885
 
34890bc
 
 
0c09885
34890bc
 
 
 
 
 
 
893ae76
 
5b5a20d
0c09885
 
 
 
 
 
a873f76
0c09885
 
 
 
 
 
 
 
a873f76
5b5a20d
0c09885
5b5a20d
a873f76
5b5a20d
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
0c09885
5b5a20d
0c09885
7070b94
d176097
0c09885
 
 
 
 
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
893ae76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
893ae76
0c09885
5b5a20d
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
5b5a20d
0c09885
 
a873f76
0c09885
 
 
 
 
 
 
 
 
 
5b5a20d
0c09885
 
5b5a20d
0c09885
 
 
5b5a20d
0c09885
 
 
 
5b5a20d
0c09885
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
0c09885
5b5a20d
0c09885
 
 
 
5b5a20d
0c09885
 
 
5b5a20d
0c09885
 
 
5b5a20d
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
0c09885
 
893ae76
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
 
5b5a20d
e612a97
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
 
 
 
 
 
 
5b5a20d
0c09885
 
2a95ee9
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
 
0c09885
 
 
 
 
 
 
 
 
 
 
de4e37c
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
 
 
 
de4e37c
 
0c09885
 
 
 
 
 
 
 
 
de4e37c
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a95ee9
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a95ee9
0c09885
 
 
 
 
 
 
2a95ee9
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
0c09885
 
 
 
 
5b5a20d
0c09885
 
 
5b5a20d
 
0c09885
 
 
5b5a20d
0c09885
 
 
 
5b5a20d
0c09885
 
 
5b5a20d
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854f873
 
fa5ff78
 
 
 
 
 
 
 
7d23ffa
 
fa5ff78
 
 
0c09885
fa5ff78
 
 
 
 
7d23ffa
fa5ff78
 
 
7d23ffa
0c09885
 
 
7d23ffa
 
0c09885
fa5ff78
 
 
7d23ffa
fa5ff78
 
 
 
 
 
 
7d23ffa
fa5ff78
 
 
 
 
 
7d23ffa
fa5ff78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d23ffa
fa5ff78
 
 
 
 
 
 
 
 
 
 
 
 
7d23ffa
 
0c09885
 
fa5ff78
 
0c09885
 
 
 
fa5ff78
0c09885
 
 
 
 
 
 
 
 
 
fa5ff78
0c09885
 
fa5ff78
0c09885
 
 
 
 
fa5ff78
7d23ffa
0c09885
 
 
 
 
 
 
fa5ff78
0c09885
 
 
 
7d23ffa
0c09885
 
 
 
 
 
 
7d23ffa
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d23ffa
 
 
0c09885
7d23ffa
0c09885
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
a9de05b
7d23ffa
0c09885
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
7d23ffa
a9de05b
0c09885
 
 
 
 
7d23ffa
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa5ff78
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5ce139
0c09885
 
 
f5ce139
 
 
0c09885
f5ce139
 
 
 
 
 
0c09885
f5ce139
 
 
 
 
0c09885
 
f5ce139
 
 
 
 
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2acfe7
0c09885
 
e2acfe7
 
 
 
0c09885
 
 
 
 
 
 
e2acfe7
 
0c09885
 
fa5ff78
0c09885
 
 
e2acfe7
 
 
 
fa5ff78
 
0c09885
5b5a20d
e2acfe7
 
 
 
 
 
 
 
8ada575
e2acfe7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a873f76
0c09885
 
 
 
e2acfe7
0c09885
 
da4b58e
0c09885
 
 
 
 
 
f5ce139
 
0c09885
 
f5ce139
0c09885
f5ce139
0c09885
f5ce139
0c09885
f5ce139
 
 
0c09885
 
a873f76
f5ce139
0c09885
f5ce139
 
 
 
 
 
 
 
0c09885
a873f76
f5ce139
 
 
 
 
 
 
0c09885
f5ce139
 
a873f76
0c09885
f5ce139
0c09885
 
 
 
f5ce139
 
 
a873f76
0c09885
 
 
 
 
 
 
 
f5ce139
 
0c09885
 
f5ce139
0c09885
 
 
 
 
 
 
 
 
 
f5ce139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
f5ce139
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a873f76
0c09885
02a1c61
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e605ae7
0c09885
a873f76
0c09885
 
 
 
 
 
893ae76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a873f76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
6dc4dd3
 
 
 
 
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
0c09885
 
 
 
 
 
 
 
 
a9de05b
de4e37c
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
0c09885
 
 
 
 
6dc4dd3
0c09885
6dc4dd3
 
 
 
 
a873f76
0c09885
 
 
a873f76
0c09885
 
a873f76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a873f76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9de05b
0c09885
 
 
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
6dc4dd3
de4e37c
 
 
 
 
 
 
 
 
0c09885
a9de05b
de4e37c
 
 
 
 
 
 
 
 
0c09885
 
 
 
 
 
 
 
 
 
893ae76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
893ae76
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
a873f76
0c09885
 
 
 
 
 
 
 
 
 
 
de4e37c
 
 
 
0c09885
 
 
 
 
de4e37c
0c09885
 
 
 
 
de4e37c
0c09885
 
 
 
 
 
 
 
e612a97
0c09885
 
 
 
de4e37c
 
 
 
f5ce139
de4e37c
 
 
f5ce139
 
 
de4e37c
 
 
 
 
 
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
0c09885
de4e37c
 
0c09885
 
 
de4e37c
 
0c09885
 
 
 
 
 
 
 
6dc4dd3
 
 
 
 
 
 
 
 
 
 
 
 
0c09885
de4e37c
0c09885
 
de4e37c
0c09885
a9de05b
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de4e37c
0c09885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
app.py (v4) β€” CollabCode Researcher Interface
==============================================
Page-based flow: Welcome β†’ Setup β†’ Sections β†’ Pipeline β†’ Done β†’ Agreement β†’ Library
No tabs. One task per screen.
"""

from __future__ import annotations

import json
import html as html_lib
import queue as _queue
import tempfile
import threading
import time
from datetime import datetime, timezone, timedelta
from pathlib import Path

import gradio as gr

from transcript_parser import parse_transcript
from agent0_sectioner  import run_sectioning
from metacog_screener  import (
    screen_transcript, result_to_dict,
    add_tier2_term, propose_tier3_candidate,
    approve_tier3_candidate, reject_tier3_candidate,
    load_full_lexicon,
)
from agent1a_boundary  import propose_boundaries, boundaries_to_segments
from agent1b_coder     import code_section
from drive_utils import (
    get_drive_service,
    list_transcripts,
    read_file_from_drive,
    write_session_to_drive,
    load_session_from_drive,
    register_researcher,
    format_drive_diagnostic,
)
from kappa_calculator  import (
    calculate_kappa_report,
    resolve_disagreement,
    discard_disagreement,
)
from agent2_learner import list_pending_rules, approve_rule, reject_rule
from pipeline import (
    run_boundaries_parallel,
    run_coding_with_context,
    render_pipeline_stats_html,
    PipelineStats,
)
from llm_client import circuit_state, compute_timeout, reset_circuit
from sequential_analysis import (
    load_and_analyse,
    render_transition_matrix_html,
    render_significant_transitions_html,
    to_csv as seq_to_csv,
    lag_to_csv,
)

SESSIONS_ROOT = Path("sessions")
SESSIONS_ROOT.mkdir(parents=True, exist_ok=True)
_STYLES_DIR   = Path(__file__).parent / "static" / "styles"

MODEL_ID    = "Qwen/Qwen2.5-72B-Instruct"
TEMPERATURE = 0.1

import sys as _sys, importlib.metadata as _meta

def _startup_log() -> None:
    import gradio as _gr
    try:
        hf_ver = _meta.version("huggingface_hub")
    except Exception:
        hf_ver = "unknown"
    hf_tok = "SET" if __import__("os").environ.get("HF_TOKEN") else "MISSING ⚠"
    print("=" * 60)
    print("  CollabCode v4 β€” startup")
    print("=" * 60)
    print(f"  Python       : {_sys.version.split()[0]}")
    print(f"  Gradio       : {_gr.__version__}")
    print(f"  HF hub       : {hf_ver}")
    print(f"  HF_TOKEN     : {hf_tok}")
    print(f"  Sessions root: {SESSIONS_ROOT.resolve()}")
    print(f"  Model        : {MODEL_ID}")
    print("=" * 60)

_startup_log()


def _load_css() -> str:
    scss_entry = _STYLES_DIR / "main.scss"
    if scss_entry.exists():
        try:
            import subprocess
            result = subprocess.run(
                ["sass", str(scss_entry), "--style=expanded",
                 "--load-path", str(_STYLES_DIR), "--no-source-map"],
                capture_output=True, text=True, timeout=30,
            )
            if result.returncode == 0 and result.stdout:
                css = result.stdout
                (_STYLES_DIR / "main.css").write_text(css, encoding="utf-8")
                return css
        except (FileNotFoundError, subprocess.TimeoutExpired):
            pass
    compiled = _STYLES_DIR / "main.css"
    if compiled.exists():
        return compiled.read_text(encoding="utf-8")
    return ""


# ---------------------------------------------------------------------------
# Design system β€” dimensions
# ---------------------------------------------------------------------------

DIMENSIONS = [
    ("D1", "Sustaining Mutual Understanding",
     "Speakers ensure contributions are understood; actively seek comprehension."),
    ("D2", "Dialogue Management",
     "Smooth conversational flow with clear turn-taking and minimal overlap."),
    ("D3", "Information Pooling",
     "Partners share, elaborate, and elicit domain-specific information."),
    ("D4", "Reaching Consensus",
     "Partners critically evaluate options before reaching a joint decision."),
    ("D5", "Task Division",
     "Task is systematically divided into subtasks with clear work phases."),
    ("D6", "Time Management",
     "Partners monitor time and adjust pace to ensure task completion."),
    ("D7", "Technical Coordination",
     "Partners manage shared technical tools effectively."),
    ("D8", "Reciprocal Interaction",
     "Partners interact as equals with mutual respect and balanced contribution."),
    ("D9", "Individual Task Orientation",
     "Each participant actively engages, contributes knowledge, avoids distraction."),
    ("NS", "Not Sure",
     "Cannot confidently assign β€” competing interpretations remain unresolved."),
    ("NA", "Not Applicable",
     "Doesn't fit any dimension: off-topic, administrative, or technical noise."),
]
DIM_CHOICES        = [f"{d} β€” {l}" for d, l, _ in DIMENSIONS]
DIM_ID_FROM_CHOICE = {f"{d} β€” {l}": d for d, l, _ in DIMENSIONS}
DIM_DESC_FROM_ID   = {d: desc for d, _, desc in DIMENSIONS}

SEC_NONE            = "None β€” single dimension only"
SEC_DIM_CHOICES     = [SEC_NONE] + DIM_CHOICES
SEC_ID_FROM_CHOICE  = {SEC_NONE: None, **DIM_ID_FROM_CHOICE}

# SSRL phase tagging (Iiskala 2011; JΓ€rvelΓ€ & Hadwin 2013)
SSRL_PHASES = [
    ("M-MON",  "Individual monitoring β€” one speaker tracks own/others' understanding"),
    ("M-REG",  "Individual regulation β€” one speaker adjusts plan, strategy or effort"),
    ("CO-REG", "Co-regulation β€” one speaker scaffolds another's metacognitive process"),
    ("SSRL",   "Socially shared β€” group jointly monitors and regulates together"),
]
SSRL_NONE           = "None β€” no metacognitive activity"
SSRL_CHOICES        = [SSRL_NONE] + [f"{c} β€” {l}" for c, l in SSRL_PHASES]
SSRL_ID_FROM_CHOICE = {SSRL_NONE: None, **{f"{c} β€” {l}": c for c, l in SSRL_PHASES}}


# ---------------------------------------------------------------------------
# Speaker palette
# ---------------------------------------------------------------------------

SPEAKER_PALETTE = [
    ("#4338ca", "#eef2ff", "#c7d2fe", "πŸ”΅"),
    ("#b45309", "#fffbeb", "#fde68a", "🟑"),
    ("#065f46", "#ecfdf5", "#a7f3d0", "🟒"),
    ("#9a3412", "#fff7ed", "#fed7aa", "🟠"),
    ("#6b21a8", "#faf5ff", "#e9d5ff", "🟣"),
    ("#0e7490", "#ecfeff", "#a5f3fc", "πŸ”·"),
]


def _assign_speakers(turns: list[dict]) -> dict:
    seen: dict[str, dict] = {}
    for t in turns:
        sp = t.get("speaker", "?")
        if sp not in seen:
            i = len(seen) % len(SPEAKER_PALETTE)
            c, bg, ibg, emoji = SPEAKER_PALETTE[i]
            seen[sp] = {"color": c, "bg": bg, "initials_bg": ibg,
                        "emoji": emoji, "index": i}
    return seen


def _speaker_avatar(name: str, entry: dict) -> str:
    initials = "".join(w[0] for w in name.split()[:2]).upper() or "?"
    return (
        f'<span title="{_h(name)}" style="'
        f'display:inline-flex;align-items:center;justify-content:center;'
        f'width:30px;height:30px;border-radius:50%;background:{entry["initials_bg"]};'
        f'color:{entry["color"]};font-weight:800;font-size:0.72em;flex-shrink:0;'
        f'border:1.5px solid {entry["color"]}20">{initials}</span>'
    )


_TURN_MERGE_GAP_S = 5   # merge same-speaker turns with gap < this many seconds

def _format_turns_html(seg: dict, speaker_map: dict) -> str:
    """Render episode turns, grouping consecutive same-speaker turns with small gaps."""
    turns = seg.get("turns", [])
    if not turns:
        return '<p style="color:#94a3b8;font-style:italic">No turns in this segment.</p>'

    # ── Group consecutive same-speaker turns with gap < _TURN_MERGE_GAP_S ────
    groups: list[dict] = []
    for t in turns:
        sp  = t.get("speaker", "?")
        cur = t.get("start_seconds", 0)
        if (groups
                and groups[-1]["speaker"] == sp
                and (cur - groups[-1]["last_seconds"]) < _TURN_MERGE_GAP_S):
            groups[-1]["texts"].append(t.get("text", ""))
            groups[-1]["last_seconds"] = cur
            groups[-1]["last_id"] = t.get("turn_id", "")
        else:
            groups.append({
                "speaker":      sp,
                "texts":        [t.get("text", "")],
                "start_time":   t.get("start_time", ""),
                "last_seconds": cur,
                "first_id":     t.get("turn_id", ""),
                "last_id":      t.get("turn_id", ""),
            })

    parts = []
    for g in groups:
        sp    = g["speaker"]
        entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc",
                                     "initials_bg": "#e2e8f0", "emoji": "β—‹"})
        avatar = _speaker_avatar(sp, entry)
        ts     = _h(g["start_time"])
        merged = " ".join(g["texts"])
        fid, lid = g["first_id"], g["last_id"]
        id_label = f"#{fid}–#{lid}" if fid != lid else f"#{fid}"
        # Wrap separate sentences for readability
        sentences = [s.strip() for s in merged.replace("…", "… ").split("  ") if s.strip()]
        body      = " ".join(f'<span style="opacity:0.9">{_h(s)}</span>' for s in sentences) or _h(merged)
        parts.append(
            f'<div style="display:flex;gap:10px;padding:11px 0;'
            f'border-bottom:1px solid #f1f5f9;align-items:flex-start">'
            f'{avatar}'
            f'<div style="flex:1;min-width:0">'
            f'<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:4px">'
            f'<span style="font-weight:700;color:{entry["color"]};font-size:0.85em">{_h(sp)}</span>'
            f'<span style="font-family:monospace;font-size:0.72em;color:#94a3b8">{ts}</span>'
            f'<span style="font-family:monospace;font-size:0.65em;color:#cbd5e1">{id_label}</span>'
            f'</div>'
            f'<div style="line-height:1.7;color:#1e293b;font-size:0.95em">{body}</div>'
            f'</div></div>'
        )
    return f'<div style="font-family:system-ui,sans-serif">{"".join(parts)}</div>'


def _h(s) -> str:
    return html_lib.escape(str(s))


def _section_cards_html(sections: list[dict], stages: dict, current_idx: int) -> str:
    if not sections:
        return ""
    cards = []
    for i, s in enumerate(sections):
        stage = stages.get(s["section_id"], "pending")
        if stage == "done":
            bc, fc, icon = "#86efac", "#065f46", "βœ“"
        elif i == current_idx:
            bc, fc, icon = "#93c5fd", "#1d4ed8", "β–Ά"
        else:
            bc, fc, icon = "#e2e8f0", "#94a3b8", "β—‹"
        n = s["end_turn_id"] - s["start_turn_id"] + 1
        cards.append(
            f'<div style="flex:1;min-width:120px;border:2px solid {bc};'
            f'border-radius:8px;padding:8px 12px;background:white">'
            f'<div style="font-weight:700;color:{fc};font-size:0.85em">'
            f'{icon} {_h(s["label"])}</div>'
            f'<div style="font-family:monospace;font-size:0.72em;color:#94a3b8;margin-top:2px">'
            f'{_h(s["start_time"])}–{_h(s["end_time"])} Β· {n} turns</div>'
            f'</div>'
        )
    return f'<div style="display:flex;gap:8px;flex-wrap:wrap;margin:10px 0">{"".join(cards)}</div>'


def _episode_table_html(turns: list[dict], boundaries: list[dict]) -> str:
    if not turns:
        return '<p style="color:#94a3b8">No turns.</p>'
    turn_ids = sorted(t["turn_id"] for t in turns)
    bmap     = {b["after_turn_id"]: b for b in boundaries}
    cuts     = [turn_ids[0]]
    for b in sorted(boundaries, key=lambda x: x["after_turn_id"]):
        idx = turn_ids.index(b["after_turn_id"]) if b["after_turn_id"] in turn_ids else -1
        if idx >= 0 and idx < len(turn_ids) - 1:
            cuts.append(turn_ids[idx + 1])

    rows = (
        "<tr style='background:#f1f5f9'>"
        "<th style='padding:6px 10px;text-align:left;font-size:0.8em;font-weight:700;color:#475569'>Episode</th>"
        "<th style='padding:6px 10px;text-align:left;font-size:0.8em;font-weight:700;color:#475569'>Turns</th>"
        "<th style='padding:6px 10px;text-align:left;font-size:0.8em;font-weight:700;color:#475569'>Count</th>"
        "</tr>"
    )
    for i, start in enumerate(cuts):
        end = turn_ids[turn_ids.index(cuts[i + 1]) - 1] if i + 1 < len(cuts) else turn_ids[-1]
        bg  = "#f8fafc" if i % 2 else "white"
        rows += (
            f'<tr style="background:{bg}">'
            f'<td style="padding:6px 10px;font-family:monospace;font-weight:700">ep{i+1:02d}</td>'
            f'<td style="padding:6px 10px;font-family:monospace;color:#475569">{start}–{end}</td>'
            f'<td style="padding:6px 10px;color:#94a3b8">{end-start+1}</td>'
            f'</tr>'
        )
        if i < len(cuts) - 1:
            after = cuts[i + 1] - 1
            b  = bmap.get(after, {})
            sig  = _h(b.get("boundary_signal", "boundary"))
            conf = b.get("confidence", "?")
            rat  = _h(b.get("rationale", ""))
            cc   = {"high": "#065f46", "medium": "#b45309", "low": "#be123c"}.get(conf, "#64748b")
            rows += (
                f'<tr style="background:#fffbeb">'
                f'<td colspan="3" style="padding:3px 10px;font-size:0.78em;color:#78350f;'
                f'border-top:1px dashed #fde68a">'
                f'─── after turn {after} Β· <em>{sig}</em> Β· '
                f'<strong style="color:{cc}">{conf}</strong> confidence β€” {rat}'
                f'</td></tr>'
            )

    n_ep = len(cuts)
    n_b  = len(boundaries)
    return (
        f'<div style="font-size:0.8em;font-weight:700;color:#64748b;'
        f'text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px">'
        f'{n_b} boundary{"ies" if n_b!=1 else ""} β†’ {n_ep} episode{"s" if n_ep!=1 else ""}'
        f'</div>'
        f'<div style="overflow-x:auto">'
        f'<table style="border-collapse:collapse;width:100%;border:1px solid #e2e8f0;'
        f'border-radius:8px;overflow:hidden">{rows}</table></div>'
    )


def _uncertainty_html(seg: dict) -> str:
    if not seg.get("uncertain"):
        return ""
    note = _h(seg.get("uncertainty_note") or "")
    return (
        f'<div role="alert" style="background:#fffbeb;border:1px solid #fbbf24;'
        f'border-radius:8px;padding:10px 14px;margin-bottom:10px;display:flex;gap:8px;'
        f'align-items:flex-start;font-size:0.88em">'
        f'<span style="font-size:1.1em">⚠</span>'
        f'<div><strong style="color:#78350f">AI flagged uncertain</strong>'
        f'<span style="color:#92400e"> β€” {note}</span></div>'
        f'</div>'
    )


def _dim_desc_html(choice: str) -> str:
    if not choice:
        return ""
    did  = DIM_ID_FROM_CHOICE.get(choice, "")
    desc = DIM_DESC_FROM_ID.get(did, "")
    if not desc:
        return ""
    return (
        f'<div style="background:#eff6ff;border-left:3px solid #4338ca;'
        f'border-radius:0 6px 6px 0;padding:7px 12px;font-size:0.85em;'
        f'color:#1e40af;margin-top:6px">{_h(desc)}</div>'
    )


def _status_card(title: str, status: str = "success",
                 details: dict | None = None, error_msg: str | None = None) -> str:
    colors = {
        "success":    ("#f0fdf4", "#065f46", "#86efac", "βœ“"),
        "error":      ("#fef2f2", "#991b1b", "#fca5a5", "βœ—"),
        "warning":    ("#fffbeb", "#78350f", "#fbbf24", "⚠"),
        "processing": ("#eff6ff", "#1e40af", "#93c5fd", "⏳"),
    }
    bg, tc, bc, icon = colors.get(status, colors["success"])
    detail_html = ""
    if details:
        detail_html = '<div style="display:flex;flex-wrap:wrap;gap:16px;font-size:0.88em;margin-top:10px">'
        for k, v in details.items():
            detail_html += (
                f'<div><span style="color:{tc};opacity:0.7">{_h(k)}:</span> '
                f'<strong style="color:{tc}">{_h(str(v))}</strong></div>'
            )
        detail_html += '</div>'
    error_html = (
        f'<div style="background:rgba(0,0,0,0.05);border-radius:6px;padding:8px;'
        f'font-family:monospace;font-size:0.78em;margin-top:8px;'
        f'white-space:pre-wrap;word-break:break-all">{_h(error_msg)}</div>'
        if error_msg else ""
    )
    return (
        f'<div style="background:{bg};border:2px solid {bc};'
        f'border-radius:10px;padding:14px 18px;margin:8px 0">'
        f'<div style="color:{tc};font-weight:700;font-size:0.95em">'
        f'{icon} {_h(title)}</div>'
        f'{detail_html}{error_html}'
        f'</div>'
    )


# ---------------------------------------------------------------------------
# LLM progress indicator β€” shown while a blocking LLM call runs in background.
# Updates every 2 s via heartbeat yields; spinner cycles to signal activity.
# ---------------------------------------------------------------------------

_SPINNERS = ["◐", "β—“", "β—‘", "β—’"]

def _llm_progress_html(message: str, elapsed: int, est_total: int,
                       tokens_in: int, circ: str, spin_i: int) -> str:
    """
    Rich status card shown during LLM calls.
    Never freezes the UI β€” fn_process calls this from a heartbeat loop
    while the actual LLM request runs in a daemon thread.
    """
    pct        = min(int(elapsed / max(est_total, 1) * 85), 85)  # max 85% until done
    remaining  = max(est_total - elapsed, 0)
    spinner    = _SPINNERS[spin_i % len(_SPINNERS)]
    bar_color  = "#4338ca"
    circ_color = "#065f46" if circ == "CLOSED" else "#b45309" if circ == "HALF_OPEN" else "#be123c"
    circ_icon  = "βœ“" if circ == "CLOSED" else "⚠" if circ == "HALF_OPEN" else "βœ—"
    tok_str    = f"{tokens_in:,}"
    eta_str    = f"~{remaining}s" if remaining > 5 else "finishing…"

    return (
        f'<div style="background:#eff6ff;border:2px solid #93c5fd;'
        f'border-radius:12px;padding:16px 20px;font-family:system-ui,sans-serif">'

        # ── Header row ────────────────────────────────────────────────────
        f'<div style="display:flex;align-items:center;gap:10px;margin-bottom:12px">'
        f'<span style="font-size:1.3em;line-height:1">{spinner}</span>'
        f'<span style="font-weight:700;color:#1e3a8a;font-size:0.94em">{_h(message)}</span>'
        f'<span style="margin-left:auto;font-family:monospace;font-size:0.84em;'
        f'background:#dbeafe;padding:3px 9px;border-radius:6px;color:#1e40af;'
        f'white-space:nowrap">{elapsed}s elapsed</span>'
        f'</div>'

        # ── Progress bar ──────────────────────────────────────────────────
        f'<div style="background:#dbeafe;border-radius:5px;height:9px;'
        f'margin-bottom:10px;overflow:hidden;position:relative">'
        f'<div style="height:100%;width:{pct}%;background:{bar_color};'
        f'border-radius:5px;transition:width 0.4s ease"></div>'
        f'<span style="position:absolute;right:6px;top:-1px;font-size:0.7em;'
        f'color:#6366f1;font-weight:700">{pct}%</span>'
        f'</div>'

        # ── Metrics row ───────────────────────────────────────────────────
        f'<div style="display:flex;flex-wrap:wrap;gap:14px;font-size:0.8em;color:#475569">'
        f'<span>⏱ Est. total: ~{est_total}s</span>'
        f'<span>βŒ› ETA: {eta_str}</span>'
        f'<span>πŸ”’ ~{tok_str} tokens in</span>'
        f'<span style="color:{circ_color};font-weight:600">'
        f'LLM circuit: {circ_icon} {circ}</span>'
        f'</div>'

        # ── Note ──────────────────────────────────────────────────────────
        f'<div style="margin-top:8px;font-size:0.75em;color:#94a3b8;font-style:italic">'
        f'Processing in background β€” UI stays responsive. '
        f'Typical 250-turn transcript: 45–90 s on HF shared inference.'
        f'</div>'
        f'</div>'
    )


def _speaker_legend_html(speaker_map: dict) -> str:
    if not speaker_map:
        return ""
    chips = []
    for name, entry in speaker_map.items():
        avatar = _speaker_avatar(name, entry)
        chips.append(
            f'<span style="display:inline-flex;align-items:center;gap:5px;'
            f'padding:3px 8px;border-radius:20px;background:{entry["bg"]};'
            f'border:1px solid {entry["initials_bg"]}">'
            f'{avatar}'
            f'<span style="font-size:0.82em;font-weight:600;color:{entry["color"]}">'
            f'{_h(name)}</span></span>'
        )
    return (
        f'<div style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px">'
        f'{"".join(chips)}</div>'
    )


def _kappa_html(report: dict) -> str:
    ac1         = report.get("overall_ac1", report.get("overall_kappa", 0.0))
    ac1_interp  = report.get("ac1_interpretation", report.get("kappa_interpretation", ""))
    ac1_ci      = report.get("ac1_ci_95", [None, None])
    gate        = report.get("gate_passed", False)
    col         = "#065f46" if gate else "#be123c"
    icon        = "βœ“" if gate else "βœ—"
    pct         = int(min(max(ac1, 0) * 100, 100))
    kappa       = report.get("overall_kappa", 0.0)
    kappa_ci    = report.get("kappa_ci_95", [None, None])
    divergence  = report.get("kappa_ac1_divergence", 0.0)
    div_flag    = report.get("kappa_ac1_divergence_flag", False)
    prev_warn   = report.get("prevalence_warning", False)
    n_segs      = report.get("n_segments_total", 0)
    n_dis       = len(report.get("segments_in_disagreement", []))

    ci_text = ""
    if ac1_ci[0] is not None:
        ci_text = f'<span style="font-size:0.75em;color:#64748b"> 95% CI [{ac1_ci[0]:.3f}, {ac1_ci[1]:.3f}]</span>'

    prev_banner = ""
    if prev_warn:
        dominant = max(
            ((d, v["prevalence"]) for d, v in (report.get("category_distribution") or {}).items()),
            key=lambda x: x[1], default=("?", 0)
        )
        prev_banner = (
            f'<div style="background:#fffbeb;border:1px solid #fbbf24;border-radius:6px;'
            f'padding:8px 12px;margin-bottom:10px;font-size:0.82em;color:#78350f">'
            f'⚠ <strong>Prevalence bias detected:</strong> {_h(dominant[0])} accounts for '
            f'{dominant[1]:.0%} of codings. AC1 is the appropriate metric here.</div>'
        )

    kc = "#065f46" if kappa >= 0.70 else "#be123c"
    if div_flag:
        div_note = (
            f'<div style="font-size:0.78em;color:#64748b;margin-top:4px">'
            f'Cohen\'s ΞΊ = <span style="font-weight:700;color:{kc}">{kappa:.3f}</span>'
            + (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') +
            f' Β· |AC1 βˆ’ ΞΊ| = <strong style="color:#d97706">{divergence:.3f}</strong> (prevalence bias)'
            f'</div>'
        )
    else:
        div_note = (
            f'<div style="font-size:0.78em;color:#94a3b8;margin-top:4px">'
            f'Cohen\'s ΞΊ = <span style="color:{kc}">{kappa:.3f}</span>'
            + (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') +
            f' (reference β€” Gwet 2008 primary)</div>'
        )

    dim_src   = report.get("ac1_per_dimension") or report.get("kappa_per_dimension") or {}
    dim_label = "AC1" if "ac1_per_dimension" in report else "ΞΊ"
    dim_rows  = ""
    for dim in ["D1","D2","D3","D4","D5","D6","D7","D8","D9","NS","NA"]:
        v = dim_src.get(dim)
        if v is None:
            dim_rows += (
                f'<div style="display:flex;gap:8px;align-items:center;padding:3px 0;'
                f'border-top:1px solid #f1f5f9;opacity:0.4">'
                f'<span style="font-weight:700;font-size:0.82em;width:32px">{dim}</span>'
                f'<span style="font-size:0.75em;color:#94a3b8;flex:1">insufficient data</span>'
                f'</div>'
            )
            continue
        vp = int(min(max(v, 0) * 100, 100))
        vc = "#065f46" if v >= 0.70 else "#b45309" if v >= 0.50 else "#be123c"
        dim_rows += (
            f'<div style="display:flex;gap:8px;align-items:center;padding:4px 0;'
            f'border-top:1px solid #f1f5f9">'
            f'<span style="font-weight:700;font-size:0.82em;width:32px">{dim}</span>'
            f'<div style="flex:1;height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden">'
            f'<div style="height:100%;width:{vp}%;background:{vc};border-radius:3px"></div></div>'
            f'<span style="font-weight:700;font-size:0.82em;color:{vc};width:40px;text-align:right">'
            f'{v:.3f}</span>'
            f'</div>'
        )

    return (
        f'<div style="background:white;border:1px solid #e2e8f0;border-radius:12px;padding:20px">'
        f'{prev_banner}'
        f'<div style="display:flex;align-items:flex-end;gap:14px;margin-bottom:4px">'
        f'<span style="font-size:3em;font-weight:800;color:{col};line-height:1">{ac1:.3f}</span>'
        f'<div>'
        f'<div style="font-weight:700;color:{col};font-size:1em">{icon} {_h(ac1_interp)}</div>'
        f'<div style="font-size:0.76em;color:#94a3b8">Gwet\'s AC1 Β· gate β‰₯ 0.70</div>'
        f'</div></div>'
        f'{ci_text}'
        f'<div style="position:relative;height:10px;background:#e2e8f0;border-radius:5px;margin:10px 0">'
        f'<div style="position:absolute;height:100%;width:{pct}%;background:{col};border-radius:5px"></div>'
        f'<div style="position:absolute;left:70%;top:-4px;height:18px;width:2px;background:#94a3b8"></div>'
        f'<div style="position:absolute;left:70%;top:-16px;font-size:0.68em;color:#94a3b8;'
        f'transform:translateX(-50%)">0.70</div>'
        f'</div>'
        f'<div style="font-size:0.83em;color:#64748b">'
        f'{n_segs} segments Β· {n_dis} disagreement{"s" if n_dis!=1 else ""}</div>'
        f'{div_note}'
        f'<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;'
        f'letter-spacing:0.07em;color:#94a3b8;margin:14px 0 6px">Per-Dimension {dim_label}</div>'
        f'{dim_rows}'
        f'</div>'
    )


def _rules_html(rules: list[dict]) -> str:
    if not rules:
        return (
            '<div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;'
            'padding:12px 16px;color:#065f46;font-size:0.9em">No rules pending review.</div>'
        )
    TYPE_META = {
        "boundary_clarification":       ("#dbeafe", "#1e3a8a", "Boundary"),
        "disambiguation_rule":          ("#fce7f3", "#831843", "Disambiguation"),
        "behavioral_marker_refinement": ("#d1fae5", "#064e3b", "Marker Refinement"),
    }
    cards = []
    for r in rules:
        bg, tc, label = TYPE_META.get(r.get("rule_type", ""), ("#f1f5f9", "#334155", "Rule"))
        dims    = _h(", ".join(r.get("dimensions_involved") or []))
        desc    = _h(r.get("description", ""))
        rat     = _h(r.get("rationale", ""))
        conf    = _h(r.get("confidence", ""))
        note    = _h(r.get("agent2_note", ""))
        rid     = _h(r.get("rule_id", ""))
        created = r.get("created_at", "")[:10]
        cards.append(
            f'<article style="border:1px solid #e2e8f0;border-radius:10px;'
            f'padding:16px 18px;margin-bottom:12px;background:white">'
            f'<div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:6px;margin-bottom:10px">'
            f'<div style="display:flex;align-items:center;gap:8px">'
            f'<span style="background:{bg};color:{tc};border-radius:20px;'
            f'padding:2px 10px;font-size:0.72em;font-weight:700;text-transform:uppercase">{label}</span>'
            f'<span style="font-family:monospace;font-size:0.75em;color:#94a3b8">{rid} Β· {created}</span>'
            f'</div>'
            f'<span style="font-size:0.78em;color:#64748b">dims: <strong>{dims}</strong></span>'
            f'</div>'
            f'<p style="font-size:0.93em;color:#1e293b;line-height:1.6;margin:0 0 8px">{desc}</p>'
            f'<p style="font-size:0.82em;color:#475569;margin:0 0 8px"><strong>Evidence:</strong> {rat}</p>'
            f'<div style="font-size:0.78em;color:#64748b">'
            f'Confidence: <strong>{conf}</strong>'
            + (f' Β· Note: {note}' if note else '') +
            f'</div></article>'
        )
    return "".join(cards)


def _sections_html(sections: list[dict], n_turns: int,
                   agent0_rt: float, n_speakers: int,
                   all_turns: list[dict] | None = None) -> str:
    """
    Rich sections display for the Review Sections page.

    Uses native HTML <details>/<summary> for expand-to-read-content β€” no JS required.
    Each section is collapsed by default (researcher sees the label and size at a glance)
    and can be expanded to read the AI summary + first 8 turns of actual transcript.

    Label format in the textarea is "s01: Label" so the mapping is unambiguous.
    """
    if not sections:
        return '<p style="color:#94a3b8;font-style:italic">No sections detected.</p>'

    avg   = n_turns // len(sections) if sections else 0
    total = n_turns

    # ── 1. Agent completion card ─────────────────────────────────────────────
    agent_card = (
        f'<div style="background:#f0fdf4;border:2px solid #86efac;border-radius:10px;'
        f'padding:14px 18px;margin-bottom:14px;font-family:system-ui,sans-serif">'
        f'<div style="display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap">'
        f'<div style="flex:1;min-width:200px">'
        f'<div style="display:flex;align-items:center;gap:8px;margin-bottom:5px">'
        f'<span style="font-size:1.1em">βœ“</span>'
        f'<strong style="color:#065f46;font-size:0.95em">Agent 0 β€” Structural Segmenter</strong>'
        f'<span style="background:#bbf7d0;color:#14532d;font-size:0.72em;font-weight:700;'
        f'padding:2px 8px;border-radius:20px;margin-left:4px">completed in {agent0_rt:.1f}s</span>'
        f'</div>'
        f'<div style="font-size:0.82em;color:#166534;line-height:1.7">'
        f'<strong>{total}</strong> turns Β· <strong>{n_speakers}</strong> speaker(s) β†’ '
        f'<strong>{len(sections)}</strong> sections detected '
        f'(avg {avg} turns/section)<br>'
        f'<em>Basis: lexical cohesion (Hearst 1997) Β· topic modelling (Purver et al. 2006) '
        f'Β· activity phases (Stahl 2006; Roschelle &amp; Teasley 1995)</em>'
        f'</div>'
        f'</div>'
        f'<div style="text-align:right;font-family:monospace;font-size:0.78em;color:#6b7280">'
        f'Qwen2.5-72B Β· T=0.1</div>'
        f'</div>'
        f'</div>'
    )

    # ── 2. Expandable section list ───────────────────────────────────────────
    palette = [
        ("#4338ca", "#eef2ff"),  # indigo
        ("#b45309", "#fffbeb"),  # amber
        ("#065f46", "#f0fdf4"),  # emerald
        ("#9a3412", "#fff7ed"),  # orange
        ("#6b21a8", "#faf5ff"),  # purple
        ("#0e7490", "#ecfeff"),  # cyan
        ("#be123c", "#fff1f2"),  # rose
    ]

    warnings = []
    detail_items = []

    for i, s in enumerate(sections):
        col, bg = palette[i % len(palette)]
        n       = s["end_turn_id"] - s["start_turn_id"] + 1
        pct     = round(n / total * 100) if total else 0

        if pct > 30 and len(sections) > 2:
            warnings.append(
                f'<strong>{_h(s["label"])}</strong> ({n} turns, {pct}%) is unusually large. '
                f'Expand it below to check if it contains distinct sub-topics.'
            )

        # ── Bar ──
        bar = (
            f'<div style="background:#e2e8f0;border-radius:3px;height:4px;'
            f'width:80px;display:inline-block;vertical-align:middle;margin-left:8px">'
            f'<div style="height:100%;width:{min(pct,100)}%;background:{col};border-radius:3px">'
            f'</div></div>'
        )

        # ── Transcript excerpt ──
        excerpt_html = ""
        if all_turns:
            sec_turns = [
                t for t in all_turns
                if s["start_turn_id"] <= t["turn_id"] <= s["end_turn_id"]
            ]
            shown = sec_turns[:8]
            rows  = []
            for t in shown:
                sp  = _h(t.get("speaker", "?"))
                ts  = _h(t.get("start_time", ""))
                txt = t.get("text", "")
                if len(txt) > 180:
                    txt = txt[:180] + "…"
                rows.append(
                    f'<div style="padding:5px 0;border-bottom:1px solid #f1f5f9">'
                    f'<span style="font-weight:700;font-size:0.82em;color:{col};margin-right:6px">'
                    f'{sp}</span>'
                    f'<span style="font-size:0.72em;color:#94a3b8;font-family:monospace;'
                    f'margin-right:8px">{ts}</span>'
                    f'<span style="font-size:0.88em;color:#1e293b">{_h(txt)}</span>'
                    f'</div>'
                )
            if len(sec_turns) > 8:
                rows.append(
                    f'<div style="font-size:0.75em;color:#94a3b8;padding:4px 0;'
                    f'font-style:italic">β‹― {len(sec_turns)-8} more turns</div>'
                )
            excerpt_html = (
                f'<div style="margin-top:10px">'
                f'<div style="font-size:0.72em;font-weight:700;text-transform:uppercase;'
                f'letter-spacing:0.06em;color:#94a3b8;margin-bottom:6px">'
                f'Transcript excerpt (first {len(shown)} of {n} turns)</div>'
                f'{"".join(rows)}'
                f'</div>'
            )

        summary_text = _h(s.get("summary", "No summary provided."))

        detail_items.append(
            f'<details style="border:1px solid {col}40;border-radius:10px;'
            f'margin-bottom:8px;overflow:hidden;font-family:system-ui,sans-serif">'

            # ── Collapsed header (always visible) ──────────────────────────
            f'<summary style="cursor:pointer;padding:12px 16px;background:{bg};'
            f'border-left:5px solid {col};display:flex;align-items:center;'
            f'gap:10px;list-style:none;-webkit-appearance:none">'
            f'<span style="font-size:0.7em;font-weight:800;color:{col};'
            f'text-transform:uppercase;letter-spacing:0.08em;min-width:28px">'
            f'{_h(s["section_id"])}</span>'
            f'<span style="font-weight:700;color:#1e293b;flex:1;font-size:0.92em">'
            f'{_h(s["label"])}</span>'
            f'<span style="font-size:0.72em;color:#64748b;white-space:nowrap;'
            f'font-family:monospace">{_h(s["start_time"])}–{_h(s["end_time"])}</span>'
            f'<span style="font-size:0.72em;color:{col};font-weight:700;white-space:nowrap">'
            f'&nbsp;{n} turns ({pct}%)</span>'
            f'{bar}'
            f'<span style="color:{col};font-size:0.8em;margin-left:4px">β–Ό read</span>'
            f'</summary>'

            # ── Expanded content ────────────────────────────────────────────
            f'<div style="padding:14px 16px;background:white;'
            f'border-top:1px solid {col}20">'
            f'<p style="font-size:0.85em;color:#334155;margin:0 0 8px;line-height:1.65">'
            f'<strong style="color:{col}">AI summary:</strong> {summary_text}</p>'
            f'{excerpt_html}'
            f'</div>'
            f'</details>'
        )

    section_list = f'<div style="margin-bottom:12px">{"".join(detail_items)}</div>'

    # ── 3. Warnings ──────────────────────────────────────────────────────────
    warn_html = ""
    if warnings:
        items = "".join(f"<li style='margin:4px 0'>{w}</li>" for w in warnings)
        warn_html = (
            f'<div style="background:#fffbeb;border:1px solid #fbbf24;border-radius:8px;'
            f'padding:10px 14px;margin-bottom:12px;font-size:0.83em;color:#78350f">'
            f'<strong>⚠ Size note</strong>'
            f'<ul style="margin:6px 0 0;padding-left:18px">{items}</ul>'
            f'</div>'
        )

    # ── 4. Label editor instruction ──────────────────────────────────────────
    instr = (
        f'<div style="background:#f8fafc;border:1px solid #e2e8f0;'
        f'border-left:4px solid #4338ca;border-radius:0 8px 8px 0;'
        f'padding:10px 14px;font-size:0.84em;color:#334155;margin-bottom:4px">'
        f'<strong>Rename sections below</strong> β€” each line follows the format '
        f'<code style="background:#e2e8f0;padding:1px 5px;border-radius:3px">'
        f's01: Your Label</code>. '
        f'Edit the text after the colon only; the <code>s01:</code> prefix keeps the order clear. '
        f'Turn boundaries are fixed β€” only labels change. '
        f'Expand any section above to read its content before renaming.'
        f'</div>'
    )

    return agent_card + section_list + warn_html + instr


def _episode_dialogue_html(segments: list[dict], boundaries: list[dict],
                           speaker_map: dict) -> str:
    """
    Render each proposed episode with its actual dialogue turns + boundary markers.

    Design goal: the researcher must be able to READ the transcript before
    deciding whether to accept the AI's proposed boundary positions.
    Showing only turn-ID tables (the old approach) is opaque.

    Rules:
    - Up to 5 turns shown per episode; truncation indicated clearly
    - Speaker avatars + timestamps match the coding canvas
    - Boundary markers show signal type, confidence, and AI rationale
    - Entire view is scrollable so the page does not grow unbounded
    """
    if not segments:
        return (
            '<p style="color:#94a3b8;font-style:italic;padding:12px">'
            'No episode data yet.</p>'
        )

    bmap: dict[int, dict] = {}
    for b in boundaries:
        bmap[b.get("after_turn_id", -1)] = b

    conf_colors = {
        "high":   ("#065f46", "#f0fdf4", "#86efac"),
        "medium": ("#92400e", "#fffbeb", "#fde68a"),
        "low":    ("#991b1b", "#fef2f2", "#fca5a5"),
    }

    parts: list[str] = []
    for i, seg in enumerate(segments):
        turns = seg.get("turns", [])
        ep_id = seg.get("segment_id", f"ep{i+1:02d}")
        ep_num = ep_id.split("_ep")[-1] if "_ep" in ep_id else str(i + 1)
        n_turns = len(turns)

        # Episode header strip
        parts.append(
            f'<div style="background:#f1f5f9;border-left:4px solid #4338ca;'
            f'padding:7px 14px;display:flex;align-items:center;gap:10px;'
            f'font-family:system-ui,sans-serif">'
            f'<span style="font-size:0.72em;font-weight:800;color:#4338ca;'
            f'text-transform:uppercase;letter-spacing:0.08em">Episode {ep_num}</span>'
            f'<span style="font-size:0.75em;color:#64748b">{n_turns} turns</span>'
            + (f'<span style="font-size:0.75em;color:#94a3b8;font-style:italic">'
               f'{_h(seg.get("rationale","")[:80])}{"…" if len(seg.get("rationale",""))>80 else ""}'
               f'</span>' if seg.get("rationale") else '')
            + '</div>'
        )

        # Show up to 5 turns
        shown = turns[:5]
        for t in shown:
            sp    = t.get("speaker", "?")
            entry = speaker_map.get(
                sp, {"color": "#64748b", "bg": "#f8fafc", "initials_bg": "#e2e8f0"}
            )
            avatar = _speaker_avatar(sp, entry)
            text   = t.get("text", "")
            if len(text) > 220:
                text = text[:220] + "…"
            ts = _h(t.get("start_time", ""))
            parts.append(
                f'<div style="display:flex;gap:9px;padding:8px 14px;'
                f'background:white;border-bottom:1px solid #f1f5f9;'
                f'align-items:flex-start;font-family:system-ui,sans-serif">'
                f'{avatar}'
                f'<div style="flex:1;min-width:0">'
                f'<div style="display:flex;gap:8px;margin-bottom:2px;align-items:baseline">'
                f'<span style="font-weight:700;font-size:0.82em;color:{entry["color"]}">'
                f'{_h(sp)}</span>'
                f'<span style="font-size:0.7em;color:#94a3b8;font-family:monospace">{ts}</span>'
                f'<span style="font-size:0.68em;color:#cbd5e1;font-family:monospace">'
                f'#{t.get("turn_id","")}</span>'
                f'</div>'
                f'<div style="font-size:0.88em;color:#1e293b;line-height:1.6">{_h(text)}</div>'
                f'</div></div>'
            )

        if n_turns > 5:
            parts.append(
                f'<div style="padding:5px 14px;font-size:0.75em;color:#94a3b8;'
                f'background:#fafafa;border-bottom:1px solid #f1f5f9;font-style:italic">'
                f'β‹― {n_turns - 5} more turn{"s" if n_turns-5>1 else ""} in this episode</div>'
            )

        # Boundary marker before the next episode
        if i < len(segments) - 1 and turns:
            last_tid = turns[-1].get("turn_id", -1)
            b = bmap.get(last_tid, {})
            sig  = b.get("boundary_signal", "boundary")
            conf = b.get("confidence", "medium")
            rat  = b.get("rationale", "")
            tc, bg, bc = conf_colors.get(conf, conf_colors["medium"])
            parts.append(
                f'<div style="background:{bg};border-top:1px dashed {bc};'
                f'border-bottom:1px dashed {bc};padding:6px 14px;'
                f'display:flex;align-items:center;gap:8px;flex-wrap:wrap;'
                f'font-family:system-ui,sans-serif">'
                f'<span style="font-size:0.72em;font-weight:800;color:{tc};'
                f'text-transform:uppercase;letter-spacing:0.06em">━ boundary</span>'
                f'<span style="background:{tc}18;color:{tc};padding:1px 7px;'
                f'border-radius:4px;font-size:0.75em;font-weight:700">{_h(sig)}</span>'
                f'<span style="font-size:0.72em;color:{tc};font-weight:600">{conf} confidence</span>'
                + (f'<span style="font-size:0.72em;color:#64748b;font-style:italic">'
                   f'β€” {_h(rat[:100])}{"…" if len(rat)>100 else ""}</span>' if rat else '')
                + f'<span style="margin-left:auto;font-size:0.68em;color:#94a3b8;'
                f'font-family:monospace">after #{last_tid}</span>'
                f'</div>'
            )

    return (
        f'<div style="border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;'
        f'max-height:55vh;overflow-y:auto;font-family:system-ui,sans-serif">'
        + "".join(parts)
        + '</div>'
    )


def _agent_log_html(logs: list[dict]) -> str:
    if not logs:
        return (
            '<p style="font-size:0.8em;color:#94a3b8;font-style:italic">'
            'No agents have run yet.</p>'
        )
    parts = []
    for entry in reversed(logs[-4:]):
        agent   = _h(entry.get("agent", "?"))
        model   = _h(entry.get("model", "?").split("/")[-1])
        runtime = entry.get("runtime_s", "?")
        ts      = _h(entry.get("timestamp", ""))
        extras  = {k: v for k, v in entry.items()
                   if k not in ("agent", "model", "temperature", "runtime_s",
                                "timestamp", "system_prompt_preview", "user_prompt_preview")}
        extra_lines = "".join(
            f'<div style="display:flex;justify-content:space-between;font-size:0.78em">'
            f'<span style="color:#64748b">{_h(str(k))}</span>'
            f'<span style="font-weight:600">{_h(str(v))}</span></div>'
            for k, v in extras.items()
        )
        parts.append(
            f'<div style="border:1px solid #e2e8f0;border-radius:8px;'
            f'padding:10px 12px;margin-bottom:8px;background:white">'
            f'<div style="display:flex;justify-content:space-between;margin-bottom:4px">'
            f'<span style="font-weight:700;font-size:0.88em;color:#1e293b">{agent}</span>'
            f'<span style="font-size:0.72em;color:#94a3b8">{ts} Β· {runtime}s</span>'
            f'</div>'
            f'<div style="font-size:0.76em;color:#94a3b8">model: <strong style="color:#4338ca">{model}</strong></div>'
            f'{extra_lines}'
            f'</div>'
        )
    return "".join(parts)


def _make_log_entry(agent: str, runtime_s: float, **stats) -> dict:
    return {
        "agent":       agent,
        "model":       MODEL_ID,
        "temperature": TEMPERATURE,
        "runtime_s":   round(runtime_s, 1),
        "timestamp":   datetime.now(timezone.utc).strftime("%H:%M:%S"),
        **stats,
    }


def _coding_progress_html(state: dict) -> str:
    sections = state.get("sections", [])
    idx      = state.get("section_idx", 0)
    segs     = _current_section_segments(state)
    codings  = state.get("codings", {})
    cidx     = state.get("coding_idx", 0)
    if not segs:
        return ""
    coded  = sum(1 for s in segs if codings.get(s["segment_id"], {}).get("dimension_id"))
    total  = len(segs)
    pct    = int(coded / total * 100) if total else 0
    sec    = sections[idx] if idx < len(sections) else {}
    ep_num = min(cidx, total - 1) + 1
    # Total across all sections
    all_coded  = sum(1 for v in codings.values() if v.get("dimension_id"))
    all_segs   = sum(
        len(state.get("section_segments_coded", {}).get(s["section_id"], []))
        for s in sections
    )
    return (
        f'<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;'
        f'padding:12px 16px;margin-bottom:12px">'
        f'<div style="display:flex;justify-content:space-between;align-items:baseline;'
        f'margin-bottom:6px">'
        f'<div style="font-size:0.88em;font-weight:700;color:#1e293b">'
        f'Section {idx+1}/{len(sections)} β€” {_h(sec.get("label",""))}</div>'
        f'<div style="font-size:0.82em;color:#64748b">Episode {ep_num} of {total}</div>'
        f'</div>'
        f'<div style="height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden">'
        f'<div style="height:100%;width:{pct}%;background:#4338ca;border-radius:3px;'
        f'transition:width 0.3s"></div></div>'
        f'<div style="display:flex;justify-content:space-between;margin-top:4px;'
        f'font-size:0.75em;color:#94a3b8">'
        f'<span>{coded}/{total} episodes coded this section</span>'
        f'<span>{all_coded}/{all_segs} total</span>'
        f'</div>'
        f'</div>'
    )


# ===========================================================================
# STATE
# ===========================================================================

def _empty_state() -> dict:
    return {
        "session_id":             "",
        "researcher_id":          "",
        "turns":                  [],
        "speakers":               {},
        "sections":               [],
        "section_idx":            0,
        "section_stages":         {},
        "section_boundaries":     {},
        "section_segments":       {},
        "section_segments_coded": {},
        "coding_idx":             0,
        "codings":                {},
        "stage":                  "upload",
        "kappa_report":           None,
        "agent_logs":             [],
        "screener_result":        None,
        "ssrl_codings":           {},
    }


def _auto_session_id(researcher_id: str = "", source_name: str = "") -> str:
    stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
    base = (Path(source_name).stem or "drive").replace(" ", "_")
    rid  = (researcher_id or "R").strip().replace(" ", "_")
    return f"{rid}_{base}_{stamp}"


def _loading_card(title: str, subtitle: str = "Please wait…", spin: str = "◐") -> str:
    return (
        '<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:12px;'
        'padding:18px 20px;margin:10px 0;font-family:system-ui,sans-serif">'
        '<div style="display:flex;align-items:center;gap:12px">'
        f'<div style="font-size:1.35em;color:#1e3a8a">{spin}</div>'
        f'<div><div style="font-weight:800;color:#1e3a8a;font-size:1.02em">{_h(title)}</div>'
        f'<div style="margin-top:4px;font-size:0.86em;color:#475569">{_h(subtitle)}</div></div>'
        '</div></div>'
    )


def _session_dir(state: dict) -> Path:
    return SESSIONS_ROOT / state["session_id"]


def _current_section(state: dict) -> dict | None:
    secs = state.get("sections", [])
    idx  = state.get("section_idx", 0)
    return secs[idx] if secs and idx < len(secs) else None


def _current_section_segments(state: dict) -> list[dict]:
    sec = _current_section(state)
    return state["section_segments_coded"].get(sec["section_id"], []) if sec else []


def _turns_for_section(turns: list[dict], section: dict) -> list[dict]:
    return [t for t in turns
            if section["start_turn_id"] <= t["turn_id"] <= section["end_turn_id"]]


def _persist(state: dict) -> None:
    """Save state to local disk AND Drive (if Drive is configured)."""
    skip = {"turns", "kappa_report"}
    slim = {k: v for k, v in state.items() if k not in skip}
    # Local save (fast, always)
    try:
        d = _session_dir(state)
        d.mkdir(parents=True, exist_ok=True)
        (d / "app_state.json").write_text(
            json.dumps(slim, indent=2, ensure_ascii=False), encoding="utf-8"
        )
    except Exception:
        pass
    # Drive save (async-ish β€” run in background thread so UI isn't blocked)
    rid = state.get("researcher_id", "")
    sid = state.get("session_id", "")
    if rid and sid:
        def _drive_save():
            try:
                svc = get_drive_service(rid)
                if svc:
                    write_session_to_drive(svc, rid, sid, slim)
            except Exception as e:
                print(f"[Drive] Background save failed: {e}", file=_sys.stderr)
        import threading as _threading
        _threading.Thread(target=_drive_save, daemon=True).start()


def _seconds_to_hms(s: float) -> str:
    return str(timedelta(seconds=int(s)))


def _push_log(state: dict, entry: dict) -> dict:
    logs = list(state.get("agent_logs", []))
    logs.append(entry)
    state["agent_logs"] = logs[-10:]
    return state


# ===========================================================================
# CODING RENDER HELPERS
# ===========================================================================

def _segment_label(seg: dict, codings: dict) -> str:
    sid   = seg["segment_id"]
    ep    = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:]
    c     = codings.get(sid, {})
    did   = c.get("dimension_id") or seg.get("dimension_id") or "?"
    sec   = c.get("secondary_dimension_id")
    coded = "βœ“" if c.get("dimension_id") else "β—‹"
    flag  = " ⚠" if seg.get("uncertain") else ""
    multi = f"+{sec}" if sec else ""
    return f"{coded} ep{ep} [{did}{multi}]{flag}"


def _proposal_md(seg: dict) -> str:
    did     = seg.get("dimension_id", "?")
    rat     = seg.get("rationale", "")
    sec_did = seg.get("secondary_dimension_id")
    sec_rat = seg.get("secondary_rationale", "")
    lines   = [f"> **AI primary: {did}**  \n> {rat}"]
    if sec_did:
        lines.append(f"> **AI secondary: {sec_did}**  \n> _{sec_rat or 'co-occurring dimension'}_")
    tags = []
    if seg.get("confident"):
        tags.append("βœ… Confident")
    if seg.get("uncertain"):
        tags.append(f"⚠️ Uncertain β€” {seg.get('uncertainty_note', '')}")
    if sec_did:
        tags.append(f"πŸ”— Multi-dimensional: {did} + {sec_did}")
    return ("\n\n".join(lines) + ("\n\n" + "  ".join(tags) if tags else "")).strip()


CODING_EMPTY = (
    "",                                                 # 0  coding_progress_comp
    gr.update(choices=[], value=None),                  # 1  segment_jump
    "",                                                 # 2  turns_html_comp
    "",                                                 # 3  uncertainty_comp
    gr.update(value="", visible=False),                 # 4  proposal_comp
    gr.update(choices=DIM_CHOICES, value=None),         # 5  dim_radio
    "",                                                 # 6  dim_desc_comp
    gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), # 7  secondary_dim_drop
    "",                                                 # 8  comment_box
    gr.update(visible=False),                           # 9  next_section_btn
    gr.update(choices=SSRL_CHOICES, value=SSRL_NONE),   # 10 ssrl_radio
    gr.update(visible=False),                           # 11 ssrl_col β€” hidden when no D1-D9
)


def _render_coding(state: dict) -> tuple:
    segs        = _current_section_segments(state)
    codings     = state.get("codings", {})
    cidx        = state.get("coding_idx", 0)
    speaker_map = state.get("speakers", {})

    if not segs:
        return CODING_EMPTY

    seg      = segs[min(cidx, len(segs) - 1)]
    sid      = seg["segment_id"]
    existing = codings.get(sid, {})
    saved    = existing.get("dimension_id", "")
    choice   = next((c for c in DIM_CHOICES if c.startswith(saved)), None)

    saved_sec  = existing.get("secondary_dimension_id")
    sec_choice = (
        next((c for c in DIM_CHOICES if c.startswith(saved_sec)), SEC_NONE)
        if saved_sec else SEC_NONE
    )

    saved_ssrl  = existing.get("ssrl_phase")
    ssrl_choice = (
        next((c for c in SSRL_CHOICES if c.startswith(saved_ssrl)), SSRL_NONE)
        if saved_ssrl else SSRL_NONE
    )

    all_done = len(codings) >= len(segs) and all(
        codings.get(s["segment_id"], {}).get("dimension_id") for s in segs
    )
    labels = [_segment_label(s, codings) for s in segs]

    _skip_prefixes = ("NS", "NA", "None", "")
    show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes)

    return (
        _coding_progress_html(state),                                         # 0
        gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]),    # 1
        _format_turns_html(seg, speaker_map),                                 # 2
        _uncertainty_html(seg),                                               # 3
        gr.update(value=_proposal_md(seg), visible=False),                    # 4
        gr.update(choices=DIM_CHOICES, value=choice),                         # 5
        _dim_desc_html(choice or ""),                                         # 6
        gr.update(choices=SEC_DIM_CHOICES, value=sec_choice),                 # 7
        existing.get("comment", ""),                                          # 8
        gr.update(visible=all_done),                                          # 9
        gr.update(choices=SSRL_CHOICES, value=ssrl_choice),                   # 10
        gr.update(visible=show_ssrl),                                         # 11 ssrl_col
    )


# ===========================================================================
# PAGE NAVIGATION HELPER
# ===========================================================================

_PAGE_NAMES = ["welcome", "setup", "screener", "sections", "pipeline",
               "done", "agreement", "library", "lexicon"]

def _show(page: str) -> list:
    """Return 9 gr.update(visible=...) items, one per page."""
    return [gr.update(visible=(p == page)) for p in _PAGE_NAMES]


# ===========================================================================
# CALLBACKS
# ===========================================================================

# ── Process: Parse + Agent 0 combined ────────────────────────────────────────

def _parse_drive_choice(choice: str) -> tuple[str, str]:
    if not choice or "::" not in choice:
        raise gr.Error("Pick a transcript from Drive first.")
    file_id, file_name = choice.split("::", 1)
    return file_id, file_name


def fn_refresh_drive_transcripts(researcher_id: str):
    rid = (researcher_id or "").strip()
    if not rid:
        return (
            gr.update(choices=[], value=None, interactive=False),
            _status_card("Enter Researcher ID first, then refresh Drive files.", "warning"),
        )

    register_researcher(rid)
    try:
        service = get_drive_service(rid)
        if not service:
            return (
                gr.update(choices=[], value=None, interactive=False),
                _status_card(
                    "Google Drive is not configured yet.",
                    "warning",
                    {
                        "Needed secret": "GOOGLE_SERVICE_ACCOUNT_JSON",
                        "Folder ID": "GOOGLE_DRIVE_FOLDER_ID",
                        "Tip": "Copy the DRIVE DEBUG block from the logs if this should already be working.",
                    },
                ),
            )

        files = list_transcripts(service)
        if not files:
            return (
                gr.update(choices=[], value=None, interactive=False),
                _status_card(
                    "No transcript files found in the configured Drive folder.",
                    "warning",
                    {"Tip": "If this is unexpected, copy the DRIVE DEBUG block from the logs."},
                ),
            )

        choices = [
            (f"{f['name']} Β· {f.get('modified_time', '')[:10]}", f"{f['id']}::{f['name']}")
            for f in files
        ]
        return (
            gr.update(choices=choices, value=choices[0][1], interactive=True),
            _status_card("Drive connected. Select a transcript and click Process.", "success", {"Files": len(choices)}),
        )
    except Exception as e:
        diag = format_drive_diagnostic("refresh_drive_transcripts", researcher_id=rid, error=e)
        print(diag, file=_sys.stderr)
        return (
            gr.update(choices=[], value=None, interactive=False),
            _status_card(
                "Drive check failed.",
                "error",
                {"Tip": "Copy the DRIVE DEBUG block below and send it with the issue."},
                diag,
            ),
        )


def fn_load_previous_session(researcher_id: str, state: dict):
    """
    Generator: load saved session from Drive, re-parse transcript, navigate to screener.
    Outputs: PARSE_OUTPUTS (state, pipeline_bar_html, process_status, process_btn,
             screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES)
    """
    rid = (researcher_id or "").strip()

    def _bail(msg: str, kind: str = "warning"):
        yield (state, _pipeline_bar_html(state),
               _status_card(msg, kind), _BTN_FREE,
               "", "", gr.update(visible=False), *_show("setup"))

    if not rid:
        yield from _bail("Enter Researcher ID first.")
        return

    # ── Step 1: initial feedback ──────────────────────────────────────────────
    yield (state, _pipeline_bar_html(state),
           _status_card("Connecting to Drive…", "info"), _BTN_BUSY,
           "", "", gr.update(visible=False), *_show("setup"))

    try:
        service = get_drive_service(rid)
    except Exception as e:
        yield from _bail(f"Drive connection failed: {e}", "error")
        return

    if not service:
        yield from _bail("Drive not configured β€” check GOOGLE_CREDENTIALS.", "warning")
        return

    # ── Step 2: load saved state ──────────────────────────────────────────────
    yield (state, _pipeline_bar_html(state),
           _status_card("Loading saved session…", "info"), _BTN_BUSY,
           "", "", gr.update(visible=False), *_show("setup"))

    try:
        loaded = load_session_from_drive(service, rid)
    except Exception as e:
        diag = format_drive_diagnostic("load_previous_session", researcher_id=rid, error=e)
        print(diag, file=_sys.stderr)
        yield from _bail(f"Could not load Drive session: {e}", "error")
        return

    if not loaded:
        yield from _bail("No previous session found for this researcher ID.", "warning")
        return

    new_state = _empty_state()
    new_state.update(loaded)
    new_state["researcher_id"] = rid
    sid = new_state.get("session_id") or _auto_session_id(rid, "restored_session")
    new_state["session_id"] = sid

    # ── Step 3: re-parse transcript to restore `turns` ────────────────────────
    drive_file_id   = new_state.get("_drive_file_id")
    source_name     = new_state.get("_source_file_name", "transcript.vtt")

    if drive_file_id:
        yield (new_state, _pipeline_bar_html(new_state),
               _status_card(f"Re-parsing '{source_name}' to restore transcript…", "info"),
               _BTN_BUSY, "", "", gr.update(visible=False), *_show("setup"))
        try:
            text   = read_file_from_drive(service, drive_file_id)
            suffix = Path(source_name).suffix or ".vtt"
            tmp    = Path(tempfile.mktemp(suffix=suffix))
            tmp.write_text(text, encoding="utf-8")
            parsed = parse_transcript(str(tmp))
            new_state["turns"]    = parsed.get("turns", [])
            new_state["speakers"] = parsed.get("speakers", new_state.get("speakers", {}))
            try:
                tmp.unlink()
            except Exception:
                pass
        except Exception as e:
            yield from _bail(
                f"Could not re-parse transcript: {e}. "
                "Re-upload the file manually to continue.", "warning"
            )
            return
    else:
        # No file_id stored (old session or local upload) β€” warn, turns unavailable
        gr.Warning("Transcript not available for re-parsing β€” turns will be missing. "
                   "Re-upload the file to restore the full view.")

    # ── Step 4: build resume summary card ────────────────────────────────────
    n_turns    = len(new_state.get("turns", []))
    n_sections = len(new_state.get("sections", []))
    n_codings  = len(new_state.get("codings", {}))
    stage_map  = {
        "complete":   "All sections coded βœ“",
        "coding":     "Coding in progress",
        "sectioned":  "Sections detected, boundaries pending",
        "parsed":     "Transcript parsed, screener run",
    }
    stage_label = stage_map.get(new_state.get("stage", ""), "Screener complete")

    sum_html = (
        '<div style="background:#f0fdf4;border:2px solid #86efac;border-radius:10px;'
        'padding:16px;font-family:system-ui,sans-serif">'
        '<div style="font-weight:700;color:#166534;font-size:1.05em;margin-bottom:10px">'
        'βœ“ Session Resumed</div>'
        '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:10px">'
        f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_turns}</div>'
        '<div style="font-size:0.75em;color:#4b5563">Turns</div></div>'
        f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_sections}</div>'
        '<div style="font-size:0.75em;color:#4b5563">Sections</div></div>'
        f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_codings}</div>'
        '<div style="font-size:0.75em;color:#4b5563">Episodes coded</div></div>'
        '</div>'
        f'<div style="font-size:0.85em;color:#374151">Stage: <strong>{stage_label}</strong>'
        f' Β· Session: <code style="background:#dcfce7;padding:1px 5px;border-radius:3px">{sid}</code></div>'
        '<div style="margin-top:8px;font-size:0.78em;color:#6b7280">'
        'Click <strong>Detect Sections β†’</strong> to continue β€” sections and boundaries '
        'are loaded from your saved session (no LLM re-run).</div>'
        '</div>'
    )

    gr.Info(f"Session resumed: {n_sections} sections Β· {n_codings} episodes coded.")

    yield (
        new_state,
        _pipeline_bar_html(new_state),
        _status_card(f"Session loaded Β· {n_turns} turns Β· {n_sections} sections Β· {n_codings} coded",
                     "success", {"Session": sid}),
        _BTN_FREE,
        sum_html,
        "",                       # screener_turns_html_c (no turn detail on resume)
        gr.update(visible=True),  # screener_to_sections_btn β€” clicking uses cached sections
        *_show("screener"),
    )


def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict):
    """Wrapper: Drive-only transcript selection with automatic session IDs."""
    temp_path: Path | None = None
    service = None
    rid = (researcher_id or "").strip()
    if not rid:
        raise gr.Error("Enter your Researcher ID first.")
    if not drive_choice:
        raise gr.Error("Choose a transcript from Drive first.")

    try:
        service = get_drive_service(rid)
        if not service:
            diag = format_drive_diagnostic("process_drive_file", researcher_id=rid)
            print(diag, file=_sys.stderr)
            raise gr.Error("Drive is not configured. Copy the DRIVE DEBUG block from the logs.")

        file_id, file_name = _parse_drive_choice(drive_choice)
        session_id = _auto_session_id(rid, file_name)
        text = read_file_from_drive(service, file_id)
        suffix = Path(file_name).suffix or ".txt"
        temp_path = Path(tempfile.mktemp(prefix="drive_transcript_", suffix=suffix))
        temp_path.write_text(text, encoding="utf-8")

        # Store Drive source so we can re-parse on session resume
        state = dict(state)
        state["_drive_file_id"]    = file_id
        state["_source_file_name"] = file_name

        effective_file = type("DriveFile", (), {"name": str(temp_path)})()
    except gr.Error:
        raise
    except Exception as e:
        file_id, file_name = ("", "")
        try:
            file_id, file_name = _parse_drive_choice(drive_choice)
        except Exception:
            pass
        diag = format_drive_diagnostic(
            "process_drive_file",
            researcher_id=rid,
            file_id=file_id,
            file_name=file_name,
            error=e,
        )
        print(diag, file=_sys.stderr)
        raise gr.Error("Drive file could not be read. Copy the DRIVE DEBUG block from the logs.")

    final_state: dict | None = None
    try:
        for out in fn_parse_transcript(effective_file, session_id, researcher_id, state):
            if isinstance(out, tuple) and out and isinstance(out[0], dict):
                final_state = out[0]
            yield out
    finally:
        if temp_path and temp_path.exists():
            try:
                temp_path.unlink()
            except Exception:
                pass

    # Persist lightweight state snapshot to Drive for resume.
    if final_state and (service or get_drive_service(rid)):
        try:
            svc = service or get_drive_service(rid)
            if svc:
                slim = {k: v for k, v in final_state.items() if k not in {"turns", "kappa_report"}}
                write_session_to_drive(
                    svc,
                    final_state.get("researcher_id", rid),
                    final_state.get("session_id", session_id),
                    slim,
                )
        except Exception:
            pass


def fn_parse_transcript(file_obj, session_id: str, researcher_id: str, state: dict):
    """
    Phase 1 β€” Generator: parse transcript, auto-run screener, navigate to screener page.
    Outputs: state, pipeline_bar_html, process_status, process_btn,
             screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES
    """
    if file_obj is None:
        raise gr.Error("Choose a transcript first.")
    if not researcher_id.strip():
        raise gr.Error("Enter your Researcher ID (e.g. R1).")
    session_id = session_id.strip() or _auto_session_id(
        researcher_id, getattr(file_obj, "name", "transcript")
    )
    rid = researcher_id.strip()

    _BTN_BUSY = gr.update(interactive=False, value="⏳ Processing…")
    _BTN_FREE = gr.update(interactive=True,  value="Process Drive Transcript β†’")

    def _parse_yield(msg, status="processing", details=None, btn=None, nav="setup"):
        return (
            state,
            _pipeline_bar_html(state),
            _status_card(msg, status, details),
            btn if btn is not None else _BTN_BUSY,
            "",                       # screener_summary_html
            "",                       # screener_turns_html_c
            gr.update(visible=False), # screener_to_sections_btn
            *_show(nav),
        )

    yield _parse_yield("Parsing transcript…")

    try:
        turns = parse_transcript(file_obj.name)
    except Exception as e:
        raise gr.Error(f"Could not parse transcript: {e}") from e

    if len(turns) < 5:
        raise gr.Error(f"Only {len(turns)} turns found β€” check the transcript format.")

    speaker_map = _assign_speakers(turns)
    speakers    = list(speaker_map.keys())
    duration    = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"])

    new_state = _empty_state()
    new_state.update({
        "session_id":    session_id,
        "researcher_id": rid,
        "turns":         turns,
        "speakers":      speaker_map,
        "stage":         "upload",
    })

    d = SESSIONS_ROOT / session_id
    d.mkdir(parents=True, exist_ok=True)
    (d / "parsed_turns.json").write_text(
        json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8"
    )

    yield _parse_yield(
        f"Running pre-screen on {len(turns)} turns…",
        details={"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration},
    )

    # ── Auto-run screener (pre-LLM, fast) ────────────────────────────────────
    screener_ok = False
    try:
        result = screen_transcript(turns)
        rd     = result_to_dict(result)
        new_state["screener_result"] = rd
        new_state["stage"] = "screened"
        n_wins   = len(rd["candidate_windows"])
        savings  = f"{rd['estimated_llm_savings']:.0%}"
        sum_html   = _screener_summary_html(rd)
        turns_html = _screener_turns_html(rd, speaker_map)
        screener_ok = True
    except Exception as e:
        sum_html   = (
            f'<div style="background:#fffbeb;border:1px solid #fde68a;border-radius:8px;'
            f'padding:14px 16px;color:#92400e;font-size:0.9em">'
            f'<strong>Screener could not run automatically.</strong><br>'
            f'Error: {html_lib.escape(str(e))}<br>'
            f'Click <em>Re-run Screener</em> below to try again, '
            f'or click <em>Detect Sections β†’</em> to continue without screening.</div>'
        )
        turns_html = ""

    yield (
        new_state,
        _pipeline_bar_html(new_state),
        _status_card(
            f"Parsed {len(turns)} turns Β· {len(speakers)} speaker(s).",
            "success",
            {"Session": session_id, "Turns": len(turns), "Speakers": ", ".join(speakers)},
        ),
        _BTN_FREE,
        sum_html,                              # screener_summary_html
        turns_html,                            # screener_turns_html_c
        gr.update(visible=True),               # screener_to_sections_btn β€” always show
        *_show("screener"),
    )


def fn_run_agent0(state: dict):
    """
    Phase 2 β€” Generator: run Agent 0 on parsed turns, navigate to sections.
    Triggered by 'Continue to Sections' button on screener page.
    Outputs: state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES
    """
    reset_circuit()  # fresh start β€” don't carry over failures from a previous run
    turns = state.get("turns", [])
    if not turns:
        raise gr.Error("No transcript loaded β€” process a file first.")

    # ── Sections cache: if Agent 0 already ran, skip LLM and go to sections ─
    existing_sections = state.get("sections", [])
    if existing_sections:
        n_t        = len(turns)
        speakers   = list(state.get("speakers", {}).keys())
        sec_html   = _sections_html(existing_sections, n_t, 0, len(speakers), all_turns=turns)
        labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in existing_sections)
        gr.Info(f"Using cached sections ({len(existing_sections)} detected). Re-run via Back if you need fresh detection.")
        yield (
            state,
            _pipeline_bar_html(state),
            sec_html,
            labels_txt,
            *_show("sections"),
        )
        return

    session_id = state.get("session_id", "")
    n_t        = len(turns)
    if n_t > 600:
        tok_per_turn = 9;  effective_turns = n_t // 2
    elif n_t > 400:
        tok_per_turn = 12; effective_turns = n_t
    elif n_t > 200:
        tok_per_turn = 16; effective_turns = n_t
    else:
        tok_per_turn = 22; effective_turns = n_t
    est_in_tok  = effective_turns * tok_per_turn + 700
    est_out_tok = 900
    est_timeout = max(45, int((est_in_tok + est_out_tok) / 35 + 20))

    def _hb(elapsed: int, spin_i: int):
        return (
            state,
            _pipeline_bar_html(state),
            _llm_progress_html(
                f"Agent 0 β€” Structural Segmenter: analysing {n_t} turns…",
                elapsed, est_timeout, est_in_tok, circuit_state(), spin_i,
            ),
            "",  # sections_labels_box
            *_show("screener"),
        )

    yield _hb(0, 0)

    result_q: _queue.Queue = _queue.Queue()

    def _run_a0():
        try:
            res = run_sectioning(turns=turns, session_id=session_id)
            result_q.put(("ok", res))
        except Exception as exc:
            result_q.put(("err", exc))

    thread = threading.Thread(target=_run_a0, daemon=True)
    thread.start()
    t_llm  = time.perf_counter()
    spin_i = 1

    while thread.is_alive():
        time.sleep(2)
        elapsed = int(time.perf_counter() - t_llm)
        yield _hb(elapsed, spin_i)
        spin_i += 1

    outcome, payload = result_q.get()
    if outcome == "err":
        raise gr.Error(f"Section detection failed: {payload}") from payload

    result   = payload
    sections = result["sections"]
    if not sections:
        raise gr.Error("Agent 0 returned no sections β€” try again.")

    from agent0_sectioner import build_system_prompt, load_dimension_labels
    agent0_rt = round(time.perf_counter() - t_llm, 1)

    new_state = dict(state)
    new_state.update({
        "sections":         sections,
        "section_stages":   {s["section_id"]: "pending" for s in sections},
        "stage":            "sectioned",
        "_agent0_overview": result.get("session_overview", ""),
    })
    log_entry = _make_log_entry(
        "Agent 0 β€” Structural Segmenter", agent0_rt,
        sections_proposed=len(sections),
        warnings=len(result.get("warnings", [])),
        system_prompt_preview=build_system_prompt(load_dimension_labels())[:120],
    )
    new_state = _push_log(new_state, log_entry)

    d = SESSIONS_ROOT / session_id
    d.mkdir(parents=True, exist_ok=True)
    (d / "sections_proposed.json").write_text(
        json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8"
    )

    overview   = result.get("session_overview", "")
    speakers   = list(state.get("speakers", {}).keys())
    sec_html   = _sections_html(sections, n_t, agent0_rt, len(speakers), all_turns=turns)
    labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in sections)

    if result.get("warnings"):
        gr.Warning("Coverage warnings β€” check the section table.")
    gr.Info(f"Ready: {n_t} turns Β· {len(sections)} sections detected in {agent0_rt}s.")

    yield (
        new_state,
        _pipeline_bar_html(new_state),
        sec_html,
        labels_txt,
        *_show("sections"),
    )


# ── Legacy wrapper kept for Drive flow ────────────────────────────────────────

def fn_process(file_obj, session_id: str, researcher_id: str, state: dict):
    """Alias β†’ fn_parse_transcript (Drive flow calls this via fn_process_with_source)."""
    yield from fn_parse_transcript(file_obj, session_id, researcher_id, state)


# ── Local file upload (new, no Drive needed) ──────────────────────────────────

def fn_process_local(file, researcher_id: str, state: dict):
    """
    Generator: load a local .txt/.vtt/.csv transcript, run screener, navigate to screener.
    Outputs match PARSE_OUTPUTS.
    """
    rid = (researcher_id or "").strip()
    if not file:
        raise gr.Error("Select a local transcript file first.")
    if not rid:
        raise gr.Error("Enter your Researcher ID first.")

    path      = Path(file.name) if hasattr(file, "name") else Path(str(file))
    sid       = _auto_session_id(rid, path.stem)
    file_mock = type("F", (), {"name": str(path)})()

    yield from fn_parse_transcript(file_mock, sid, rid, state)


# ── Original fn_process body (kept below for Drive fn_process_with_source) ───

# ── Confirm sections ──────────────────────────────────────────────────────────

def fn_confirm_sections(labels_text: str, state: dict):
    """
    Generator: immediately shows a 'confirming' state (so the user knows
    their click registered), then navigates to the pipeline page.
    """
    sections = state.get("sections", [])
    if not sections:
        raise gr.Error("No sections to confirm β€” process a transcript first.")

    _BUSY_HTML = (
        '<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:10px;'
        'padding:14px 18px;font-family:system-ui,sans-serif">'
        '<div style="display:flex;align-items:center;gap:10px">'
        '<span style="font-size:1.2em">β—‘</span>'
        '<strong style="color:#1e3a8a">Saving section labels and loading pipeline…</strong>'
        '</div>'
        '<div style="margin-top:8px;font-size:0.82em;color:#4b5563">'
        'Please wait β€” this takes only a moment.'
        '</div></div>'
    )

    # ── Yield 1: immediate feedback, stay on sections page ────────────────────
    yield (
        state,
        *_show("sections"),
        gr.update(value=_BUSY_HTML),                       # sections_display_html
        gr.update(interactive=False, value="⏳ Saving…"),  # confirm_sections_btn
        gr.update(visible=True),                           # col_run_all_boundaries (Column β€” visible only)
        gr.update(visible=False),                          # col_boundary_review
        gr.update(visible=False),                          # col_coding
    )

    # ── Process (fast: no LLM, just in-memory + disk) ─────────────────────────
    # Parse "s01: My Label" or plain "My Label" (both accepted)
    raw_lines = [l.strip() for l in labels_text.strip().splitlines() if l.strip()]
    labels = []
    for line in raw_lines:
        # Strip "sXX: " or "sXX:" prefix if present
        if ":" in line:
            prefix, _, rest = line.partition(":")
            if prefix.strip().lower().startswith("s") and prefix.strip()[1:].isdigit():
                labels.append(rest.strip())
                continue
        labels.append(line)

    confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"])
                 for i, s in enumerate(sections)]

    if len(labels) != len(sections):
        gr.Warning(
            f"Label count mismatch ({len(labels)} labels for {len(sections)} sections) β€” "
            f"AI labels used for any extras."
        )

    new_state = dict(state)
    new_state.update({
        "sections":            confirmed,
        "section_idx":         0,
        "section_stages":      {s["section_id"]: "pending" for s in confirmed},
        "section_a1a_results": {},
        "stage":               "coding",
    })

    d = _session_dir(new_state)
    (d / "sections_confirmed.json").write_text(
        json.dumps(confirmed, indent=2, ensure_ascii=False), encoding="utf-8"
    )
    _persist(new_state)

    gr.Info(f"{len(confirmed)} sections confirmed. Click 'Detect Episode Boundaries' to continue.")
    print(f"[Confirm Sections] {len(confirmed)} sections saved for session {new_state['session_id']}")

    # ── Yield 2: navigate to pipeline page ────────────────────────────────────
    yield (
        new_state,
        *_show("pipeline"),
        gr.update(value=""),                                     # sections_display_html (leaving)
        gr.update(interactive=True, value="Confirm Sections β†’"), # reset button for if user navigates back
        gr.update(visible=True),   # col_run_all_boundaries
        gr.update(visible=False),  # col_boundary_review
        gr.update(visible=False),  # col_coding
    )


# ── Agent 1a β€” parallel boundary detection ───────────────────────────────────

def fn_run_all_boundaries(state: dict):
    reset_circuit()  # fresh start for this pipeline step
    sections = state.get("sections", [])
    if not sections:
        raise gr.Error("Confirm sections first.")
    if not state.get("turns"):
        raise gr.Error("No parsed turns β€” parse the transcript first.")

    # ── Cache check: if all sections already have boundaries, skip LLM ───────
    existing = state.get("section_a1a_results", {})
    if existing and all(s["section_id"] in existing for s in sections):
        collected = {sid: r for sid, r in existing.items()}
        # Jump straight to showing first section review
        sec     = sections[0]
        turns   = _turns_for_section(state["turns"], sec)
        result  = collected.get(sec["section_id"], {})
        bounds  = result.get("boundaries", [])
        ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)
        yield (
            state,
            "βœ“ Episode boundaries already detected β€” showing cached results.",
            "",
            gr.update(visible=False),
            gr.update(visible=True,  value=_episode_table_html(turns, bounds)),
            gr.update(visible=True,  value=ids_txt),
            _section_header_md(sec),
            _agent_log_html(state.get("agent_logs", [])),
            "",
            gr.update(value=_episode_dialogue_html(turns, bounds)),
        )
        return

    n                = len(sections)
    session_overview = state.get("_agent0_overview", "")
    collected        = {}
    pipeline_stats_html = ""

    def _a1a_banner(done: int, total: int, status: str = "running") -> str:
        pct   = int(done / total * 100) if total else 0
        color = "#4338ca" if status == "running" else "#065f46" if status == "done" else "#be123c"
        icon  = "⏳" if status == "running" else "βœ“" if status == "done" else "βœ—"
        return (
            f'<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:10px;'
            f'padding:12px 16px;font-family:system-ui,sans-serif">'
            f'<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">'
            f'<span>{icon}</span>'
            f'<strong style="color:#1e3a8a;font-size:0.9em">Agent 1a β€” Boundary Detector</strong>'
            f'<span style="margin-left:auto;font-size:0.78em;color:#6b7280">'
            f'{done}/{total} sections Β· {pct}%</span>'
            f'</div>'
            f'<div style="background:#dbeafe;border-radius:4px;height:7px;overflow:hidden">'
            f'<div style="height:100%;width:{pct}%;background:{color};border-radius:4px;'
            f'transition:width 0.4s"></div></div>'
            f'<div style="margin-top:6px;font-size:0.77em;color:#4b5563">'
            f'Parallel map pattern (Dean &amp; Ghemawat 2004) Β· '
            f'Basis: Schegloff (2007) adjacency pairs Β· '
            f'Krippendorff (2004) unitising precedes categorising'
            f'</div></div>'
        )

    # Initial yield β€” show banner immediately
    yield (
        state,
        f"⏳ Running Agent 1a on {n} section(s) (max 3 concurrent)…",
        "",
        gr.update(visible=False),
        gr.update(visible=False, value=""),
        gr.update(visible=False, value=""),
        "",
        _agent_log_html(state.get("agent_logs", [])),
        _a1a_banner(0, n, "running"),
        gr.update(value=""),  # episode_dialogue_html β€” clear while processing
    )

    pstats = PipelineStats(agent_name="Agent 1a β€” Boundary Detector", n_sections=n)

    try:
        for sr, pstats in run_boundaries_parallel(
            sections=sections,
            all_turns=state["turns"],
            session_id=state["session_id"],
            session_overview=session_overview,
        ):
            if sr.success:
                collected[sr.section_id] = sr.result
            else:
                gr.Warning(f"Section {sr.section_id} failed: {sr.error}")

            processed = len(pstats.results)
            failed_sids = {x.section_id for x in pstats.results if not x.success}
            prog_lines = []
            for s in sections:
                sid = s["section_id"]
                res = collected.get(sid)
                failed = sid in failed_sids
                if res:
                    b = len(res.get("boundaries", []))
                    e = len(res.get("segments", []))
                    prog_lines.append(f"βœ“ **{sid}** {s['label']} β€” {b} boundaries β†’ {e} episodes")
                elif failed:
                    prog_lines.append(f"βœ— **{sid}** {s['label']} β€” ERROR")
                else:
                    prog_lines.append(f"⏳ **{sid}** {s['label']}…")

            status_md = f"**{processed}/{n} sections complete**\n\n" + "\n\n".join(prog_lines)
            pipeline_stats_html = render_pipeline_stats_html(pstats)

            yield (
                state,
                status_md,
                pipeline_stats_html,
                gr.update(visible=False),
                gr.update(visible=False, value=""),
                gr.update(visible=False, value=""),
                "",
                _agent_log_html(state.get("agent_logs", [])),
                _a1a_banner(processed, n, "running"),
                gr.update(value=""),  # episode_dialogue_html β€” still processing
            )

    except Exception as e:
        raise gr.Error(f"Parallel boundary detection failed: {e}") from e

    # All done β€” update state
    state = dict(state)
    n_success = len(collected)
    n_error   = n - n_success

    for sec in sections:
        sid    = sec["section_id"]
        result = collected.get(sid)
        if result:
            state["section_boundaries"][sid] = result["boundaries"]
            state["section_segments"][sid]   = result["segments"]
            state["section_stages"][sid]     = "boundaries"
            state.setdefault("section_a1a_results", {})[sid] = result
        else:
            state["section_stages"][sid] = "error"

    log = _make_log_entry(
        "Agent 1a β€” Boundary Detector (parallel)", round(pstats.parallel_wall_s, 1),
        sections_ok=n_success, sections_error=n_error,
        speedup=f"{pstats.speedup:.1f}x",
        total_est_tokens=pstats.total_estimated_tokens,
    )
    state = _push_log(state, log)
    _persist(state)

    sec     = sections[0]
    turns   = _turns_for_section(state["turns"], sec)
    result  = collected.get(sec["section_id"], {})
    bounds  = result.get("boundaries", [])
    ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)

    status_final = (
        f"βœ“ {n_success}/{n} sections analysed "
        f"({pstats.parallel_wall_s:.0f}s parallel Β· {pstats.speedup:.1f}Γ— speedup).\n\n"
        f"Review boundaries for each section below, then confirm to start coding."
    )
    if n_error:
        status_final += f"\n\n⚠ {n_error} section(s) failed β€” enter boundary turn IDs manually."

    gr.Info(f"Parallel analysis complete: {n_success}/{n} sections OK.")
    print(f"[Agent 1a] Complete: {n_success}/{n} OK in {pstats.parallel_wall_s:.1f}s "
          f"({pstats.speedup:.1f}Γ— speedup)")

    # Build dialogue view for the first section to review
    first_result  = collected.get(sec["section_id"], {})
    first_segs    = first_result.get("segments", [])
    ep_dial_html  = _episode_dialogue_html(first_segs, bounds, state["speakers"])

    yield (
        state,
        status_final,
        pipeline_stats_html,
        gr.update(visible=True),
        gr.update(visible=True, value=_episode_table_html(turns, bounds)),
        gr.update(visible=True, value=ids_txt),
        f"### Reviewing: {sec['label']}  ({sec['section_id']})",
        _agent_log_html(state["agent_logs"]),
        _a1a_banner(n_success, n, "done" if n_error == 0 else "error"),
        ep_dial_html,  # full dialogue view β€” researcher reads this before confirming
    )


# ── Confirm boundaries + run Agent 1b ────────────────────────────────────────

def fn_confirm_and_code(boundary_ids_text: str, state: dict):
    sec = _current_section(state)
    if not sec:
        raise gr.Error("No section loaded.")

    session_id = state.get("session_id") or _auto_session_id(state.get("researcher_id", ""), sec.get("label", "section"))
    state = dict(state)
    state["session_id"] = session_id

    turns     = _turns_for_section(state["turns"], sec)
    valid_ids = {t["turn_id"] for t in turns}
    boundaries: list[dict] = []

    for tok in boundary_ids_text.split(","):
        tok = tok.strip()
        if not tok:
            continue
        try:
            tid = int(tok)
        except ValueError:
            raise gr.Error(f"'{tok}' is not a valid turn ID.")
        if tid not in valid_ids:
            raise gr.Error(
                f"Turn {tid} is outside this section "
                f"(valid: {min(valid_ids)}–{max(valid_ids)})."
            )
        boundaries.append({"boundary_id": f"r_{tid}", "after_turn_id": tid,
                           "confidence": "high", "boundary_signal": "researcher_defined",
                           "rationale": "Set by researcher."})
    boundaries.sort(key=lambda b: b["after_turn_id"])
    segments = boundaries_to_segments(sec, turns, boundaries, session_id)

    if not segments:
        raise gr.Error("No segments produced β€” check your boundary turn IDs.")

    # ── Min-episode guard: merge segments with < 2 turns into the next one ───
    _MIN_TURNS = 2
    merged: list[dict] = []
    pending_turns: list = []
    for seg in segments:
        seg_turns = seg.get("turns", [])
        combined  = pending_turns + seg_turns
        pending_turns = []
        if len(combined) < _MIN_TURNS:
            pending_turns = combined   # carry forward, merge into next
        else:
            if merged:
                seg["turns"] = combined
            else:
                seg["turns"] = combined
            merged.append(seg)
    # Any remaining tiny tail β€” append to last segment
    if pending_turns and merged:
        merged[-1]["turns"] = merged[-1].get("turns", []) + pending_turns
    elif pending_turns:
        merged = [{"turns": pending_turns, "segment_id": "s_merged",
                   "label": "Merged", "section_id": sec["section_id"]}]
    segments = merged if merged else segments
    if not segments:
        raise gr.Error("No segments produced after merging short episodes.")

    state["section_boundaries"][sec["section_id"]] = boundaries
    state["section_segments"][sec["section_id"]]   = segments

    # ── Agent 1b cache: if proposals already exist for this section, skip LLM ─
    cached_coded = state.get("section_segments_coded", {}).get(sec["section_id"])
    if cached_coded:
        state["section_stages"][sec["section_id"]] = "coding"
        state["coding_idx"]                         = 0
        n_uncertain = sum(1 for s in cached_coded if s.get("uncertain"))
        msg = f"βœ“ {len(cached_coded)} episodes (cached β€” no LLM re-run)."
        if n_uncertain:
            msg += f" **{n_uncertain} flagged ⚠**"
        gr.Info(f"Using cached Agent 1b proposals ({len(cached_coded)} episodes).")
        yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state.get("agent_logs", []))
        return

    yield (
        state,
        _loading_card("Loading coding stage…", f"Agent 1b is preparing {len(segments)} episode(s) for coding."),
        gr.update(visible=False),
        *CODING_EMPTY,
        "",
    )

    agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"])
    t0 = time.perf_counter()
    try:
        coded, llm_stats = run_coding_with_context(
            section=sec,
            segments=segments,
            agent1a_result=agent1a_result,
        )
    except Exception as e:
        raise gr.Error(f"Agent 1b failed: {e}") from e

    rt = round(time.perf_counter() - t0, 1)
    n_uncertain = sum(1 for s in coded if s.get("uncertain"))
    state["section_segments_coded"][sec["section_id"]] = coded
    state["section_stages"][sec["section_id"]]         = "coding"
    state["coding_idx"]                                = 0
    log = _make_log_entry(
        "Agent 1b β€” Dimension Coder", rt,
        segments_coded=len(coded),
        uncertain_flagged=n_uncertain,
        system_prompt_preview=f"Context chain: section={sec['label']}",
        user_prompt_preview=f"Code {len(segments)} segments",
    )
    state = _push_log(state, log)

    d = _session_dir(state)
    (d / f"segments_{sec['section_id']}.json").write_text(
        json.dumps(coded, indent=2, ensure_ascii=False), encoding="utf-8"
    )

    msg = f"βœ“ {len(coded)} segments coded ({rt}s)."
    if n_uncertain:
        msg += f" **{n_uncertain} flagged ⚠ β€” review these first.**"
    gr.Info(f"{len(coded)} segments coded. {n_uncertain} uncertain.")

    yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state["agent_logs"])


# ── Navigate segments ─────────────────────────────────────────────────────────

def fn_navigate(direction: int, dim_choice: str, sec_choice: str, comment: str,
                ssrl_choice: str, state: dict):
    segs    = _current_section_segments(state)
    if not segs:
        return state, *_render_coding(state)
    idx     = state.get("coding_idx", 0)
    codings = dict(state.get("codings", {}))
    sid     = segs[idx]["segment_id"]
    if dim_choice:
        codings[sid] = {
            "dimension_id":          DIM_ID_FROM_CHOICE[dim_choice],
            "secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),
            "comment":               comment.strip(),
            "ssrl_phase":            SSRL_ID_FROM_CHOICE.get(ssrl_choice or SSRL_NONE),
        }
    state               = dict(state)
    state["codings"]    = codings
    state["coding_idx"] = max(0, min(idx + direction, len(segs) - 1))
    return state, *_render_coding(state)


def fn_jump(label: str, state: dict):
    segs = _current_section_segments(state)
    if not segs or not label:
        return state, *_render_coding(state)
    codings = state.get("codings", {})
    labels  = [_segment_label(s, codings) for s in segs]
    state   = dict(state)
    if label in labels:
        state["coding_idx"] = labels.index(label)
    return state, *_render_coding(state)


def fn_reveal(state: dict):
    segs = _current_section_segments(state)
    if not segs:
        return gr.update(visible=False)
    seg = segs[min(state.get("coding_idx", 0), len(segs) - 1)]
    return gr.update(value=_proposal_md(seg), visible=True)


def fn_dim_desc(choice: str):
    """Return dim description HTML + SSRL visibility update."""
    desc = _dim_desc_html(choice or "")
    # Show SSRL only when a substantive D1-D9 code is selected (not NS / NA / None)
    _skip_prefixes = ("NS", "NA", "None", "")
    show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes)
    return desc, gr.update(visible=show_ssrl)


def fn_skip_episode(state: dict):
    """Mark current episode as non-codeable and advance to next."""
    idx  = state.get("current_index", 0)
    segs = state.get("segments", [])
    if 0 <= idx < len(segs):
        sid = segs[idx].get("segment_id")
        state.setdefault("codings", {})[sid] = {
            "dimension_id": "SKIP",
            "secondary_dim": None,
            "ssrl_phase":    None,
            "comment":       "Not codeable β€” skipped",
        }
    return fn_navigate(+1, "SKIP", SEC_NONE, "", SSRL_NONE, state)


# ── Next section / finish ─────────────────────────────────────────────────────

def fn_next_section(dim_choice: str, sec_choice: str, comment: str,
                    ssrl_choice: str, state: dict):
    segs    = _current_section_segments(state)
    codings = dict(state.get("codings", {}))
    idx     = state.get("coding_idx", 0)
    if segs and dim_choice:
        sid = segs[min(idx, len(segs) - 1)]["segment_id"]
        codings[sid] = {
            "dimension_id":          DIM_ID_FROM_CHOICE[dim_choice],
            "secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),
            "comment":               comment.strip(),
            "ssrl_phase":            SSRL_ID_FROM_CHOICE.get(ssrl_choice or SSRL_NONE),
        }

    new_state            = dict(state)
    new_state["codings"] = codings
    sections             = new_state.get("sections", [])
    sec_idx              = new_state.get("section_idx", 0)
    cur_id               = sections[sec_idx]["section_id"]
    new_state["section_stages"][cur_id] = "done"
    next_idx = sec_idx + 1

    if next_idx >= len(sections):
        # All done β€” navigate to done page
        new_state["stage"] = "complete"
        _write_coding_file(new_state)
        _persist(new_state)
        gr.Info("All sections coded! Download your coding file.")
        print(f"[Done] All {len(sections)} sections coded for session {new_state['session_id']}")
        return (
            new_state,
            *_show("done"),
            _section_cards_html(sections, new_state["section_stages"], sec_idx),
            "",                        # section_header_md
            gr.update(visible=False),  # col_boundary_review
            gr.update(visible=False),  # col_coding
            gr.update(value=""),       # boundary_display_html
            gr.update(value=""),       # boundary_ids_box
            gr.update(value=""),       # episode_dialogue_html
        )

    # More sections remain β€” populate boundary review for the next section
    new_state["section_idx"] = next_idx
    new_state["coding_idx"]  = 0
    next_sec = sections[next_idx]
    n        = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1
    hdr      = (
        f"### Section {next_idx+1} of {len(sections)}: {next_sec['label']}\n"
        f"*{next_sec.get('summary','')}*  Β·  "
        f"turns {next_sec['start_turn_id']}–{next_sec['end_turn_id']} ({n} turns)"
    )
    _persist(new_state)

    result   = new_state.get("section_a1a_results", {}).get(next_sec["section_id"], {})
    bounds   = result.get("boundaries", [])
    next_segs = result.get("segments", [])
    turns    = _turns_for_section(new_state["turns"], next_sec)
    ids_txt  = ", ".join(str(b["after_turn_id"]) for b in bounds)
    ep_html  = _episode_dialogue_html(next_segs, bounds, new_state["speakers"])

    gr.Info(f"Section {next_idx+1} of {len(sections)}: {next_sec['label']}")
    print(f"[Next Section] Moving to section {next_idx+1}: {next_sec['label']}")
    return (
        new_state,
        *_show("pipeline"),
        _section_cards_html(sections, new_state["section_stages"], next_idx),
        hdr,
        gr.update(visible=True),   # col_boundary_review
        gr.update(visible=False),  # col_coding
        gr.update(value=_episode_table_html(turns, bounds)),  # boundary_display_html
        gr.update(value=ids_txt),                             # boundary_ids_box
        ep_html,                                              # episode_dialogue_html
    )


# ── Download ──────────────────────────────────────────────────────────────────

def _write_coding_file(state: dict) -> Path:
    all_segs: list[dict] = []
    for sec in state.get("sections", []):
        all_segs.extend(state["section_segments_coded"].get(sec["section_id"], []))
    codings = state.get("codings", {})
    output  = {
        "session_id":    state["session_id"],
        "researcher_id": state["researcher_id"],
        "codings": [
            {
                "segment_id":            s["segment_id"],
                "section_id":            s.get("section_id", ""),
                "dimension_id":          codings.get(s["segment_id"], {}).get("dimension_id", ""),
                "secondary_dimension_id":codings.get(s["segment_id"], {}).get("secondary_dimension_id"),
                "ssrl_phase":            codings.get(s["segment_id"], {}).get("ssrl_phase"),
                "comment":               codings.get(s["segment_id"], {}).get("comment", ""),
            }
            for s in all_segs
        ],
    }
    segs_all = {"segments": [{k: v for k, v in s.items() if k != "turns"} for s in all_segs]}
    d = _session_dir(state)
    (d / "segments_all.json").write_text(
        json.dumps(segs_all, indent=2, ensure_ascii=False), encoding="utf-8"
    )
    out = d / f"coding_{state['researcher_id']}.json"
    out.write_text(json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8")
    return out


def fn_download(state: dict):
    if not state.get("sections"):
        raise gr.Error("No coding to download yet.")
    path = _write_coding_file(state)
    tmp  = Path(tempfile.mktemp(suffix=f"_{path.name}"))
    tmp.write_bytes(path.read_bytes())
    return str(tmp)


# ── Agreement ─────────────────────────────────────────────────────────────────

def fn_calculate_kappa(r2_file, state: dict):
    if r2_file is None:
        raise gr.Error("Upload your co-researcher's coding file first.")
    if not state.get("session_id"):
        raise gr.Error("Complete the Pipeline first β€” session ID not set.")

    d         = _session_dir(state)
    r1_path   = d / f"coding_{state['researcher_id']}.json"
    segs_path = d / "segments_all.json"

    if not r1_path.exists():
        raise gr.Error("Your own coding file not found β€” download it from the Pipeline first.")
    if not segs_path.exists():
        raise gr.Error("Segments file not found β€” complete the coding pipeline first.")

    r2_path = d / "coding_R2.json"
    r2_path.write_bytes(Path(r2_file.name).read_bytes())

    t0 = time.perf_counter()
    try:
        report = calculate_kappa_report(
            session_id=state["session_id"],
            coding_r1_path=r1_path,
            coding_r2_path=r2_path,
            proposed_segments_path=segs_path,
            output_path=d / "kappa_report.json",
        )
    except Exception as e:
        raise gr.Error(f"Kappa calculation failed: {e}") from e

    rt    = round(time.perf_counter() - t0, 1)
    gate  = report.get("gate_passed", False)
    n_dis = len(report.get("segments_in_disagreement", []))

    state = dict(state)
    state["kappa_report"] = report
    log = _make_log_entry("Kappa Calculator", rt,
                          kappa=round(report.get("overall_kappa", 0), 3),
                          gate_passed=gate, disagreements=n_dis)
    state = _push_log(state, log)

    if gate:
        gr.Info(f"ΞΊ={report['overall_kappa']:.3f} β€” gate passed! {n_dis} disagreements to resolve.")
    else:
        gr.Warning(f"ΞΊ={report['overall_kappa']:.3f} β€” below 0.70 threshold.")

    dis_md = ""
    if n_dis:
        dis  = report.get("segments_in_disagreement", [])
        rows = "| Segment | R1 | R2 | Agent 1b |\n|---|---|---|---|\n"
        for di in dis[:20]:
            rows += (
                f"| `{di['segment_id']}` "
                f"| {di.get('r1_dimension','?')} "
                f"| {di.get('r2_dimension','?')} "
                f"| {di.get('agent_dimension','?')} |\n"
            )
        if len(dis) > 20:
            rows += f"| *…{len(dis)-20} more* | | | |\n"
        dis_md = f"### Disagreements ({n_dis})\n\n{rows}"

    return (
        state,
        _kappa_html(report),
        dis_md,
        gr.update(visible=bool(n_dis)),
        _agent_log_html(state["agent_logs"]),
    )


def fn_run_sequence_analysis(rater_choice: str, state: dict):
    if not state.get("session_id"):
        raise gr.Error("No session loaded β€” complete the Pipeline first.")

    d = _session_dir(state)
    try:
        path = d / "coding_R2.json" if "R2" in rater_choice else d / f"coding_{state['researcher_id']}.json"
        if not path.exists():
            raise gr.Error(f"Coding file not found: {path.name}.")
        analysis = load_and_analyse(path, max_lag=3)
    except gr.Error:
        raise
    except Exception as e:
        raise gr.Error(f"Sequence analysis failed: {e}") from e

    if "error" in analysis:
        raise gr.Error(analysis["error"])

    stat    = analysis.get("statistics", {})
    n_ep    = stat.get("n_episodes", 0)
    n_tr    = stat.get("n_transitions", 0)
    cats    = stat.get("categories_used", [])
    entropy = stat.get("transition_entropy", 0.0)
    ent_max = stat.get("entropy_max", 0.0)
    sig_pos = stat.get("significant_pos", [])
    sig_neg = stat.get("significant_neg", [])

    ent_note = (
        f"**{entropy:.3f}** bits / max {ent_max:.3f} β€” "
        + ("high entropy: no strong sequential pattern"
           if ent_max > 0 and entropy / ent_max > 0.80
           else "moderate entropy: some transitions dominate"
           if ent_max > 0 and entropy / ent_max > 0.50
           else "low entropy: a few transitions strongly dominate")
    )

    warnings = analysis.get("sparse_warnings", [])
    warn_md  = ""
    if warnings:
        warn_md = (
            f"\n\n*⚠ {len(warnings)} sparse cell(s): "
            f"{'; '.join(warnings[:3])}{'…' if len(warnings) > 3 else ''}*"
        )

    summary_md = (
        f"**{n_ep}** episodes Β· **{n_tr}** transitions Β· "
        f"**{len(cats)}** dimensions: `{'`, `'.join(cats)}`  \n"
        f"Entropy: {ent_note}  \n"
        f"**{len(sig_pos)}** significantly common Β· **{len(sig_neg)}** significantly rare"
        f"{warn_md}"
    )

    gr.Info(f"Sequence analysis: {n_ep} episodes, {len(sig_pos)} significant transitions.")
    return summary_md, render_transition_matrix_html(analysis), render_significant_transitions_html(analysis), gr.update(visible=True)


def fn_download_seq_csv(rater_choice: str, state: dict):
    if not state.get("session_id"):
        raise gr.Error("No session loaded.")
    d    = _session_dir(state)
    path = d / ("coding_R2.json" if "R2" in rater_choice else f"coding_{state['researcher_id']}.json")
    if not path.exists():
        raise gr.Error(f"Coding file not found: {path.name}")
    analysis = load_and_analyse(path)
    if "error" in analysis:
        raise gr.Error(analysis["error"])
    csv_str = seq_to_csv(analysis)
    tmp = Path(tempfile.mktemp(suffix=f"_transitions_{state['session_id']}.csv"))
    tmp.write_text(csv_str, encoding="utf-8")
    return str(tmp)


def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict):
    if not seg_id.strip():
        raise gr.Error("Enter the segment ID.")
    if not dim_choice:
        raise gr.Error("Select the resolved dimension.")
    resolved = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice)
    try:
        resolve_disagreement(
            report_path=_session_dir(state) / "kappa_report.json",
            segment_id=seg_id.strip(), resolved_dimension=resolved,
            resolution_note=note.strip(),
        )
    except Exception as e:
        raise gr.Error(f"Could not resolve: {e}") from e
    gr.Info(f"Resolved {seg_id.strip()} β†’ {resolved}")
    return state, f"βœ“ `{seg_id.strip()}` β†’ **{resolved}**"


def fn_discard(seg_id: str, note: str, state: dict):
    if not seg_id.strip():
        raise gr.Error("Enter the segment ID.")
    try:
        discard_disagreement(
            report_path=_session_dir(state) / "kappa_report.json",
            segment_id=seg_id.strip(), discard_note=note.strip(),
        )
    except Exception as e:
        raise gr.Error(f"Could not discard: {e}") from e
    gr.Info(f"Discarded {seg_id.strip()}")
    return state, f"Discarded `{seg_id.strip()}`"


# ── Rules ─────────────────────────────────────────────────────────────────────

def fn_load_rules():
    pending = list_pending_rules()
    choices = [f"{r['rule_id']}: {r['description'][:55]}…" for r in pending]
    return _rules_html(pending), choices


def fn_approve(choice: str, researcher: str, note: str):
    if not choice:
        raise gr.Error("Select a rule.")
    if not researcher.strip():
        raise gr.Error("Enter your Researcher ID.")
    rid = choice.split(":")[0].strip()
    approve_rule(rid, researcher.strip(), note.strip())
    gr.Info(f"Rule {rid} approved.")
    return f"βœ“ Rule **{rid}** approved β€” now active for Agent 1b."


def fn_reject(choice: str, researcher: str, note: str):
    if not choice:
        raise gr.Error("Select a rule.")
    if not researcher.strip():
        raise gr.Error("Enter your Researcher ID.")
    if not note.strip():
        raise gr.Error("Provide a rejection reason β€” Agent 2 learns from it.")
    rid = choice.split(":")[0].strip()
    reject_rule(rid, researcher.strip(), note.strip())
    gr.Info(f"Rule {rid} rejected.")
    return f"βœ— Rule **{rid}** rejected."


# ===========================================================================
# CSS
# ===========================================================================

EXTRA_CSS = """
.gradio-container {
    max-width: 1200px !important;
    margin: 0 auto !important;
    background: #ececee !important;
    font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif !important;
}
footer { display: none !important; }

:root {
    --cc-bg:          #ececee;
    --cc-surface:     #f6f6f7;
    --cc-paper:       #ffffff;
    --cc-ink:         #111217;
    --cc-muted:       #6b6f76;
    --cc-border:      #d8dade;
    --cc-accent:      #ff5a3d;
    --cc-accent-deep: #ea4425;
}

:focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; }
:focus         { outline: none; }

/* Primary button */
.gradio-container button.primary {
    background: var(--cc-accent) !important;
    border-color: var(--cc-accent) !important;
    color: #fff !important;
    font-weight: 700 !important;
}
.gradio-container button.primary:hover {
    background: var(--cc-accent-deep) !important;
    border-color: var(--cc-accent-deep) !important;
}
.gradio-container button.secondary,
.gradio-container button:not(.primary) {
    border-color: #c9cdd3 !important;
}

/* ── Welcome ── */
.cc-hero {
    text-align: center;
    padding: 56px 24px 40px;
}
.cc-hero-title {
    font-size: clamp(3.5rem, 10vw, 7rem);
    font-weight: 900;
    letter-spacing: -0.06em;
    color: var(--cc-ink);
    line-height: 0.88;
    margin: 0 0 16px;
}
.cc-hero-sub {
    font-size: 1rem;
    color: var(--cc-muted);
    max-width: 44ch;
    margin: 0 auto 48px;
    line-height: 1.55;
}
.cc-entry-card {
    background: var(--cc-paper);
    border: 1px solid var(--cc-border);
    border-radius: 16px;
    padding: 24px;
    min-height: 190px;
    position: relative;
    overflow: hidden;
}
.cc-entry-card::after {
    content: "";
    position: absolute;
    right: -24px; bottom: -24px;
    width: 96px; height: 96px;
    border-radius: 999px;
    background: rgba(255,90,61,0.1);
}
.cc-entry-kicker {
    font-size: 0.7rem;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    color: var(--cc-accent-deep);
    margin-bottom: 10px;
    display: block;
}
.cc-entry-title {
    font-size: 1.28rem;
    font-weight: 800;
    letter-spacing: -0.025em;
    color: var(--cc-ink);
    margin: 0 0 8px;
    line-height: 1.1;
}
.cc-entry-desc {
    font-size: 0.87rem;
    color: #434852;
    line-height: 1.55;
    max-width: 32ch;
}

/* ── Page nav bar ── */
.cc-page-nav {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 0 14px;
    border-bottom: 2px solid var(--cc-border);
    margin-bottom: 24px;
}
.cc-page-label {
    font-size: 0.68rem;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.12em;
    color: var(--cc-accent-deep);
}
.cc-page-title {
    font-size: 1.5rem;
    font-weight: 800;
    letter-spacing: -0.03em;
    color: var(--cc-ink);
    margin: 0;
}
.cc-page-meta {
    font-size: 0.78rem;
    color: var(--cc-muted);
    margin-left: auto;
    font-family: monospace;
}

/* ── Step indicator ── */
.cc-steps {
    display: flex;
    gap: 6px;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 20px;
}
.cc-step-done   { color:#065f46;background:#f0fdf4;border:1px solid #86efac;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; }
.cc-step-active { color:#4338ca;background:#eef2ff;border:1px solid #818cf8;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; }
.cc-step-next   { color:#94a3b8;background:transparent;border:1px solid #e2e8f0;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:500; }
.cc-step-sep    { color:#d1d5db;font-size:0.7rem; }

/* ── Setup page ── */
.cc-setup-box {
    background: var(--cc-paper);
    border: 1px solid var(--cc-border);
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 16px;
}

/* ── Pipeline page ── */
.cc-section-header {
    background: #eff6ff;
    border: 1px solid #93c5fd;
    border-left: 4px solid #3b82f6;
    border-radius: 0 8px 8px 0;
    padding: 10px 16px;
    margin: 12px 0;
    font-size:0.92em;
    color: #1e3a8a;
}

/* ── Coding canvas ── */
.cc-coding-transcript {
    background: var(--cc-paper);
    border: 1px solid var(--cc-border);
    border-radius: 10px;
    padding: 16px;
    max-height: 62vh;
    overflow-y: auto;
}
.cc-coding-controls {
    background: var(--cc-paper);
    border: 1px solid var(--cc-border);
    border-radius: 10px;
    padding: 16px;
}
.cc-coding-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 12px 0 0;
    border-top: 1px solid var(--cc-border);
    margin-top: 12px;
}

/* ── Done page ── */
.cc-done-card {
    background: #f0fdf4;
    border: 2px solid #86efac;
    border-radius: 16px;
    padding: 32px;
    text-align: center;
    margin: 24px 0;
}
.cc-done-title {
    font-size: 2rem;
    font-weight: 800;
    color: #065f46;
    margin: 0 0 8px;
}
.cc-done-sub {
    color: #14532d;
    font-size: 0.95rem;
    max-width: 50ch;
    margin: 0 auto;
    line-height: 1.6;
}

/* ── Info callout ── */
.cc-callout {
    background: #eff6ff;
    border: 1px solid #93c5fd;
    border-radius: 10px;
    padding: 16px 20px;
    margin-bottom: 16px;
    font-size: 0.88em;
    color: #1e3a8a;
    line-height: 1.7;
}

/* ── Pipeline progress header (always visible) ── */
.cc-pipeline-bar {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 20px;
    background: var(--cc-paper);
    border-bottom: 1.5px solid var(--cc-border);
    flex-wrap: wrap;
    position: sticky;
    top: 0;
    z-index: 50;
    box-shadow: 0 1px 6px rgba(0,0,0,0.05);
}
.cc-pipeline-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 2px;
    padding: 5px 12px;
    border-radius: 7px;
    min-width: 64px;
    border: 1.5px solid var(--cc-border);
    background: var(--cc-surface);
}
.cc-pipeline-step.done   { background: #f0fdf4; border-color: #86efac; }
.cc-pipeline-step.active { background: #fff5f2; border-color: var(--cc-accent); }
.cc-pipeline-step .dot   { font-size: 0.82em; color: var(--cc-muted); }
.cc-pipeline-step.done .dot   { color: #15803d; }
.cc-pipeline-step.active .dot { color: var(--cc-accent); }
.cc-pipeline-step .lbl   {
    font-size: 0.66em; font-weight: 800; text-transform: uppercase;
    letter-spacing: 0.06em; color: var(--cc-muted);
}
.cc-pipeline-step.done .lbl   { color: #15803d; }
.cc-pipeline-step.active .lbl { color: var(--cc-accent-deep); }

/* ── Screener view ── */
.cc-screener-row {
    display: grid;
    grid-template-columns: 36px 80px 64px 1fr 160px;
    gap: 8px;
    padding: 7px 12px;
    border-bottom: 1px solid var(--cc-border);
    align-items: start;
    font-size: 0.85em;
}
.cc-screener-header {
    background: var(--cc-surface);
    border-radius: 8px 8px 0 0;
    font-size: 0.7em;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--cc-muted);
}

/* ── Lexicon tier cards ── */
.cc-tier-card {
    border: 1.5px solid var(--cc-border);
    border-radius: 10px;
    padding: 12px 16px;
    margin-bottom: 10px;
    background: var(--cc-paper);
}
.cc-tier-kicker {
    font-size: 0.68em;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: var(--cc-accent-deep);
    margin-bottom: 4px;
}
"""

CSS = _load_css() + EXTRA_CSS

# ===========================================================================
# Pipeline header + Screener + Lexicon helpers
# ===========================================================================

_PIPE_STAGES = [
    ("upload",    "Upload"),
    ("screened",  "Screen"),
    ("sectioned", "Section"),
    ("coded",     "Code"),
    ("done",      "Done"),
    ("agreed",    "Agreement"),
]
_PIPE_ORDER = [s for s, _ in _PIPE_STAGES]


def _pipeline_bar_html(state: dict) -> str:
    current = state.get("stage", "upload")
    session = html_lib.escape(state.get("session_id", "β€”") or "β€”")
    turns   = len(state.get("turns", []))
    sc      = state.get("screener_result")
    savings = f"{sc['estimated_llm_savings']:.0%}" if sc else "β€”"
    n_wins  = len(sc["candidate_windows"]) if sc else "β€”"
    try:
        cur_i = _PIPE_ORDER.index(current)
    except ValueError:
        cur_i = 0

    steps = []
    for i, (stage, label) in enumerate(_PIPE_STAGES):
        cls = "done" if i < cur_i else ("active" if i == cur_i else "")
        dot = "βœ“" if i < cur_i else ("β–Ά" if i == cur_i else "β—‹")
        steps.append(
            f'<div class="cc-pipeline-step {cls}">'
            f'<span class="dot">{dot}</span>'
            f'<span class="lbl">{label}</span>'
            f'</div>'
        )

    return (
        f'<div class="cc-pipeline-bar">'
        f'<div style="line-height:1.25;margin-right:6px">'
        f'<div style="font-weight:800;font-size:0.85em;color:var(--cc-ink)">{session}</div>'
        f'<div style="font-size:0.68em;color:var(--cc-muted)">'
        f'{turns} turns Β· {n_wins} windows Β· ~{savings} LLM saved</div>'
        f'</div>'
        + "".join(steps)
        + f'</div>'
    )


def _screener_summary_html(rd: dict) -> str:
    total   = rd.get("total_turns", 0)
    flagged = rd.get("flagged_turns", 0)
    windows = len(rd.get("candidate_windows", []))
    savings = rd.get("estimated_llm_savings", 0)

    def chip(v, lbl, tc, bg):
        return (
            f'<div style="background:{bg};border-radius:9px;padding:10px 16px;'
            f'text-align:center;min-width:80px">'
            f'<div style="font-size:1.45em;font-weight:800;color:{tc}">{html_lib.escape(str(v))}</div>'
            f'<div style="font-size:0.68em;color:{tc};opacity:.8;font-weight:700;'
            f'text-transform:uppercase;letter-spacing:.05em">{lbl}</div></div>'
        )

    return (
        f'<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px">'
        + chip(total,          "Total turns",    "#111217", "#f6f6f7")
        + chip(flagged,        "Flagged",        "#15803d", "#f0fdf4")
        + chip(windows,        "LLM windows",    "#b45309", "#fffbeb")
        + chip(f"{savings:.0%}", "LLM saved",   "#ff5a3d", "#fff5f2")
        + f'</div>'
    )


def _screener_turns_html(rd: dict, speaker_map: dict) -> str:
    scores = rd.get("turn_scores", [])
    if not scores:
        return '<p style="color:var(--cc-muted)">No turns scored.</p>'

    rows = [
        '<div style="border:1px solid var(--cc-border);border-radius:10px;overflow:hidden">'
        '<div class="cc-screener-row cc-screener-header" '
        'style="padding:6px 12px;background:var(--cc-surface)">'
        '<div>#</div><div>Speaker</div><div>Score</div><div>Text</div><div>Triggers</div>'
        '</div>'
    ]
    for ts in scores[:250]:
        excl    = bool(ts.get("excluded_reason"))
        flagged = ts.get("flagged", False)
        score   = ts.get("composite", 0)
        sp      = ts.get("speaker", "?")
        text    = html_lib.escape(ts.get("text", "")[:130])
        tid     = ts.get("turn_id", "")
        hits    = ts.get("hits", [])
        sigs    = ts.get("signals", [])

        if excl:
            sbg, stc = "#f6f6f7", "#a8a29e"
        elif score >= 0.8:
            sbg, stc = "#f0fdf4", "#15803d"
        elif score >= 0.4:
            sbg, stc = "#fffbeb", "#b45309"
        elif score >= 0.2:
            sbg, stc = "#fff5f2", "#ff5a3d"
        else:
            sbg, stc = "#f6f6f7", "#6b6f76"

        chips = ""
        for h in hits[:3]:
            lbl = html_lib.escape(h.get("category_label", "")[:22])
            t   = h.get("tier", 1)
            mark = "Β²" if t == 2 else "Β³?" if t == 3 else ""
            chips += (
                f'<span style="background:#fff5f2;color:#ff5a3d;font-size:0.72em;'
                f'padding:1px 5px;border-radius:3px;white-space:nowrap">{lbl}{mark}</span> '
            )
        for sig in sigs[:2]:
            chips += (
                f'<span style="background:#faf5ff;color:#7c3aed;font-size:0.72em;'
                f'padding:1px 5px;border-radius:3px;white-space:nowrap">{html_lib.escape(sig)}</span> '
            )
        if excl:
            chips = '<span style="font-size:0.72em;color:#a8a29e">small talk</span>'

        flag  = "β–Ά" if flagged else ("–" if excl else "Β·")
        row_bg = "#fffbeb" if flagged else ("#f6f6f7" if excl else "white")

        rows.append(
            f'<div class="cc-screener-row" style="background:{row_bg}">'
            f'<div style="font-family:monospace;font-size:0.72em;color:var(--cc-muted)">'
            f'{flag}{html_lib.escape(str(tid))}</div>'
            f'<div style="font-size:0.78em;font-weight:600;color:#111217;'
            f'overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{html_lib.escape(sp[:12])}</div>'
            f'<div><span style="background:{sbg};color:{stc};font-family:monospace;'
            f'font-size:0.8em;font-weight:700;padding:2px 5px;border-radius:4px">'
            f'{score:.2f}</span></div>'
            f'<div style="font-size:0.85em;color:#111217;line-height:1.45">{text}</div>'
            f'<div style="display:flex;flex-direction:column;gap:2px">{chips}</div>'
            f'</div>'
        )
    if len(scores) > 250:
        rows.append(
            f'<div style="text-align:center;padding:8px;font-size:0.8em;color:var(--cc-muted)">'
            f'{len(scores)-250} more turns not shown</div>'
        )
    rows.append('</div>')
    return "".join(rows)


def _lexicon_tier1_html(data: dict) -> str:
    cats = data.get("categories", [])
    phase_colors = {
        "planning":   ("#1d4ed8","#eff6ff"),
        "monitoring": ("#15803d","#f0fdf4"),
        "evaluating": ("#b45309","#fffbeb"),
        "ssrl":       ("#7c3aed","#faf5ff"),
    }
    parts = ['<div style="font-size:0.8em;color:var(--cc-muted);margin-bottom:12px;'
             'padding:8px 12px;background:var(--cc-surface);border-radius:6px">'
             'Tier 1 is research-locked. Add custom terms in Tier 2.</div>']
    for cat in cats:
        tc, bg = phase_colors.get(cat.get("phase",""), ("#6b6f76","#f6f6f7"))
        terms  = " ".join(
            f'<span style="background:{bg};color:{tc};font-size:0.78em;'
            f'padding:2px 7px;border-radius:4px;display:inline-block;margin:2px">'
            f'{html_lib.escape(t)}</span>'
            for t in cat.get("terms", [])
        )
        parts.append(
            f'<div class="cc-tier-card">'
            f'<div class="cc-tier-kicker">{html_lib.escape(cat.get("phase",""))}</div>'
            f'<div style="font-weight:800;color:var(--cc-ink);margin-bottom:4px">'
            f'{html_lib.escape(cat.get("label",""))}</div>'
            f'<div style="font-size:0.72em;color:var(--cc-muted);margin-bottom:8px">'
            f'w={cat.get("weight",0)} Β· {html_lib.escape(cat.get("source",""))}</div>'
            f'<div style="line-height:2">{terms}</div></div>'
        )
    return "".join(parts)


def _lexicon_tier2_html(data: dict) -> str:
    entries = data.get("entries", [])
    if not entries:
        return ('<div style="text-align:center;padding:36px;color:var(--cc-muted)">'
                'No validated terms yet. Use the form below to add them.</div>')
    parts = []
    for e in entries:
        terms = " ".join(
            f'<span style="background:#f0fdf4;color:#15803d;font-size:0.8em;'
            f'padding:2px 7px;border-radius:4px">{html_lib.escape(t)}</span>'
            for t in e.get("terms", [])
        )
        note = html_lib.escape(e.get("note",""))
        parts.append(
            f'<div class="cc-tier-card">'
            f'<div style="font-weight:700;color:var(--cc-ink)">{html_lib.escape(e.get("label",""))}</div>'
            f'<div style="font-size:0.72em;color:var(--cc-muted);margin-bottom:6px">'
            f'by {html_lib.escape(e.get("added_by",""))} Β· {html_lib.escape(e.get("category_id",""))}</div>'
            f'<div style="margin-bottom:6px">{terms}</div>'
            + (f'<div style="font-size:0.8em;color:var(--cc-muted)">{note}</div>' if note else "")
            + f'</div>'
        )
    return "".join(parts)


def _lexicon_tier3_html(data: dict) -> str:
    cands = [c for c in data.get("candidates", [])
             if not c.get("approved") and not c.get("rejected")]
    if not cands:
        return ('<div style="text-align:center;padding:36px;color:var(--cc-muted)">'
                'No pending candidates.</div>')
    parts = []
    for c in cands:
        terms = " ".join(
            f'<span style="background:#fffbeb;color:#b45309;font-size:0.8em;'
            f'padding:2px 8px;border-radius:4px;font-weight:600">{html_lib.escape(t)}</span>'
            for t in c.get("terms", [])
        )
        ctx = html_lib.escape(c.get("context","")[:180])
        parts.append(
            f'<div class="cc-tier-card" style="border-color:#fde68a;background:#fffbeb">'
            f'<div class="cc-tier-kicker" style="color:#b45309">Pending review</div>'
            f'<div style="font-weight:700;color:var(--cc-ink);margin-bottom:6px">'
            f'{html_lib.escape(c.get("label",""))}</div>'
            f'<div style="margin-bottom:6px">{terms}</div>'
            + (f'<div style="font-size:0.8em;color:#78350f;font-style:italic">&ldquo;{ctx}&rdquo;</div>' if ctx else "")
            + f'</div>'
        )
    return "".join(parts)


# Screener handler β€” returns (state, bar, summary_html, turns_html, rerun_btn_update)
def fn_run_screener(state: dict):
    turns = state.get("turns", [])
    if not turns:
        err = ('<div style="background:#fffbeb;border:1px solid #fde68a;border-radius:8px;'
               'padding:14px;color:#92400e">No transcript loaded β€” go back to Upload.</div>')
        return state, _pipeline_bar_html(state), err, "", gr.update(visible=True)
    try:
        result      = screen_transcript(turns)
        rd          = result_to_dict(result)
        new_state   = dict(state)
        new_state["screener_result"] = rd
        new_state["stage"] = "screened"
        speaker_map = new_state.get("speakers", {})
        return (
            new_state,
            _pipeline_bar_html(new_state),
            _screener_summary_html(rd),
            _screener_turns_html(rd, speaker_map),
            gr.update(visible=False),   # hide re-run btn β€” success
        )
    except Exception as e:
        err = (
            f'<div style="background:#fffbeb;border:1px solid #fde68a;border-radius:8px;'
            f'padding:14px;color:#92400e"><strong>Screener error:</strong> '
            f'{html_lib.escape(str(e))}</div>'
        )
        return state, _pipeline_bar_html(state), err, "", gr.update(visible=True)


# Lexicon handlers
def fn_load_lexicon():
    try:
        d = load_full_lexicon()
        return _lexicon_tier1_html(d["tier1"]), _lexicon_tier2_html(d["tier2"]), _lexicon_tier3_html(d["tier3"]), ""
    except Exception as e:
        return "", "", "", f"Error loading lexicon: {e}"


def fn_add_tier2_term(cat_id, label, phase, terms_text, weight, researcher_id, note):
    terms = [t.strip() for t in terms_text.replace(",","\n").splitlines() if t.strip()]
    if not terms:
        return "Enter at least one term.", "", ""
    try:
        add_tier2_term(terms=terms, category_id=cat_id or "TIER2_custom",
                       label=label or "Custom", phase=phase or "monitoring",
                       weight=float(weight), added_by=researcher_id or "researcher", note=note)
        d = load_full_lexicon()
        return f"Added {len(terms)} term(s) to Tier 2.", _lexicon_tier2_html(d["tier2"]), ""
    except Exception as e:
        return f"Failed: {e}", "", ""


def fn_approve_t3(term, researcher_id):
    if not term.strip():
        return "Enter a term.", ""
    try:
        approve_tier3_candidate(term.strip(), approved_by=researcher_id or "researcher")
        d = load_full_lexicon()
        return f"'{term}' approved.", _lexicon_tier3_html(d["tier3"])
    except Exception as e:
        return f"Failed: {e}", ""


def fn_reject_t3(term, researcher_id, note):
    if not term.strip():
        return "Enter a term.", ""
    try:
        reject_tier3_candidate(term.strip(), rejected_by=researcher_id or "researcher", note=note)
        d = load_full_lexicon()
        return f"'{term}' rejected.", _lexicon_tier3_html(d["tier3"])
    except Exception as e:
        return f"Failed: {e}", ""


# ===========================================================================
# UI β€” page-based (no tabs)
# ===========================================================================

with gr.Blocks(title="CollabCode") as demo:

    state = gr.State(_empty_state())

    # Persistent pipeline status bar (hidden on welcome)
    pipeline_bar_html = gr.HTML(
        value=_pipeline_bar_html(_empty_state()),
        visible=False,
        elem_id="cc-pipeline-bar-root",
    )

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 0: Welcome
    # Hidden buttons kept so wiring stays intact
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=True) as pg_welcome:
        # Hidden nav buttons (agreement / library) β€” wiring requires them to exist
        agreement_nav_btn = gr.Button(visible=False)
        library_nav_btn   = gr.Button(visible=False)

        gr.HTML(
            '<div class="cc-hero">'
            '<h1 class="cc-hero-title">CollabCode</h1>'
            '<p class="cc-hero-sub">Human-in-the-loop qualitative coding '
            'for collaborative learning research</p>'
            '</div>'
        )

        # ── Primary entry card ────────────────────────────────────────────
        with gr.Row(equal_height=True):
            with gr.Column(scale=2):
                gr.HTML(
                    '<div class="cc-entry-card">'
                    '<span class="cc-entry-kicker">Primary workflow</span>'
                    '<h3 class="cc-entry-title">Code a Transcript</h3>'
                    '<p class="cc-entry-desc">Upload a Zoom transcript or load from Drive. '
                    'AI pre-screens turns for metacognitive signals, detects discussion sections, '
                    'finds episode boundaries, and proposes D1–D9 codes β€” '
                    'you review and confirm every decision.</p>'
                    '</div>'
                )
                start_btn = gr.Button("Start Coding β†’", variant="primary", size="lg")

        # ── About / system logic ──────────────────────────────────────────
        gr.HTML(
            '<div style="margin:36px 0 8px;border-top:1px solid var(--cc-border);'
            'padding-top:32px">'
            '<div style="font-weight:800;font-size:1.05em;color:var(--cc-ink);'
            'margin-bottom:20px;letter-spacing:-0.01em">How CollabCode works</div>'
            '</div>'
        )

        with gr.Row(equal_height=True):
            gr.HTML(
                '<div class="cc-entry-card" style="border-top:3px solid #ff5a3d">'
                '<span class="cc-entry-kicker">Step 1 β€” Pre-screen</span>'
                '<h3 class="cc-entry-title" style="font-size:1em">Metacognitive Screener</h3>'
                '<p class="cc-entry-desc">Before any LLM call, every turn is scored against '
                'a three-tier lexicon (Iiskala 2011; Schoor &amp; Bannert 2012). '
                'Turns with no metacognitive signal are filtered out β€” typically cutting '
                'LLM cost by 40–70 %. Only candidate windows reach Agent 0.</p>'
                '</div>'
            )
            gr.HTML(
                '<div class="cc-entry-card" style="border-top:3px solid #f59e0b">'
                '<span class="cc-entry-kicker">Step 2 β€” Structure</span>'
                '<h3 class="cc-entry-title" style="font-size:1em">Agent 0 β€” Sectioner</h3>'
                '<p class="cc-entry-desc">Agent 0 reads the full transcript and proposes '
                'thematic sections (e.g. "Problem framing", "Solution negotiation"). '
                'You rename or merge them before the next stage. '
                'Sections give Agent 1a its scope and anchor all downstream analysis.</p>'
                '</div>'
            )
            gr.HTML(
                '<div class="cc-entry-card" style="border-top:3px solid #10b981">'
                '<span class="cc-entry-kicker">Step 3 β€” Episodes</span>'
                '<h3 class="cc-entry-title" style="font-size:1em">Agent 1a β€” Boundary Detector</h3>'
                '<p class="cc-entry-desc">Within each section, Agent 1a runs in parallel '
                'to find episode boundaries β€” moments where the collaborative activity '
                'shifts. Boundary proposals are shown to you for review and adjustment '
                'before coding begins.</p>'
                '</div>'
            )
            gr.HTML(
                '<div class="cc-entry-card" style="border-top:3px solid #6366f1">'
                '<span class="cc-entry-kicker">Step 4 β€” Code</span>'
                '<h3 class="cc-entry-title" style="font-size:1em">Agent 1b + Human</h3>'
                '<p class="cc-entry-desc">Agent 1b proposes D1–D9 codes '
                '(Meier, Spada &amp; Rummel 2007) and SSRL phases (M-MON, M-REG, CO-REG, SSRL) '
                'for each episode. You code independently first, then reveal the AI proposal '
                'to resolve ambiguity. All decisions are yours.</p>'
                '</div>'
            )

        with gr.Row(equal_height=True):
            gr.HTML(
                '<div class="cc-entry-card" style="border-top:3px solid #0ea5e9">'
                '<span class="cc-entry-kicker">Step 5 β€” Agreement</span>'
                '<h3 class="cc-entry-title" style="font-size:1em">Inter-rater Reliability</h3>'
                '<p class="cc-entry-desc">Upload a second coder\'s file to compute '
                'Gwet\'s AC1 (primary) and Cohen\'s ΞΊ (reference) per dimension. '
                'Disagreements are listed segment by segment so you can resolve '
                'or flag them for discussion.</p>'
                '</div>'
            )
            gr.HTML(
                '<div class="cc-entry-card" style="border-top:3px solid #8b5cf6">'
                '<span class="cc-entry-kicker">Step 6 β€” Learn</span>'
                '<h3 class="cc-entry-title" style="font-size:1em">Agent 2 β€” Rule Learner</h3>'
                '<p class="cc-entry-desc">After each validated session, Agent 2 induces '
                'tentative coding rules from agreed codings. Rules are held in Tier 3 '
                'until a researcher promotes them to the validated lexicon β€” '
                'keeping the human firmly in the loop.</p>'
                '</div>'
            )
            gr.HTML(
                '<div class="cc-entry-card" style="border-top:3px solid #f43f5e">'
                '<span class="cc-entry-kicker">Design principle</span>'
                '<h3 class="cc-entry-title" style="font-size:1em">Human-in-the-loop</h3>'
                '<p class="cc-entry-desc">Every AI action is a proposal, not a decision. '
                'The researcher confirms sections, adjusts boundaries, codes independently, '
                'and approves lexicon updates. AI reduces mechanical effort; '
                'expert judgment drives all coding outcomes.</p>'
                '</div>'
            )

        gr.HTML(
            '<div style="text-align:center;padding:32px 0 16px;font-size:0.75rem;color:#94a3b8">'
            f'Model: <strong>{MODEL_ID.split("/")[-1]}</strong> Β· '
            f'Temperature: {TEMPERATURE} Β· '
            'Framework: Meier, Spada &amp; Rummel (2007) Β· Iiskala (2011)'
            '</div>'
        )

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 1: Setup
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_setup:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<span class="cc-page-label">Step 1 of 5 β€” Upload</span>'
            '<h2 class="cc-page-title">Load a Transcript</h2>'
            '</div>'
            '<div class="cc-steps">'
            '<span class="cc-step-active">1 Upload</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">2 Screen</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">3 Sections</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">4 Code</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">5 Done</span>'
            '</div>'
        )

        # ── Researcher ID ─────────────────────────────────────────────────
        gr.HTML(
            '<div style="font-weight:700;color:var(--cc-ink);margin:16px 0 4px">Your Researcher ID</div>'
            '<div style="font-size:0.82em;color:var(--cc-muted);margin-bottom:8px">'
            'A short label used to identify your coding file (e.g. R1, lara, jsmith).</div>'
        )
        researcher_id_box = gr.Textbox(
            label="",
            placeholder="e.g. R1",
            max_lines=1,
        )

        # ── Option A: Google Drive ────────────────────────────────────────
        gr.HTML(
            '<div style="border-top:1px solid var(--cc-border);margin:20px 0 12px"></div>'
            '<div style="font-weight:700;color:var(--cc-ink);margin-bottom:4px">Option A β€” Google Drive</div>'
            '<div style="font-size:0.82em;color:var(--cc-muted);margin-bottom:10px">'
            'Refresh the list, pick a transcript, then click Load.</div>'
        )
        with gr.Row():
            drive_refresh_btn = gr.Button("Refresh Drive list", variant="secondary", scale=2)
            load_prev_btn     = gr.Button("Resume session", variant="secondary", scale=1)

        drive_file_dropdown = gr.Dropdown(
            label="Select transcript",
            choices=[],
            interactive=False,
        )
        drive_status_html = gr.HTML()
        process_btn       = gr.Button("Load from Drive β†’", variant="primary")
        process_status    = gr.HTML()
        process_log       = gr.HTML()

        back_setup_btn = gr.Button("← Back to Home", size="sm")

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 2: Screener
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_screener:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<span class="cc-page-label">Step 2 of 5 β€” Pre-screen</span>'
            '<h2 class="cc-page-title">Metacognitive Screener</h2>'
            '</div>'
            '<div class="cc-steps">'
            '<span class="cc-step-done">βœ“ Upload</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-active">2 Screen</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">3 Sections</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">4 Code</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">5 Done</span>'
            '</div>'
        )

        # Summary chips β€” auto-populated when the page loads
        screener_summary_html = gr.HTML(
            value='<div style="padding:20px;text-align:center;color:var(--cc-muted)">'
                  'Running screener…</div>'
        )

        # Primary CTA β€” shown once screener finishes
        screener_to_sections_btn = gr.Button(
            "Detect Sections β†’", variant="primary", size="lg", visible=False
        )

        # Collapsible turn detail
        with gr.Accordion("Turn-by-turn detail", open=False):
            gr.HTML(
                '<div style="font-size:0.8em;color:var(--cc-muted);padding:6px 0 10px">'
                'Turns are colour-coded by composite score. '
                'Orange rows are candidate windows passed to Agent 0; '
                'grey rows are filtered out.</div>'
            )
            screener_turns_html_c = gr.HTML()

        # Re-run (only needed if auto-run failed)
        run_screener_btn = gr.Button(
            "Re-run Screener", variant="secondary", size="sm", visible=False
        )

        back_screener_btn = gr.Button("← Back to Upload", size="sm")

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 3: Sections review
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_sections:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<span class="cc-page-label">Step 2 of 4</span>'
            '<h2 class="cc-page-title">Review Sections</h2>'
            '</div>'
            '<div class="cc-steps">'
            '<span class="cc-step-done">βœ“ Setup</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-active">2 Sections</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">3 Code</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">4 Done</span>'
            '</div>'
        )

        sections_display_html = gr.HTML()

        gr.Markdown("**Rename sections** β€” edit the text after the colon, keep the `s01:` prefix:")
        sections_labels_box  = gr.Textbox(
            lines=10, show_label=False,
            placeholder="s01: Introduction\ns02: Main Discussion\n…",
        )
        confirm_sections_btn = gr.Button("Confirm Sections β†’", variant="primary")
        back_sections_btn    = gr.Button("← Back to Setup", size="sm")

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 3: Pipeline β€” boundaries + coding (per section)
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_pipeline:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<span class="cc-page-label">Step 3 of 4</span>'
            '<h2 class="cc-page-title">Detect Episodes &amp; Code</h2>'
            '</div>'
            '<div class="cc-steps">'
            '<span class="cc-step-done">βœ“ Setup</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-done">βœ“ Sections</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-active">3 Code</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-next">4 Done</span>'
            '</div>'
        )

        sections_overview_html = gr.HTML()

        # Live agent-activity banner β€” updated by callbacks to show what is running
        agent_activity_html = gr.HTML(
            '<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;'
            'padding:12px 16px;font-size:0.84em;color:#64748b;font-family:system-ui,sans-serif">'
            'No agent running. Click <strong>Detect Episode Boundaries</strong> to start.</div>'
        )

        # Sub-step A: Parallel boundary detection
        with gr.Column(visible=True) as col_run_all_boundaries:
            gr.HTML(
                '<div style="background:#eff6ff;border:1px solid #93c5fd;border-radius:10px;'
                'padding:14px 18px;margin-bottom:10px;font-size:0.87em;color:#1e3a8a;line-height:1.6">'
                '<strong>Agent 1a β€” Boundary Detector</strong> runs in parallel on all sections '
                'simultaneously. Processing time scales with the <em>longest</em> section, not '
                'total transcript length. '
                '<em>(Dean &amp; Ghemawat 2004 β€” parallel map; Schegloff 2007 β€” episode boundaries; '
                'Krippendorff 2004 β€” unitising precedes categorising)</em>'
                '</div>'
            )
            run_all_btn         = gr.Button("⚑ Detect Episode Boundaries (All Sections)", variant="primary")
            parallel_status_md  = gr.Markdown()
            parallel_stats_html = gr.HTML()

        section_header_md = gr.Markdown()

        # Sub-step B: Per-section boundary review
        with gr.Column(visible=False) as col_boundary_review:
            # Agent 1b will run here β€” show what principles it uses
            gr.HTML(
                '<div style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;'
                'padding:10px 16px;margin-bottom:8px;font-size:0.83em;color:#166534">'
                '<strong>Agent 1b β€” Dimension Coder</strong> will run after you confirm these boundaries. '
                'It uses: D1–D9 framework (Meier, Spada &amp; Rummel 2007) Β· '
                'Tier 1 hard rules (R01–R08) Β· Tier 2 learned rules Β· '
                'Uncertainty sampling (Settles 2012) to flag hard cases for your review.'
                '</div>'
            )

            # Episode count summary (compact table)
            boundary_display_html = gr.HTML()

            # Full dialogue view β€” the key UX improvement
            gr.HTML(
                '<div style="font-size:0.8em;font-weight:700;color:#475569;'
                'text-transform:uppercase;letter-spacing:0.06em;margin:10px 0 6px">'
                'Read the dialogue β€” verify each episode boundary</div>'
            )
            episode_dialogue_html = gr.HTML()

            # Edit controls
            gr.HTML(
                '<div style="font-size:0.82em;color:#334155;margin:10px 0 4px;'
                'padding:8px 12px;background:#f8fafc;border:1px solid #e2e8f0;'
                'border-radius:8px">'
                '<strong>Adjust if needed:</strong> enter the turn ID <em>after which</em> '
                'each new episode begins. Leave empty for a single undivided episode. '
                'The AI proposal is pre-filled β€” edit only where you disagree.'
                '</div>'
            )
            with gr.Row():
                boundary_ids_box = gr.Textbox(
                    label="Boundary turn IDs (comma-separated)",
                    placeholder="e.g.  12, 28, 35",
                    lines=1, scale=3,
                )
                confirm_boundaries_btn = gr.Button("Confirm & Run Agent 1b β†’",
                                                   variant="primary", scale=1)
            code_status = gr.Markdown()

        # Sub-step C: Coding canvas
        with gr.Column(visible=False) as col_coding:
            coding_progress_comp = gr.HTML()

            # ── Jump to segment β€” at the TOP before the transcript ──────────
            segment_jump = gr.Dropdown(
                label="Jump to segment", choices=[], value=None, interactive=True,
                info="Quickly navigate to any episode by ID."
            )

            with gr.Row(equal_height=False):
                # Left: transcript
                with gr.Column(scale=3, elem_classes=["cc-coding-transcript"]):
                    uncertainty_comp = gr.HTML()
                    turns_html_comp  = gr.HTML()
                    with gr.Row():
                        reveal_btn = gr.Button("β–Ά Reveal AI proposal", variant="secondary", size="sm")
                        gr.HTML(
                            '<p style="font-size:0.75em;color:#94a3b8;margin:auto 0;line-height:1.4">'
                            'Code independently first β€” reveal only if unsure '
                            '<em>(Settles 2012)</em></p>'
                        )
                    proposal_comp = gr.Markdown(visible=False)

                # Right: coding controls
                with gr.Column(scale=2, elem_classes=["cc-coding-controls"]):
                    gr.Markdown("#### D1–D9 Dimension")
                    dim_radio     = gr.Radio(choices=DIM_CHOICES, label="Primary", value=None)
                    dim_desc_comp = gr.HTML()

                    secondary_dim_drop = gr.Dropdown(
                        choices=SEC_DIM_CHOICES,
                        value=SEC_NONE,
                        label="Secondary dimension (optional)",
                        info="Only when a second dimension is clearly sustained throughout. Strijbos et al. (2006).",
                        interactive=True,
                    )

                    # ── SSRL section β€” hidden until a D1-D9 code is chosen ──
                    with gr.Column(visible=False) as ssrl_col:
                        gr.HTML(
                            '<div style="border-top:1px solid var(--cc-border);'
                            'margin:12px 0 8px;padding-top:10px">'
                            '<div style="font-weight:700;font-size:0.85em;color:var(--cc-ink);'
                            'text-transform:uppercase;letter-spacing:.05em;margin-bottom:4px">SSRL Phase</div>'
                            '<div style="font-size:0.72em;color:var(--cc-muted)">Iiskala (2011) Β· '
                            'JΓ€rvelΓ€ &amp; Hadwin (2013) β€” only shown when a D1-D9 code is selected</div></div>'
                        )
                        ssrl_radio = gr.Radio(
                            choices=SSRL_CHOICES,
                            label="Metacognitive phase",
                            value=SSRL_NONE,
                            info="Tag the dominant SSRL phase if metacognition is present.",
                        )

                    comment_box = gr.Textbox(
                        label="Note (optional)", lines=2,
                        placeholder="Ambiguity, competing codes…"
                    )
                    with gr.Row():
                        prev_btn = gr.Button("← Prev", size="sm")
                        next_btn = gr.Button("Next β†’", variant="primary", size="sm")
                        skip_btn = gr.Button("⊘ Skip", size="sm", variant="secondary")
                    gr.HTML(
                        '<p style="font-size:0.72em;color:#94a3b8;margin-top:4px;line-height:1.4">'
                        'Skip marks the episode as <em>not codeable</em> (small talk, off-topic) and moves on.</p>'
                    )

            next_section_btn = gr.Button(
                "β†’ Finish Section & Continue", variant="secondary", visible=False
            )

        with gr.Accordion("Agent Activity Log", open=False):
            pipeline_log = gr.HTML(_agent_log_html([]))

        back_pipeline_btn = gr.Button("← Back to Sections", size="sm")

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 4: Done
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_done:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<span class="cc-page-label">Step 4 of 4</span>'
            '<h2 class="cc-page-title">All Sections Coded</h2>'
            '</div>'
            '<div class="cc-steps">'
            '<span class="cc-step-done">βœ“ Setup</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-done">βœ“ Sections</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-done">βœ“ Coded</span>'
            '<span class="cc-step-sep">β€Ί</span>'
            '<span class="cc-step-active">4 Done</span>'
            '</div>'
        )

        gr.HTML(
            '<div class="cc-done-card">'
            '<div class="cc-done-title">Coding complete βœ“</div>'
            '<p class="cc-done-sub">'
            'Download your coding file and share it with your co-researcher. '
            'Both of you should complete the pipeline independently on the same '
            'transcript, then bring both files to the <strong>Agreement Check</strong>.'
            '</p>'
            '</div>'
        )

        download_btn  = gr.Button("Download My Coding File", variant="primary")
        download_file = gr.File(visible=False, label="Download")

        with gr.Row():
            go_agreement_btn = gr.Button("β†’ Check Agreement", variant="secondary")
            back_done_btn    = gr.Button("← Back to Pipeline")

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 5: Agreement
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_agreement:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<span class="cc-page-label">Inter-Rater Reliability</span>'
            '<h2 class="cc-page-title">Agreement Check</h2>'
            '</div>'
        )

        gr.HTML(
            '<div class="cc-callout">'
            '<strong>How it works:</strong>'
            '<ol style="margin:8px 0 0;padding-left:20px;line-height:1.9">'
            '<li>You complete the pipeline β†’ download <code>coding_R1.json</code></li>'
            '<li>Your co-researcher runs the same pipeline independently β†’ downloads their file</li>'
            '<li>Upload their file here to compute <strong>Gwet\'s AC1</strong> and Cohen\'s ΞΊ</li>'
            '<li>Gate: <strong>AC1 β‰₯ 0.70</strong> <em>(Landis &amp; Koch 1977)</em></li>'
            '<li>Resolve remaining disagreements β€” they feed Agent 2\'s learning cycle</li>'
            '</ol>'
            '</div>'
        )

        with gr.Row():
            r2_upload = gr.File(
                label="Co-researcher coding file (.json)",
                file_types=[".json"], scale=2
            )
            kappa_btn = gr.Button("Calculate Agreement", variant="primary", scale=1)

        kappa_html_comp  = gr.HTML()
        disagreements_md = gr.Markdown()

        with gr.Column(visible=False) as col_disagreements:
            gr.HTML(
                '<div style="background:#fffbeb;border:1px solid #fbbf24;'
                'border-radius:8px;padding:12px 16px;margin:12px 0;font-size:0.88em">'
                '<strong style="color:#78350f">Disagreement Resolution</strong>'
                '<p style="color:#92400e;margin:4px 0 0">For each disagreement: enter the '
                'segment ID, select the consensus dimension, add a rationale. '
                'Resolved segments become training data for Agent 2.</p>'
                '</div>'
            )
            with gr.Row():
                dis_seg_id = gr.Textbox(label="Segment ID", placeholder="e.g. dyad_01_s01_ep03", scale=2)
                dis_dim    = gr.Dropdown(label="Resolved dimension", choices=DIM_CHOICES, scale=2)
            dis_note = gr.Textbox(
                label="Rationale β€” why this dimension?", lines=2,
                placeholder="After discussion we agreed… because…"
            )
            with gr.Row():
                resolve_btn = gr.Button("Resolve βœ“", variant="primary")
                discard_btn = gr.Button("Discard segment", variant="secondary")
            dis_status = gr.Markdown()

        with gr.Accordion("Sequence Analysis (optional)", open=False):
            gr.HTML(
                '<div style="background:#f0fdf4;border:1px solid #86efac;'
                'border-radius:8px;padding:10px 14px;margin-bottom:10px;'
                'font-size:0.83em;color:#065f46">'
                '<strong>Temporal structure of the coded sequence.</strong> '
                'Frequency counts show <em>how much</em>; sequential analysis shows '
                '<em>what follows what</em>. '
                '<em>Bakeman &amp; Gottman (1986)</em>'
                '</div>'
            )
            with gr.Row():
                seq_rater_choice = gr.Dropdown(
                    label="Analyse coding from",
                    choices=["R1 (you)", "R2 (co-researcher)"],
                    value="R1 (you)", scale=2,
                )
                seq_run_btn = gr.Button("Run β†’", variant="primary", scale=1)

            seq_summary_md  = gr.Markdown()
            seq_matrix_html = gr.HTML()
            seq_sig_html    = gr.HTML()
            with gr.Column(visible=False) as col_seq_download:
                seq_dl_btn  = gr.Button("Download transition matrix (CSV)", variant="secondary", size="sm")
                seq_dl_file = gr.File(visible=False)

        with gr.Accordion("Agent Activity Log", open=False):
            agreement_log = gr.HTML(_agent_log_html([]))

        with gr.Row():
            back_agreement_btn = gr.Button("← Back to Done")
            go_library_btn     = gr.Button("β†’ Review AI Rules")

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 6: Library
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_library:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<span class="cc-page-label">Advanced</span>'
            '<h2 class="cc-page-title">AI Rule Library</h2>'
            '</div>'
        )

        gr.HTML(
            '<div class="cc-callout">'
            '<strong>How the learning loop works:</strong> Agent 2 analyses patterns '
            'across resolved disagreements and proposes rules to improve Agent 1b\'s '
            'future coding. Rules are <em>inactive</em> until approved here. '
            'Approved rules enter Tier 2 immediately. '
            '<em>(Amershi et al. 2014; Monarch 2021)</em>'
            '<br><br>'
            '⚠ Agent 2 requires β‰₯ 3 validated sessions and β‰₯ 90 coded segments '
            'before proposing rules <em>(Bujang &amp; Baharum 2017)</em>.'
            '</div>'
        )

        load_rules_btn  = gr.Button("Load Pending Rules", variant="primary")
        rules_html_comp = gr.HTML()

        with gr.Group():
            gr.Markdown("#### Approve or Reject a Rule")
            gr.Markdown(
                "Rejection reasons are logged β€” Agent 2 learns from them on the next cycle."
            )
            rule_selector = gr.Dropdown(label="Select rule", choices=[])
            rule_rid      = gr.Textbox(label="Researcher ID", placeholder="e.g. R1")
            rule_note     = gr.Textbox(
                label="Note (required for rejection, optional for approval)", lines=2,
                placeholder="This rule is consistent with sessions 3–5 because…"
            )
            with gr.Row():
                reject_rule_btn  = gr.Button("Reject βœ—", variant="secondary")
                approve_rule_btn = gr.Button("Approve βœ“", variant="primary")
            rule_status = gr.Markdown()

        with gr.Row():
            back_library_btn = gr.Button("← Back to Agreement")
            home_from_lib    = gr.Button("Home")
            open_lexicon_btn = gr.Button("Open Lexicon β†’")

    # ─────────────────────────────────────────────────────────────────────
    # PAGE 8: Lexicon manager
    # ─────────────────────────────────────────────────────────────────────
    with gr.Column(visible=False) as pg_lexicon:
        gr.HTML(
            '<div class="cc-page-nav">'
            '<h2 class="cc-page-title">Lexicon Manager</h2>'
            '</div>'
            '<div class="cc-callout">'
            'Tier 1 is research-locked (Iiskala 2011; Schoor &amp; Bannert 2012). '
            'Tier 2 accepts researcher-validated additions. '
            'Tier 3 collects candidates found during screening β€” review and promote them here.'
            '</div>'
        )

        with gr.Tabs():
            with gr.Tab("Tier 1 β€” Core (read-only)"):
                tier1_html = gr.HTML()
            with gr.Tab("Tier 2 β€” Validated"):
                tier2_html = gr.HTML()
                gr.HTML('<div style="margin-top:20px;font-weight:700;margin-bottom:6px">Add term to Tier 2</div>')
                with gr.Row():
                    t2_cat_id    = gr.Textbox(label="Category ID", placeholder="MON_custom")
                    t2_label     = gr.Textbox(label="Label", placeholder="Metacognitive hedge")
                    t2_phase     = gr.Dropdown(label="Phase", choices=["planning","monitoring","evaluating","ssrl"], value="monitoring")
                    t2_weight    = gr.Number(label="Weight (0–1)", value=0.5, minimum=0, maximum=1)
                t2_terms_box  = gr.Textbox(label="Terms (one per line or comma-separated)", lines=3)
                with gr.Row():
                    t2_researcher = gr.Textbox(label="Researcher ID", placeholder="R1")
                    t2_note       = gr.Textbox(label="Note (optional)")
                add_t2_btn   = gr.Button("Add to Tier 2", variant="primary")
                t2_status    = gr.HTML()
            with gr.Tab("Tier 3 β€” Candidates"):
                tier3_html    = gr.HTML()
                gr.HTML('<div style="margin-top:16px;font-weight:700">Approve or reject a candidate</div>')
                with gr.Row():
                    t3_term       = gr.Textbox(label="Term (exact text)")
                    t3_researcher = gr.Textbox(label="Researcher ID", placeholder="R1")
                t3_note       = gr.Textbox(label="Rejection note (optional)")
                with gr.Row():
                    t3_reject_btn  = gr.Button("Reject", variant="secondary")
                    t3_approve_btn = gr.Button("Approve", variant="primary")
                t3_status = gr.HTML()

        lex_error = gr.HTML()
        load_lexicon_btn = gr.Button("Refresh Lexicon", variant="secondary", size="sm")

        with gr.Row():
            back_lexicon_btn = gr.Button("← Back to Library")
            home_from_lex    = gr.Button("Home")

    # =====================================================================
    # ALL PAGES list (order must match _PAGE_NAMES)
    # =====================================================================
    ALL_PAGES = [pg_welcome, pg_setup, pg_screener, pg_sections, pg_pipeline,
                 pg_done, pg_agreement, pg_library, pg_lexicon]

    CODING_OUTPUTS = [
        coding_progress_comp,   # 0
        segment_jump,           # 1
        turns_html_comp,        # 2
        uncertainty_comp,       # 3
        proposal_comp,          # 4
        dim_radio,              # 5
        dim_desc_comp,          # 6
        secondary_dim_drop,     # 7
        comment_box,            # 8
        next_section_btn,       # 9
        ssrl_radio,             # 10 β€” SSRL phase tag
        ssrl_col,               # 11 β€” SSRL section visibility (show only for D1-D9)
    ]

    # fn_parse_transcript / fn_process_with_source outputs
    # state, pipeline_bar_html, process_status, process_btn,
    # screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES
    PARSE_OUTPUTS = [
        state, pipeline_bar_html, process_status, process_btn,
        screener_summary_html, screener_turns_html_c, screener_to_sections_btn,
        *ALL_PAGES,
    ]

    # fn_run_agent0 outputs
    # state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES
    AGENT0_OUTPUTS = [
        state, pipeline_bar_html, sections_display_html, sections_labels_box,
        *ALL_PAGES,
    ]

    # Legacy alias (used by load_prev_btn and other legacy code paths)
    PROCESS_OUTPUTS = PARSE_OUTPUTS

    # fn_confirm_sections outputs  (13 total β€” generator; includes button + sections_display)
    CONFIRM_SECTIONS_OUTPUTS = [
        state, *ALL_PAGES,
        sections_display_html,       # show busy state on yield-1; clear on yield-2
        confirm_sections_btn,        # disable on yield-1; re-enable on yield-2
        col_run_all_boundaries,
        col_boundary_review,
        col_coding,
    ]

    # fn_run_all_boundaries outputs  (10 total)
    RUN_ALL_OUTPUTS = [
        state,
        parallel_status_md,
        parallel_stats_html,
        col_boundary_review,
        boundary_display_html,
        boundary_ids_box,
        section_header_md,
        pipeline_log,
        agent_activity_html,
        episode_dialogue_html,   # NEW β€” full dialogue view per episode
    ]

    # fn_confirm_and_code outputs  (14 total)
    CONFIRM_CODE_OUTPUTS = [state, code_status, col_coding] + CODING_OUTPUTS + [pipeline_log]

    # fn_next_section outputs  (15 total β€” includes boundary + dialogue update for next section)
    NEXT_SECTION_OUTPUTS = [
        state, *ALL_PAGES,
        sections_overview_html,
        section_header_md,
        col_boundary_review,
        col_coding,
        boundary_display_html,   # re-populate for next section
        boundary_ids_box,        # re-populate for next section
        episode_dialogue_html,   # re-populate for next section
    ]

    # =====================================================================
    # WIRING
    # =====================================================================

    # Welcome navigation
    start_btn.click(lambda: _show("setup"), outputs=ALL_PAGES)
    agreement_nav_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
    library_nav_btn.click(lambda: _show("library"), outputs=ALL_PAGES)

    # Back buttons
    back_setup_btn.click(lambda: _show("welcome"), outputs=ALL_PAGES)
    back_sections_btn.click(
        fn=lambda st: _show("screener") if st.get("screener_result") else _show("setup"),
        inputs=[state], outputs=ALL_PAGES,
    )
    back_pipeline_btn.click(lambda: _show("sections"), outputs=ALL_PAGES)
    back_done_btn.click(lambda: _show("pipeline"), outputs=ALL_PAGES)
    back_agreement_btn.click(lambda: _show("done"), outputs=ALL_PAGES)
    back_library_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
    home_from_lib.click(lambda: _show("welcome"), outputs=ALL_PAGES)
    back_screener_btn.click(lambda: _show("setup"), outputs=ALL_PAGES)

    # Forward navigation
    go_agreement_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
    go_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES)

    # Setup: Drive β€” Phase 1 (parse + screen)
    drive_refresh_btn.click(
        fn=fn_refresh_drive_transcripts,
        inputs=[researcher_id_box],
        outputs=[drive_file_dropdown, drive_status_html],
    )
    load_prev_btn.click(
        fn=fn_load_previous_session,
        inputs=[researcher_id_box, state],
        outputs=PARSE_OUTPUTS,
    )
    process_btn.click(
        fn=fn_process_with_source,
        inputs=[drive_file_dropdown, researcher_id_box, state],
        outputs=PARSE_OUTPUTS,
    ).then(fn=lambda: gr.update(visible=True), outputs=[pipeline_bar_html])


    # Screener: manual re-run (only shown when auto-run failed)
    run_screener_btn.click(
        fn=fn_run_screener,
        inputs=[state],
        outputs=[state, pipeline_bar_html, screener_summary_html,
                 screener_turns_html_c, run_screener_btn],
    )

    # Screener β†’ Sections: Phase 2 (run Agent 0)
    screener_to_sections_btn.click(
        fn=fn_run_agent0,
        inputs=[state],
        outputs=AGENT0_OUTPUTS,
    )

    # Sections: confirm labels
    confirm_sections_btn.click(
        fn=fn_confirm_sections,
        inputs=[sections_labels_box, state],
        outputs=CONFIRM_SECTIONS_OUTPUTS,
    )

    # Pipeline: run boundaries in parallel
    run_all_btn.click(
        fn=fn_run_all_boundaries,
        inputs=[state],
        outputs=RUN_ALL_OUTPUTS,
    )

    # Pipeline: confirm boundaries + run Agent 1b
    confirm_boundaries_btn.click(
        fn=fn_confirm_and_code,
        inputs=[boundary_ids_box, state],
        outputs=CONFIRM_CODE_OUTPUTS,
    )

    # Coding navigation (now includes ssrl_radio)
    next_btn.click(
        fn=lambda d, sec, c, ssrl, s: fn_navigate(+1, d, sec, c, ssrl, s),
        inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, state],
        outputs=[state] + CODING_OUTPUTS,
    )
    prev_btn.click(
        fn=lambda d, sec, c, ssrl, s: fn_navigate(-1, d, sec, c, ssrl, s),
        inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, state],
        outputs=[state] + CODING_OUTPUTS,
    )
    segment_jump.change(
        fn=fn_jump,
        inputs=[segment_jump, state],
        outputs=[state] + CODING_OUTPUTS,
    )
    reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp])
    # dim_radio controls description AND shows/hides SSRL section
    dim_radio.change(
        fn=fn_dim_desc,
        inputs=[dim_radio],
        outputs=[dim_desc_comp, ssrl_col],
    )

    # Skip episode β€” mark as not codeable and advance
    skip_btn.click(
        fn=fn_skip_episode,
        inputs=[state],
        outputs=[state] + CODING_OUTPUTS,
    )

    # Finish section / go to done (now includes ssrl_radio)
    next_section_btn.click(
        fn=fn_next_section,
        inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, state],
        outputs=NEXT_SECTION_OUTPUTS,
    )

    # Download
    download_btn.click(fn=fn_download, inputs=[state], outputs=[download_file]).then(
        fn=lambda: gr.update(visible=True), outputs=[download_file]
    )

    # Agreement
    kappa_btn.click(
        fn=fn_calculate_kappa,
        inputs=[r2_upload, state],
        outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, agreement_log],
    )
    resolve_btn.click(
        fn=fn_resolve,
        inputs=[dis_seg_id, dis_dim, dis_note, state],
        outputs=[state, dis_status],
    )
    discard_btn.click(
        fn=fn_discard,
        inputs=[dis_seg_id, dis_note, state],
        outputs=[state, dis_status],
    )

    # Sequence analysis
    seq_run_btn.click(
        fn=fn_run_sequence_analysis,
        inputs=[seq_rater_choice, state],
        outputs=[seq_summary_md, seq_matrix_html, seq_sig_html, col_seq_download],
    )
    seq_dl_btn.click(
        fn=fn_download_seq_csv,
        inputs=[seq_rater_choice, state],
        outputs=[seq_dl_file],
    ).then(fn=lambda: gr.update(visible=True), outputs=[seq_dl_file])

    # Library
    load_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector])
    approve_rule_btn.click(
        fn=fn_approve, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
    )
    reject_rule_btn.click(
        fn=fn_reject, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
    )
    open_lexicon_btn.click(
        fn=fn_load_lexicon,
        outputs=[tier1_html, tier2_html, tier3_html, lex_error],
    ).then(lambda: _show("lexicon"), outputs=ALL_PAGES)

    # Lexicon navigation + actions
    back_lexicon_btn.click(lambda: _show("library"), outputs=ALL_PAGES)
    home_from_lex.click(lambda: _show("welcome"), outputs=ALL_PAGES)
    load_lexicon_btn.click(
        fn=fn_load_lexicon,
        outputs=[tier1_html, tier2_html, tier3_html, lex_error],
    )
    add_t2_btn.click(
        fn=fn_add_tier2_term,
        inputs=[t2_cat_id, t2_label, t2_phase, t2_terms_box, t2_weight,
                t2_researcher, t2_note],
        outputs=[t2_status, tier2_html, lex_error],
    )
    t3_approve_btn.click(
        fn=fn_approve_t3,
        inputs=[t3_term, t3_researcher],
        outputs=[t3_status, tier3_html],
    )
    t3_reject_btn.click(
        fn=fn_reject_t3,
        inputs=[t3_term, t3_researcher, t3_note],
        outputs=[t3_status, tier3_html],
    )


if __name__ == "__main__":
    demo.launch(css=CSS, theme=gr.themes.Soft(), ssr_mode=False)