File size: 97,696 Bytes
6b466f3
ca46a92
413f89f
d810a2e
673f6eb
413f89f
d810a2e
 
 
acd95b2
d810a2e
 
 
5a6721e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9217e4
cc71c22
 
f9217e4
5a6721e
cdb9fb7
 
 
 
 
 
 
5a6721e
 
 
a36909e
5a6721e
 
 
 
 
 
 
 
a36909e
 
5a6721e
 
 
d16ce7f
 
 
 
 
 
 
 
 
 
 
 
 
f2d6dd9
 
 
f9217e4
 
 
 
 
 
 
 
 
413f89f
f9217e4
 
 
 
 
 
 
ca46a92
f2d6dd9
 
 
ca46a92
 
cc71c22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb9fb7
563834d
cdb9fb7
 
 
 
 
 
 
 
 
59446c8
cdb9fb7
59446c8
cdb9fb7
 
 
 
 
 
acd95b2
d810a2e
 
4e0880e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e957e7
412ec3b
497a8a3
412ec3b
497a8a3
 
 
 
 
 
412ec3b
 
497a8a3
 
 
d16ce7f
 
 
 
 
 
 
 
 
 
 
 
412ec3b
3e957e7
412ec3b
3e957e7
412ec3b
3e957e7
412ec3b
3e957e7
412ec3b
3e957e7
 
d16ce7f
412ec3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a6721e
497a8a3
3e957e7
497a8a3
412ec3b
3e957e7
412ec3b
3e957e7
 
 
412ec3b
 
3e957e7
 
 
 
 
 
 
412ec3b
 
 
3e957e7
412ec3b
3e957e7
 
 
 
c34d640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412ec3b
c34d640
 
 
 
 
3e957e7
 
 
 
412ec3b
 
 
fb11199
 
 
 
 
 
 
 
 
 
412ec3b
 
 
 
 
 
 
fb11199
412ec3b
 
 
 
fb11199
412ec3b
 
 
 
 
 
 
 
 
cdb9fb7
2462f17
cdb9fb7
 
 
 
 
 
 
d810a2e
 
828dde2
d810a2e
 
 
 
 
cdb9fb7
 
d810a2e
828dde2
cdb9fb7
 
 
d810a2e
 
cdb9fb7
d810a2e
cdb9fb7
 
d810a2e
 
b45c877
 
 
828dde2
b45c877
 
 
828dde2
 
 
 
b45c877
 
 
 
 
 
828dde2
b45c877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb9fb7
 
 
 
 
d810a2e
cdb9fb7
d810a2e
b45c877
cdb9fb7
b45c877
d810a2e
b45c877
 
cdb9fb7
 
d810a2e
 
cdb9fb7
 
b45c877
 
cdb9fb7
 
 
b45c877
 
d810a2e
 
cdb9fb7
b45c877
 
 
 
828dde2
d810a2e
 
b45c877
cdb9fb7
d810a2e
 
 
 
 
b45c877
cdb9fb7
d810a2e
 
 
b45c877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acd95b2
00ecebc
acd95b2
ce87c24
2462f17
 
 
 
 
 
 
 
 
5a6721e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff4f0e7
f2d6dd9
ff4f0e7
 
 
 
 
 
 
 
 
 
 
 
 
 
f2d6dd9
 
 
 
 
ff4f0e7
 
f2d6dd9
 
 
 
a36909e
f2d6dd9
 
 
ff4f0e7
 
 
 
f2d6dd9
 
a36909e
ff4f0e7
 
f2d6dd9
ff4f0e7
 
ca46a92
413f89f
ca46a92
cc71c22
 
 
 
ff4f0e7
 
413f89f
ff4f0e7
 
f2d6dd9
ca46a92
ff4f0e7
 
f2d6dd9
ff4f0e7
 
 
f2d6dd9
ff4f0e7
 
 
 
 
 
 
 
 
 
 
413f89f
ff4f0e7
 
 
 
 
 
f9217e4
ff4f0e7
 
 
 
 
cc71c22
 
 
 
 
 
 
 
 
 
 
 
 
 
ff4f0e7
 
 
 
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413f89f
ff4f0e7
 
f2d6dd9
 
 
 
 
cc71c22
f2d6dd9
cc71c22
 
 
ff4f0e7
 
 
 
 
f2d6dd9
 
 
 
 
 
 
 
 
 
ff4f0e7
 
f2d6dd9
 
 
 
 
 
ff4f0e7
 
 
f2d6dd9
ff4f0e7
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
217de2a
f2d6dd9
 
217de2a
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217de2a
f2d6dd9
 
 
 
 
 
 
 
 
 
cc71c22
f2d6dd9
 
 
 
 
 
 
cc71c22
f2d6dd9
 
 
 
 
 
cc71c22
f2d6dd9
 
 
 
217de2a
f2d6dd9
 
 
413f89f
f2d6dd9
 
 
bc33023
f2d6dd9
 
f9217e4
f2d6dd9
 
 
 
 
 
 
 
f9217e4
f2d6dd9
413f89f
f2d6dd9
 
 
 
 
 
 
 
 
 
217de2a
f2d6dd9
 
 
413f89f
f2d6dd9
 
 
413f89f
f2d6dd9
 
 
413f89f
f2d6dd9
 
217de2a
f2d6dd9
 
217de2a
f2d6dd9
 
217de2a
f2d6dd9
 
 
 
 
 
 
 
cc71c22
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc71c22
f2d6dd9
 
 
 
 
 
 
 
 
cc71c22
f2d6dd9
 
 
 
 
 
 
 
 
 
d5ebf36
f2d6dd9
 
 
 
 
 
 
 
 
 
bc33023
 
aaa0c7a
f2d6dd9
 
 
 
 
aaa0c7a
 
 
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc33023
ca46a92
 
 
413f89f
bc33023
 
f2d6dd9
 
bc33023
 
aaa0c7a
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413f89f
bc33023
aaa0c7a
f2d6dd9
 
 
 
 
 
 
 
 
 
bc33023
 
 
f2d6dd9
bc33023
aaa0c7a
f2d6dd9
 
aaa0c7a
f2d6dd9
aaa0c7a
 
f2d6dd9
 
 
aaa0c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ebf36
 
5a6721e
 
 
 
 
 
 
 
 
ff4f0e7
 
 
 
5a6721e
 
 
 
ff4f0e7
5a6721e
 
 
 
ff4f0e7
 
 
 
d16ce7f
 
 
 
 
 
 
 
 
 
 
 
5a6721e
 
 
 
 
 
 
 
 
ff4f0e7
 
 
 
5a6721e
 
 
 
ff4f0e7
5a6721e
 
 
 
ff4f0e7
 
 
 
d16ce7f
 
 
 
 
 
 
 
 
 
 
 
5a6721e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d16ce7f
 
 
 
 
 
 
 
 
 
 
5a6721e
 
d5ebf36
 
5a6721e
 
ff4f0e7
 
5a6721e
 
ff4f0e7
d5ebf36
 
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff4f0e7
 
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a6721e
 
 
f2d6dd9
ff4f0e7
d5ebf36
f2d6dd9
 
 
 
 
 
 
 
 
 
 
 
d5ebf36
ff4f0e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ebf36
 
ff4f0e7
 
 
d5ebf36
ff4f0e7
 
d5ebf36
ff4f0e7
 
 
d5ebf36
 
ff4f0e7
 
 
d5ebf36
 
685ce0a
 
 
 
 
 
 
 
 
 
 
 
d16ce7f
685ce0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a6721e
685ce0a
 
 
 
 
5a6721e
685ce0a
 
 
 
 
5a6721e
685ce0a
 
 
 
 
 
 
b3c9281
 
 
 
d16ce7f
685ce0a
b3c9281
 
685ce0a
 
b3c9281
685ce0a
 
 
 
 
b3c9281
 
685ce0a
 
 
 
 
 
 
b3c9281
685ce0a
 
b3c9281
685ce0a
 
d16ce7f
b3c9281
ff4f0e7
b3c9281
ff4f0e7
b3c9281
ff4f0e7
 
 
b3c9281
 
ff4f0e7
 
 
 
 
 
 
 
b3c9281
ff4f0e7
b3c9281
ff4f0e7
d16ce7f
b3c9281
ff4f0e7
b3c9281
ff4f0e7
 
 
 
 
b3c9281
 
 
ff4f0e7
 
b3c9281
 
 
ff4f0e7
b3c9281
 
ff4f0e7
b3c9281
ff4f0e7
d16ce7f
b3c9281
ff4f0e7
b3c9281
ff4f0e7
 
 
 
 
b3c9281
 
 
 
 
ff4f0e7
 
 
d16ce7f
ff4f0e7
 
b3c9281
 
 
 
 
 
 
ff4f0e7
b3c9281
 
 
 
ff4f0e7
b3c9281
ff4f0e7
 
b3c9281
 
 
ff4f0e7
b3c9281
 
 
 
d16ce7f
ff4f0e7
 
b3c9281
ff4f0e7
 
 
 
 
d16ce7f
b3c9281
ff4f0e7
b3c9281
ff4f0e7
 
 
b3c9281
 
ff4f0e7
b3c9281
ff4f0e7
 
 
 
b3c9281
ff4f0e7
 
 
 
 
 
d16ce7f
ff4f0e7
b3c9281
 
 
ff4f0e7
b3c9281
ff4f0e7
 
 
 
 
d16ce7f
b3c9281
685ce0a
b3c9281
685ce0a
b3c9281
685ce0a
b3c9281
685ce0a
 
 
 
e0d7ad2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb11199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7ad2
fb11199
 
e0d7ad2
 
 
 
fb11199
 
 
217de2a
992e1e4
 
 
 
fb11199
 
992e1e4
 
 
 
fb11199
 
 
 
 
 
 
 
 
 
 
 
 
 
00ecebc
217de2a
fb11199
 
 
 
 
 
 
 
 
217de2a
fb11199
 
 
00ecebc
 
 
5a6721e
 
d5ebf36
5a6721e
 
d5ebf36
5a6721e
 
217de2a
5a6721e
 
 
d5ebf36
5a6721e
 
d5ebf36
 
 
 
 
 
5a6721e
 
d5ebf36
 
 
 
cdb9fb7
df53987
 
5a6721e
 
 
 
 
 
 
c34d640
 
 
 
 
 
 
 
 
 
497a8a3
 
 
 
 
 
 
5a6721e
c34d640
 
 
497a8a3
 
 
df53987
 
 
 
 
 
 
 
 
d16ce7f
df53987
 
497a8a3
 
 
412ec3b
 
497a8a3
c34d640
 
 
 
 
 
412ec3b
 
 
497a8a3
 
df53987
 
 
 
 
 
 
 
 
4e0880e
 
 
 
412ec3b
 
 
 
 
4e0880e
df53987
5a6721e
df53987
 
 
 
 
 
 
4e0880e
df53987
 
 
 
 
 
 
412ec3b
497a8a3
3e957e7
df53987
 
4e0880e
 
 
df53987
412ec3b
497a8a3
 
412ec3b
497a8a3
5a6721e
413f89f
 
 
 
 
 
497a8a3
 
 
5a6721e
497a8a3
 
 
 
 
 
 
 
 
8ae58e0
 
 
 
 
df53987
 
5a6721e
413f89f
 
 
 
 
 
4cf2029
df53987
9c45409
 
df53987
 
 
 
 
 
 
 
497a8a3
412ec3b
3e957e7
df53987
 
 
 
 
 
 
 
 
 
5a6721e
df53987
 
 
 
 
 
 
 
 
 
5a6721e
df53987
 
 
5a6721e
 
 
 
df53987
8ae58e0
412ec3b
df53987
 
 
5a6721e
 
df53987
 
 
 
 
 
6479c2d
df53987
 
 
 
5a6721e
 
 
 
 
 
 
 
 
 
 
 
df53987
5a6721e
df53987
 
6479c2d
9c45409
df53987
 
5a6721e
 
 
df53987
 
 
 
d16ce7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df53987
bc33023
cdb9fb7
06f6c6e
 
 
 
 
 
 
 
 
d16ce7f
6479c2d
 
 
 
 
 
06f6c6e
6479c2d
 
 
 
 
 
06f6c6e
 
6479c2d
06f6c6e
 
df53987
b45c877
 
a8885dd
b45c877
 
 
df53987
 
 
b45c877
6479c2d
497a8a3
 
412ec3b
497a8a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413f89f
6479c2d
b45c877
9c45409
b45c877
6479c2d
8ae58e0
b45c877
 
 
 
6479c2d
de0693a
b45c877
 
 
fa38e18
b45c877
 
9c45409
b45c877
 
 
 
 
 
 
 
 
 
8ae58e0
 
df53987
 
 
2d98216
 
 
 
 
06f6c6e
2d98216
2462f17
 
2d98216
 
 
d16ce7f
 
 
412ec3b
2d98216
d16ce7f
 
 
 
2d98216
 
 
 
 
 
 
 
 
06f6c6e
2d98216
 
 
 
 
 
 
 
 
 
 
 
 
 
5a6721e
de0693a
2d98216
de0693a
2d98216
 
 
 
d16ce7f
 
 
 
2d98216
 
 
 
b3c9281
5a6721e
ff4f0e7
 
 
b3c9281
 
5a6721e
 
d16ce7f
 
 
5a6721e
b3c9281
 
 
 
5a6721e
b3c9281
 
 
 
 
ff4f0e7
5a6721e
 
ff4f0e7
 
5a6721e
ff4f0e7
d16ce7f
 
 
ff4f0e7
b3c9281
d16ce7f
 
 
 
 
5a6721e
ff4f0e7
 
b3c9281
 
ff4f0e7
 
 
 
b3c9281
5a6721e
 
b3c9281
 
ff4f0e7
 
 
 
b3c9281
5a6721e
b3c9281
ff4f0e7
b3c9281
ff4f0e7
 
d16ce7f
 
 
 
 
5a6721e
ff4f0e7
 
 
b3c9281
5a6721e
 
ff4f0e7
 
b3c9281
ff4f0e7
 
5a6721e
 
 
ff4f0e7
 
5a6721e
ff4f0e7
d16ce7f
 
 
 
5a6721e
 
 
 
ff4f0e7
d16ce7f
 
 
 
 
ff4f0e7
 
5a6721e
ff4f0e7
5a6721e
 
b3c9281
 
 
 
 
ff4f0e7
b3c9281
 
5a6721e
b3c9281
 
 
 
ff4f0e7
 
5a6721e
 
b3c9281
5a6721e
 
 
ff4f0e7
5a6721e
b3c9281
 
ff4f0e7
 
 
bc33023
 
d16ce7f
 
 
5a6721e
aaa0c7a
 
bc33023
 
 
 
 
 
 
 
 
 
 
 
 
d16ce7f
 
 
 
 
 
 
bc33023
d16ce7f
 
 
 
 
 
 
bc33023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a6721e
bc33023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673f6eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6479c2d
8ae58e0
 
 
 
 
06f6c6e
d16ce7f
9c45409
242d732
8ae58e0
 
 
242d732
8ae58e0
9c45409
6479c2d
5a6721e
 
 
 
d5ebf36
 
 
 
 
 
 
 
 
9c45409
ce7e958
5a6721e
 
 
d16ce7f
 
 
 
5a6721e
d16ce7f
 
5a6721e
 
 
d16ce7f
 
 
5a6721e
 
d16ce7f
5a6721e
 
d16ce7f
5a6721e
d16ce7f
5a6721e
d16ce7f
 
5a6721e
 
d16ce7f
 
 
 
 
 
 
5a6721e
 
fb11199
 
 
 
 
 
 
 
 
 
90c4601
 
 
fb11199
 
90c4601
0c9b101
fb11199
 
 
90c4601
fb11199
0c9b101
fb11199
 
 
 
 
90c4601
fb11199
 
 
 
 
 
cdb9fb7
 
 
d810a2e
cdb9fb7
71cbc6e
b45c877
ce87c24
d16ce7f
 
 
 
 
b45c877
d810a2e
 
6b466f3
8ae58e0
87739b8
 
 
 
d810a2e
 
 
 
59446c8
 
d810a2e
6b466f3
9c45409
 
8ae58e0
9c45409
 
71cbc6e
242d732
1b02279
 
 
 
 
 
 
 
 
 
b45c877
5a6721e
6b466f3
 
 
5a6721e
 
6b466f3
 
 
cdb9fb7
828dde2
0d89397
 
 
cdb9fb7
 
 
acd95b2
2462f17
ce87c24
06f6c6e
6479c2d
06f6c6e
 
1b02279
 
 
 
 
 
 
 
 
 
 
 
 
df53987
ce87c24
563834d
1b02279
 
 
 
 
 
 
 
 
 
 
 
 
df53987
ce87c24
 
 
 
2462f17
ce87c24
 
2462f17
acd95b2
d16ce7f
 
 
d5ebf36
df53987
b45c877
 
9c45409
b45c877
 
 
 
 
 
 
df53987
 
 
 
9c45409
df53987
 
 
 
 
 
 
 
 
2d98216
06f6c6e
2d98216
 
 
 
 
 
 
ce87c24
 
06f6c6e
ce87c24
 
 
de0693a
 
2462f17
 
d16ce7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ebf36
242d732
6479c2d
0c9b101
d16ce7f
c5f844f
8ae58e0
9c45409
 
d16ce7f
06f6c6e
0c9b101
06f6c6e
8ae58e0
 
df53987
0c9b101
df53987
2d98216
4cf2029
 
 
 
 
 
 
 
df53987
 
0c9b101
df53987
 
673f6eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b45c877
 
a2c82ca
df53987
0c9b101
df53987
2d98216
cdb9fb7
 
a2c82ca
06f6c6e
0c9b101
6479c2d
06f6c6e
 
a2c82ca
0c9b101
a2c82ca
 
06f6c6e
 
 
 
 
a2c82ca
 
 
df53987
ce87c24
90b2356
2d98216
4cf0b98
 
a2c82ca
df53987
ce87c24
90b2356
2d98216
2462f17
 
673f6eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5ebf36
dbf3c04
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
import html
import time
import threading
from datetime import datetime
from functools import lru_cache
from concurrent.futures import ThreadPoolExecutor, as_completed

import gradio as gr
import pandas as pd
import requests
from huggingface_hub import HfApi


# ============================================================
# Constants / shared config
# ============================================================
REPO_KINDS = ("model", "dataset", "space")
REPO_KIND_LABELS = {
    "model": "Models",
    "dataset": "Datasets",
    "space": "Spaces",
}
REPO_KIND_EMOJIS = {
    "model": "🧠",
    "dataset": "📦",
    "space": "🚀",
}
REPO_KIND_PALETTES = {
    "model": "blue",
    "dataset": "pink",
    "space": "orange",
}

RECENT_ACTIVITY_LIMIT = 20
RECENT_ACTIVITY_MAX_PAGES = 300
RECENT_ACTIVITY_MAX_STALLED_PAGES = 5


# ============================================================
# API
# ============================================================
def get_api(token: str | None = None) -> HfApi:
    return HfApi(token=token) if token else HfApi()


# ============================================================
# HTTP helpers
# ============================================================
def build_session(accept: str, token: str | None = None) -> requests.Session:
    session = requests.Session()
    session.headers.update(
        {
            "User-Agent": "hf-contributions-app/1.0",
            "Accept": accept,
            "Cache-Control": "no-cache",
        }
    )
    if token:
        session.headers["Authorization"] = f"Bearer {token}"
    return session


# ============================================================
# Viewer helpers
# ============================================================
def get_viewer_username(profile: gr.OAuthProfile | None) -> str | None:
    return getattr(profile, "username", None) if profile is not None else None


def is_self_view(username: str, profile: gr.OAuthProfile | None) -> bool:
    username = (username or "").strip()
    viewer = get_viewer_username(profile)
    return bool(viewer and username and viewer.lower() == username.lower())


# ============================================================
# Recent-activity shared helpers
# ============================================================
def normalize_recent_activity_payload(payload):
    if isinstance(payload, list):
        return payload, None

    if isinstance(payload, dict):
        events = payload.get("recentActivity")
        if isinstance(events, list):
            return events, payload.get("cursor")

        for key in ["items", "events", "activity"]:
            value = payload.get(key)
            if isinstance(value, list):
                return value, payload.get("cursor")

    return [], None


def get_year_bounds(selected_year: int):
    year_start = pd.Timestamp(f"{selected_year}-01-01", tz="UTC")
    year_end = pd.Timestamp(f"{selected_year}-12-31 23:59:59.999999", tz="UTC")
    return year_start, year_end


def build_events_page_signature(events: list[dict]) -> tuple:
    signature = []
    for event in events:
        if not isinstance(event, dict):
            continue
        signature.append(
            (
                event.get("eventId"),
                event.get("time"),
                event.get("repoId"),
                event.get("type"),
                event.get("targetUrl"),
            )
        )
    return tuple(signature)


def parse_recent_activity_event_ts(event: dict):
    raw_time = event.get("time")
    if not raw_time:
        return None
    try:
        return pd.to_datetime(raw_time, utc=True)
    except Exception:
        return None


def update_recent_activity_progress(
    event_ts,
    *,
    year_start,
    year_end,
    oldest_event_ts_seen,
    page_oldest_event_ts,
    seen_target_year,
    crossed_before_year_start,
):
    if event_ts is None:
        return (
            oldest_event_ts_seen,
            page_oldest_event_ts,
            seen_target_year,
            crossed_before_year_start,
        )

    if oldest_event_ts_seen is None or event_ts < oldest_event_ts_seen:
        oldest_event_ts_seen = event_ts

    if page_oldest_event_ts is None or event_ts < page_oldest_event_ts:
        page_oldest_event_ts = event_ts

    if year_start <= event_ts <= year_end:
        seen_target_year = True
    elif event_ts < year_start:
        crossed_before_year_start = True

    return (
        oldest_event_ts_seen,
        page_oldest_event_ts,
        seen_target_year,
        crossed_before_year_start,
    )


def update_stalled_pagination_state(
    *,
    page_oldest_event_ts,
    previous_oldest_event_ts_seen,
    stalled_oldest_count,
):
    if previous_oldest_event_ts_seen is not None and page_oldest_event_ts is not None:
        if page_oldest_event_ts >= previous_oldest_event_ts_seen:
            stalled_oldest_count += 1
        else:
            stalled_oldest_count = 0

    if page_oldest_event_ts is not None:
        previous_oldest_event_ts_seen = page_oldest_event_ts

    return previous_oldest_event_ts_seen, stalled_oldest_count


# ============================================================
# Thread-safe rate limiters
# ============================================================
class RateLimiter:
    def __init__(self, calls_per_second=10):
        self.calls_per_second = calls_per_second
        self.last_call = 0.0
        self.lock = threading.Lock()

    def wait(self):
        with self.lock:
            now = time.time()
            min_interval = 1.0 / self.calls_per_second
            elapsed = now - self.last_call
            if elapsed < min_interval:
                time.sleep(min_interval - elapsed)
            self.last_call = time.time()


rate_limiter = RateLimiter(calls_per_second=10)
recent_activity_rate_limiter = RateLimiter(calls_per_second=1.0)


# ============================================================
# Simple in-memory cache
# ============================================================
CACHE = {}
CACHE_TTL = 60 * 10  # 10 minutes
CACHE_LOCK = threading.Lock()


def get_cache(key):
    with CACHE_LOCK:
        entry = CACHE.get(key)
        if not entry:
            return None

        value, timestamp = entry
        if time.time() - timestamp > CACHE_TTL:
            del CACHE[key]
            return None

        print(f"[CACHE HIT] {key}")
        return value


def set_cache(key, value):
    with CACHE_LOCK:
        CACHE[key] = (value, time.time())


# ============================================================
# Username validation / identity resolution
# ============================================================
def empty_identity(username: str, error: str):
    username = (username or "").strip()
    return {
        "exists": False,
        "username": username,
        "fullname": None,
        "display_name": f"@{username}" if username else "",
        "error": error,
        "source": "empty",
    }


def resolve_identity(username: str, profile: gr.OAuthProfile | None):
    username = (username or "").strip()
    if not username:
        return empty_identity("", "No username provided.")
    return validate_username(username, profile)


def is_invalid_identity(identity: dict, username: str) -> bool:
    username = (username or "").strip()
    return bool(username and not identity.get("exists"))


def validate_username(username: str, profile: gr.OAuthProfile | None):
    username = (username or "").strip()

    if not username:
        return empty_identity(username, "No username provided.")

    cache_key = ("identity", username.lower())
    cached = get_cache(cache_key)
    if cached is not None:
        return cached

    profile_username = get_viewer_username(profile)
    profile_name = getattr(profile, "name", None) if profile is not None else None

    if profile_username and profile_username.lower() == username.lower():
        result = {
            "exists": True,
            "username": profile_username,
            "fullname": profile_name.strip() if isinstance(profile_name, str) and profile_name.strip() else None,
            "display_name": (
                f"{profile_name.strip()} (@{profile_username})"
                if isinstance(profile_name, str) and profile_name.strip()
                else f"@{profile_username}"
            ),
            "error": None,
            "source": "oauth",
        }
        set_cache(cache_key, result)
        return result

    session = build_session("text/html,application/json")

    try:
        response = session.get(
            f"https://huggingface.co/{username}",
            timeout=15,
            allow_redirects=True,
        )

        if response.status_code == 404:
            result = empty_identity(username, f"Username or org '{username}' was not found.")
            result["source"] = "profile_page"
            set_cache(cache_key, result)
            return result

        response.raise_for_status()

        result = {
            "exists": True,
            "username": username,
            "fullname": None,
            "display_name": f"@{username}",
            "error": None,
            "source": "profile_page",
        }
        set_cache(cache_key, result)
        return result

    except requests.HTTPError:
        result = empty_identity(
            username,
            f"Username or org '{username}' could not be verified."
        )
        result["source"] = "profile_page_error"
        set_cache(cache_key, result)
        return result

    except requests.RequestException:
        result = empty_identity(
            username,
            "Could not verify this username right now. Please try again."
        )
        result["source"] = "network_error"
        set_cache(cache_key, result)
        return result

    except Exception:
        result = empty_identity(
            username,
            "Could not verify this username right now. Please try again."
        )
        result["source"] = "unknown_error"
        set_cache(cache_key, result)
        return result


# ============================================================
# Public cache only
# ============================================================
def list_items_with_api(api: HfApi, username: str, kind: str):
    fetchers = {
        "model": api.list_models,
        "dataset": api.list_datasets,
        "space": api.list_spaces,
    }
    fetcher = fetchers.get(kind)
    return list(fetcher(author=username)) if fetcher else []


@lru_cache(maxsize=1000)
def cached_list_commits_public(repo_id: str, repo_type: str):
    return list(HfApi().list_repo_commits(repo_id=repo_id, repo_type=repo_type))


@lru_cache(maxsize=200)
def cached_list_items_public(username: str, kind: str):
    return list_items_with_api(HfApi(), username, kind)


def list_items(username: str, kind: str, token: str | None = None):
    if token:
        return list_items_with_api(get_api(token), username, kind)
    return cached_list_items_public(username, kind)


def list_commits(repo_id: str, repo_type: str, token: str | None = None):
    if token:
        return list(get_api(token).list_repo_commits(repo_id=repo_id, repo_type=repo_type))
    return cached_list_commits_public(repo_id, repo_type)


# ============================================================
# Repo activity fetch
# ============================================================
def fetch_commits_for_repo(
    repo_id: str,
    repo_type: str,
    selected_year: int,
    token: str | None = None,
):
    try:
        rate_limiter.wait()
        commits = list_commits(repo_id, repo_type, token=token)

        commit_dates = []
        commit_count = 0

        for commit in commits:
            commit_created_at = getattr(commit, "created_at", None)
            if commit_created_at is None:
                continue

            dt = pd.to_datetime(commit_created_at).tz_localize(None).date()
            if dt.year == selected_year:
                commit_dates.append(dt)
                commit_count += 1

        return commit_dates, commit_count, None

    except Exception as e:
        return [], 0, f"{repo_type}:{repo_id} -> {str(e)}"


def build_repo_entry(item, kind: str, selected_year: int, token: str | None = None):
    repo_id = item.id
    is_private = bool(getattr(item, "private", False))

    created_dates = []
    created_at = getattr(item, "created_at", None)
    if created_at is not None:
        dt = pd.to_datetime(created_at).tz_localize(None).date()
        if dt.year == selected_year:
            created_dates.append(dt)

    repo_commit_dates, repo_commit_count, err = fetch_commits_for_repo(
        repo_id=repo_id,
        repo_type=kind,
        selected_year=selected_year,
        token=token,
    )

    created_count = len(created_dates)
    activity_dates = created_dates + repo_commit_dates
    activity_count = created_count + repo_commit_count

    return {
        "repo_id": repo_id,
        "kind": kind,
        "is_private": is_private,
        "created_dates": created_dates,
        "created_count": created_count,
        "repo_commit_dates": repo_commit_dates,
        "repo_commit_count": repo_commit_count,
        "activity_dates": activity_dates,
        "activity_count": activity_count,
        "error": err,
    }


def collect_kind_repo_entries(
    username: str,
    kind: str,
    selected_year: int,
    token: str | None = None,
):
    try:
        items = list_items(username, kind, token=token)

        repo_entries = []
        errors = []
        chunk_size = 5

        for i in range(0, len(items), chunk_size):
            chunk = items[i:i + chunk_size]
            if not chunk:
                continue

            with ThreadPoolExecutor(max_workers=min(5, len(chunk))) as executor:
                futures = {
                    executor.submit(
                        build_repo_entry,
                        item,
                        kind,
                        selected_year,
                        token,
                    ): item.id
                    for item in chunk
                }

                for future in as_completed(futures):
                    entry = future.result()
                    repo_entries.append(entry)
                    if entry["error"]:
                        errors.append(entry["error"])

        return {
            "total_items": len(items),
            "repos": repo_entries,
            "errors": errors,
        }

    except Exception as e:
        return {
            "total_items": 0,
            "repos": [],
            "errors": [f"Error fetching {kind}s for {username}: {str(e)}"],
        }


def aggregate_repo_entries(repo_entries: list[dict], include_private: bool):
    filtered = repo_entries if include_private else [r for r in repo_entries if not r["is_private"]]

    created_dates = []
    repo_commit_dates = []
    activity_dates = []
    created_count = 0
    repo_commit_count = 0
    repos_with_activity = 0

    for repo in filtered:
        created_dates.extend(repo["created_dates"])
        repo_commit_dates.extend(repo["repo_commit_dates"])
        activity_dates.extend(repo["activity_dates"])
        created_count += repo["created_count"]
        repo_commit_count += repo["repo_commit_count"]

        if repo["activity_count"] > 0:
            repos_with_activity += 1

    return {
        "created_dates": created_dates,
        "created_count": created_count,
        "repo_commit_dates": repo_commit_dates,
        "repo_commit_count": repo_commit_count,
        "activity_dates": activity_dates,
        "activity_count": created_count + repo_commit_count,
        "repos_with_activity": repos_with_activity,
    }


# ============================================================
# Generic activity bucket helpers
# ============================================================
def empty_activity_bucket(title: str):
    return {
        "title": title,
        "fetched": False,
        "dates": [],
        "count": 0,
        "logs": f"{title} not fetched yet.",
    }


def empty_bucketed_activity_state(
    selected_year: int,
    logs_text: str,
    bucket_titles: dict[str, str],
):
    state = {
        "username": "",
        "selected_year": int(selected_year),
        "fetched": False,
        "logs": logs_text,
    }

    for key, title in bucket_titles.items():
        state[key] = empty_activity_bucket(title)

    return state


def build_fetched_bucket(title: str, dates: list, selected_year: int, label: str):
    return {
        "title": title,
        "fetched": True,
        "dates": dates,
        "count": len(dates),
        "logs": f"Found {len(dates)} {label} in {selected_year}.",
    }


def build_failed_bucket(title: str):
    return {
        "title": title,
        "fetched": True,
        "dates": [],
        "count": 0,
        "logs": "",
    }


def build_invalid_section_state(username: str, selected_year: int, empty_state_fn, identity: dict):
    state = empty_state_fn(selected_year)
    state["username"] = username
    state["selected_year"] = int(selected_year)
    state["logs"] = identity.get("error") or f"Username or org '{username}' was not found."
    return state


# ============================================================
# Community activity state
# ============================================================
def empty_community_state(selected_year: int):
    return {
        "username": "",
        "selected_year": int(selected_year),
        "fetched": False,
        "pr_opened": empty_activity_bucket("Pull Requests"),
        "pr_activity": empty_activity_bucket("PR Activity"),
        "thread_opened": empty_activity_bucket("Community Threads"),
        "discussion_activity": empty_activity_bucket("Community Activity"),
        "logs": "Community activity not fetched yet.",
    }


# ============================================================
# Generic recent-activity engine
# ============================================================
def collect_recent_activity(
    *,
    username: str,
    selected_year: int,
    activity_type: str,
    processor,
    build_session_fn,
    rate_limiter_obj,
    token: str | None = None,
    limit: int = RECENT_ACTIVITY_LIMIT,
    max_pages: int = RECENT_ACTIVITY_MAX_PAGES,
    max_stalled_pages: int = RECENT_ACTIVITY_MAX_STALLED_PAGES,
):
    username = (username or "").strip()
    selected_year = int(selected_year)

    processor_state = processor.init_state()
    year_start, year_end = get_year_bounds(selected_year)
    session = build_session_fn("application/json", token=token)

    cursor = None
    skip = 0
    pages_fetched = 0

    seen_target_year = False
    crossed_before_year_start = False
    oldest_event_ts_seen = None
    previous_oldest_event_ts_seen = None
    stalled_oldest_count = 0
    seen_cursors = set()
    seen_page_signatures = set()

    logs = []

    try:
        while True:
            if pages_fetched >= max_pages:
                logs.append("Stopped due to safety max pages.")
                break

            rate_limiter_obj.wait()

            params = {
                "limit": limit,
                "activityType": activity_type,
                "feedType": "user",
                "entity": username,
            }
            if cursor:
                params["cursor"] = cursor
            else:
                params["skip"] = skip

            response = session.get(
                "https://huggingface.co/api/recent-activity",
                params=params,
                timeout=20,
            )
            response.raise_for_status()

            payload = response.json()
            pages_fetched += 1

            events, next_cursor = normalize_recent_activity_payload(payload)

            if not events:
                logs.append("No more events.")
                break

            page_signature = build_events_page_signature(events)
            if page_signature in seen_page_signatures:
                logs.append("Stopped because recent-activity returned a repeated page.")
                break
            seen_page_signatures.add(page_signature)

            if next_cursor:
                if next_cursor in seen_cursors:
                    logs.append("Stopped because recent-activity returned a repeated cursor.")
                    break
                seen_cursors.add(next_cursor)

            page_oldest_event_ts = None

            for event in events:
                if not isinstance(event, dict):
                    continue

                event_ts = parse_recent_activity_event_ts(event)

                (
                    oldest_event_ts_seen,
                    page_oldest_event_ts,
                    seen_target_year,
                    crossed_before_year_start,
                ) = update_recent_activity_progress(
                    event_ts,
                    year_start=year_start,
                    year_end=year_end,
                    oldest_event_ts_seen=oldest_event_ts_seen,
                    page_oldest_event_ts=page_oldest_event_ts,
                    seen_target_year=seen_target_year,
                    crossed_before_year_start=crossed_before_year_start,
                )

                processor.process_event(
                    event=event,
                    event_ts=event_ts,
                    year_start=year_start,
                    year_end=year_end,
                    state=processor_state,
                )

            if crossed_before_year_start:
                logs.append("Stopped after crossing before selected year.")
                break

            previous_oldest_event_ts_seen, stalled_oldest_count = update_stalled_pagination_state(
                page_oldest_event_ts=page_oldest_event_ts,
                previous_oldest_event_ts_seen=previous_oldest_event_ts_seen,
                stalled_oldest_count=stalled_oldest_count,
            )

            if stalled_oldest_count >= max_stalled_pages:
                logs.append("Stopped because pagination no longer progressed toward older events.")
                break

            if next_cursor:
                cursor = next_cursor
            else:
                skip += limit

        return processor.build_result(
            username=username,
            selected_year=selected_year,
            state=processor_state,
            logs=logs,
            pages_fetched=pages_fetched,
            oldest_event_ts_seen=oldest_event_ts_seen,
            seen_target_year=seen_target_year,
            crossed_before_year_start=crossed_before_year_start,
        )

    except Exception as e:
        return processor.build_error_result(
            username=username,
            selected_year=selected_year,
            error=e,
            logs=logs,
        )


# ============================================================
# Recent-activity processors
# ============================================================
class CommunityActivityProcessor:
    TITLE_MAP = {
        "pr_opened": "Pull Requests",
        "pr_activity": "PR Activity",
        "thread_opened": "Community Threads",
        "discussion_activity": "Community Activity",
    }
    LOG_LABEL_MAP = {
        "pr_opened": "unique pr_opened event(s)",
        "pr_activity": "unique pr_activity event(s)",
        "thread_opened": "unique thread_opened event(s)",
        "discussion_activity": "unique discussion_activity event(s)",
    }
    OPEN_EVENT_EPSILON_SECONDS = 90

    def __init__(self, username: str):
        self.username = (username or "").strip()

    def init_state(self):
        return {
            "dates": {
                "pr_opened": [],
                "pr_activity": [],
                "thread_opened": [],
                "discussion_activity": [],
            },
            "seen_ids": {
                "pr_opened": set(),
                "pr_activity": set(),
                "thread_opened": set(),
                "discussion_activity": set(),
            },
        }

    def extract_author_name(self, discussion: dict) -> str | None:
        author = discussion.get("author")
        if isinstance(author, str):
            return author
        if isinstance(author, dict):
            for key in ["name", "username", "login"]:
                value = author.get(key)
                if isinstance(value, str):
                    return value
        return None

    def parse_ts(self, raw_value):
        if not raw_value:
            return None
        try:
            return pd.to_datetime(raw_value, utc=True)
        except Exception:
            return None

    def classify_event(self, event: dict, discussion: dict) -> tuple[str | None, str | None]:
        is_pr = bool(discussion.get("isPullRequest", False))
        author_name = self.extract_author_name(discussion)
        repo_id = event.get("repoId", "unknown-repo")
        discussion_num = discussion.get("num", "unknown-num")
        event_id = event.get("eventId", "unknown-event")

        if is_pr:
            if author_name and author_name.lower() == self.username.lower():
                return "pr_opened", f"{repo_id}::pr::{discussion_num}"
            return "pr_activity", f"event::{event_id}"

        if author_name and author_name.lower() == self.username.lower():
            return "thread_opened", f"{repo_id}::thread::{discussion_num}"
        return "discussion_activity", f"event::{event_id}"

    def extract_business_timestamp(self, bucket_key: str, event: dict, discussion: dict):
        event_ts = self.parse_ts(event.get("time"))
        created_ts = self.parse_ts(discussion.get("createdAt"))

        if bucket_key in {"pr_opened", "thread_opened"}:
            return created_ts

        if bucket_key in {"pr_activity", "discussion_activity"}:
            if event_ts is None:
                return None
            if created_ts is not None:
                delta_seconds = abs((event_ts - created_ts).total_seconds())
                if delta_seconds <= self.OPEN_EVENT_EPSILON_SECONDS:
                    return None
            return event_ts

        return None

    def process_event(
        self,
        *,
        event: dict,
        event_ts,
        year_start,
        year_end,
        state: dict,
    ):
        _ = event_ts

        discussion = event.get("discussionData") or {}
        if not isinstance(discussion, dict):
            return

        bucket_key, unique_id = self.classify_event(event, discussion)
        if not bucket_key or not unique_id:
            return

        business_ts = self.extract_business_timestamp(bucket_key, event, discussion)
        if business_ts is None:
            return

        if not (year_start <= business_ts <= year_end):
            return

        if unique_id in state["seen_ids"][bucket_key]:
            return

        state["seen_ids"][bucket_key].add(unique_id)
        state["dates"][bucket_key].append(business_ts.tz_localize(None).date())

    def build_bucket(self, key: str, dates: list, selected_year: int):
        return {
            "title": self.TITLE_MAP[key],
            "fetched": True,
            "dates": dates,
            "count": len(dates),
            "logs": f"Found {len(dates)} {self.LOG_LABEL_MAP[key]} in {selected_year}.",
        }

    def build_result(
        self,
        *,
        username: str,
        selected_year: int,
        state: dict,
        logs: list[str],
        pages_fetched: int,
        oldest_event_ts_seen,
        seen_target_year: bool,
        crossed_before_year_start: bool,
    ):
        logs = list(logs)
        logs.append(f"Fetched {pages_fetched} page(s) from recent-activity.")
        if oldest_event_ts_seen is not None:
            logs.append(f"Oldest event reached: {oldest_event_ts_seen.date()}.")
        logs.append(f"Seen target year: {seen_target_year}.")
        logs.append(f"Crossed before year start: {crossed_before_year_start}.")
        logs.append(
            " | ".join(
                f"{self.TITLE_MAP[key]}: {len(state['dates'][key])}"
                for key in ["pr_opened", "pr_activity", "thread_opened", "discussion_activity"]
            )
        )

        combined_logs = "\n\n".join(
            [
                "[Pull Requests]\n" + self.build_bucket("pr_opened", state["dates"]["pr_opened"], selected_year)["logs"],
                "[PR Activity]\n" + self.build_bucket("pr_activity", state["dates"]["pr_activity"], selected_year)["logs"],
                "[Community Threads]\n" + self.build_bucket("thread_opened", state["dates"]["thread_opened"], selected_year)["logs"],
                "[Community Activity]\n" + self.build_bucket("discussion_activity", state["dates"]["discussion_activity"], selected_year)["logs"],
                "[Fetch]\n" + "\n".join(logs),
            ]
        )

        return {
            "username": username,
            "selected_year": selected_year,
            "fetched": True,
            "pr_opened": self.build_bucket("pr_opened", state["dates"]["pr_opened"], selected_year),
            "pr_activity": self.build_bucket("pr_activity", state["dates"]["pr_activity"], selected_year),
            "thread_opened": self.build_bucket("thread_opened", state["dates"]["thread_opened"], selected_year),
            "discussion_activity": self.build_bucket("discussion_activity", state["dates"]["discussion_activity"], selected_year),
            "logs": combined_logs,
        }

    def build_error_result(
        self,
        *,
        username: str,
        selected_year: int,
        error,
        logs: list[str],
    ):
        _ = logs
        return {
            "username": username,
            "selected_year": selected_year,
            "fetched": True,
            "pr_opened": build_failed_bucket("Pull Requests"),
            "pr_activity": build_failed_bucket("PR Activity"),
            "thread_opened": build_failed_bucket("Community Threads"),
            "discussion_activity": build_failed_bucket("Community Activity"),
            "logs": f"Community fetch failed: {str(error)}",
        }


class BucketedActivityProcessor:
    def __init__(
        self,
        *,
        bucket_titles: dict[str, str],
        bucket_log_labels: dict[str, str],
        classifier,
        error_label: str,
    ):
        self.bucket_titles = bucket_titles
        self.bucket_log_labels = bucket_log_labels
        self.classifier = classifier
        self.error_label = error_label

    def init_state(self):
        return {
            "bucket_dates": {key: [] for key in self.bucket_titles},
            "bucket_seen_ids": {key: set() for key in self.bucket_titles},
        }

    def process_event(
        self,
        *,
        event: dict,
        event_ts,
        year_start,
        year_end,
        state: dict,
    ):
        if event_ts is None:
            return

        if not (year_start <= event_ts <= year_end):
            return

        bucket_key, unique_id = self.classifier(event)

        if not bucket_key or not unique_id:
            return

        if bucket_key not in state["bucket_dates"]:
            return

        if unique_id in state["bucket_seen_ids"][bucket_key]:
            return

        state["bucket_seen_ids"][bucket_key].add(unique_id)
        state["bucket_dates"][bucket_key].append(event_ts.tz_localize(None).date())

    def build_result(
        self,
        *,
        username: str,
        selected_year: int,
        state: dict,
        logs: list[str],
        pages_fetched: int,
        oldest_event_ts_seen,
        seen_target_year: bool,
        crossed_before_year_start: bool,
    ):
        logs = list(logs)
        logs.append(f"Fetched {pages_fetched} page(s) from recent-activity.")
        if oldest_event_ts_seen is not None:
            logs.append(f"Oldest event reached: {oldest_event_ts_seen.date()}.")
        logs.append(f"Seen target year: {seen_target_year}.")
        logs.append(f"Crossed before year start: {crossed_before_year_start}.")
        logs.append(
            " | ".join(
                f"{self.bucket_titles[key]}: {len(state['bucket_dates'][key])}"
                for key in self.bucket_titles
            )
        )

        result = {
            "username": username,
            "selected_year": selected_year,
            "fetched": True,
            "logs": "\n".join(logs),
        }

        for key, title in self.bucket_titles.items():
            dates = state["bucket_dates"][key]
            result[key] = build_fetched_bucket(
                title=title,
                dates=dates,
                selected_year=selected_year,
                label=self.bucket_log_labels[key],
            )

        return result

    def build_error_result(
        self,
        *,
        username: str,
        selected_year: int,
        error,
        logs: list[str],
    ):
        _ = logs
        result = {
            "username": username,
            "selected_year": selected_year,
            "fetched": True,
            "logs": f"{self.error_label} fetch failed: {str(error)}",
        }

        for key, title in self.bucket_titles.items():
            result[key] = build_failed_bucket(title)

        return result


# ============================================================
# Activity classifiers + config
# ============================================================
def classify_upvote_event(event: dict):
    target_type = event.get("targetType")
    target = event.get("target") or {}
    if not isinstance(target, dict):
        target = {}

    unique_id = event.get("targetUrl") or target.get("id") or target.get("_id")

    mapping = {
        "paper": "papers",
        "article": "blog",
        "changelog": "changelog",
    }

    bucket_key = mapping.get(target_type)
    if not bucket_key or not unique_id:
        return None, None

    return bucket_key, unique_id


def classify_like_event(event: dict):
    repo_data = event.get("repoData") or {}
    if not isinstance(repo_data, dict):
        repo_data = {}

    repo_type = event.get("repoType") or repo_data.get("repoType")
    unique_id = event.get("repoId") or repo_data.get("id")

    mapping = {
        "model": "models",
        "dataset": "datasets",
        "space": "spaces",
    }

    bucket_key = mapping.get(repo_type)
    if not bucket_key or not unique_id:
        return None, None

    return bucket_key, unique_id


def classify_paper_event(event: dict):
    event_type = event.get("type")
    paper = event.get("paper") or {}
    if not isinstance(paper, dict):
        paper = {}

    unique_id = paper.get("id")

    mapping = {
        "paper-daily": "daily",
        "paper": "authored",
    }

    bucket_key = mapping.get(event_type)
    if not bucket_key or not unique_id:
        return None, None

    return bucket_key, unique_id


SINGLE_SECTION_CONFIG = {
    "upvotes": {
        "section_label": "upvotes activity",
        "empty_chart_title": "Upvotes",
        "empty_logs_text": "Upvotes activity not fetched yet.",
        "needs_fetch_text": "Upvotes activity needs to be fetched for the current username/year.",
        "default_mode": "all",
        "palette_name": "purple",
        "bucket_titles": {
            "papers": "Paper Upvotes",
            "blog": "Blog Upvotes",
            "changelog": "Changelog Upvotes",
        },
        "bucket_log_labels": {
            "papers": "paper upvote(s)",
            "blog": "blog upvote(s)",
            "changelog": "changelog upvote(s)",
        },
        "activity_type": "upvote",
        "cache_scope": "upvotes",
        "classifier": classify_upvote_event,
        "mode_labels": {
            "papers": "paper upvote(s)",
            "blog": "blog upvote(s)",
            "changelog": "changelog upvote(s)",
        },
        "button_text": "Fetch upvotes activity",
        "empty_context_text": "Not logged in · Enter a username to fetch upvotes activity",
        "radio_choices": [
            ("All", "all"),
            ("Papers", "papers"),
            ("Blog", "blog"),
            ("Changelog", "changelog"),
        ],
        "radio_label": "Upvotes view",
        "radio_elem_id": "upvotes-view-toggle",
        "logs_label": "Upvotes Fetch Logs",
        "logs_lines": 10,
    },
    "likes": {
        "section_label": "likes activity",
        "empty_chart_title": "Likes",
        "empty_logs_text": "Likes activity not fetched yet.",
        "needs_fetch_text": "Likes activity needs to be fetched for the current username/year.",
        "default_mode": "all",
        "palette_name": "blue",
        "bucket_titles": {
            "models": "Model Likes",
            "datasets": "Dataset Likes",
            "spaces": "Space Likes",
        },
        "bucket_log_labels": {
            "models": "model like(s)",
            "datasets": "dataset like(s)",
            "spaces": "space like(s)",
        },
        "activity_type": "like",
        "cache_scope": "likes",
        "classifier": classify_like_event,
        "mode_labels": {
            "models": "model like(s)",
            "datasets": "dataset like(s)",
            "spaces": "space like(s)",
        },
        "button_text": "Fetch likes activity",
        "empty_context_text": "Not logged in · Enter a username to fetch likes activity",
        "radio_choices": [
            ("All", "all"),
            ("Models", "models"),
            ("Datasets", "datasets"),
            ("Spaces", "spaces"),
        ],
        "radio_label": "Likes view",
        "radio_elem_id": "likes-view-toggle",
        "logs_label": "Likes Fetch Logs",
        "logs_lines": 10,
    },
    "papers": {
        "section_label": "papers activity",
        "empty_chart_title": "Papers",
        "empty_logs_text": "Papers activity not fetched yet.",
        "needs_fetch_text": "Papers activity needs to be fetched for the current username/year.",
        "default_mode": "all",
        "palette_name": "teal",
        "bucket_titles": {
            "daily": "Daily Papers",
            "authored": "Authored Papers",
        },
        "bucket_log_labels": {
            "daily": "daily paper submission(s)",
            "authored": "authored paper(s)",
        },
        "activity_type": "update-paper",
        "cache_scope": "papers",
        "classifier": classify_paper_event,
        "mode_labels": {
            "daily": "Daily Papers submission(s)",
            "authored": "authored paper(s)",
        },
        "button_text": "Fetch papers activity",
        "empty_context_text": "Not logged in · Enter a username to fetch papers activity",
        "radio_choices": [
            ("All", "all"),
            ("Daily Papers", "daily"),
            ("Authored", "authored"),
        ],
        "radio_label": "Papers view",
        "radio_elem_id": "papers-view-toggle",
        "logs_label": "Papers Fetch Logs",
        "logs_lines": 10,
    },
}


def empty_single_section_state(section_key: str, selected_year: int):
    cfg = SINGLE_SECTION_CONFIG[section_key]
    return empty_bucketed_activity_state(
        selected_year=selected_year,
        logs_text=cfg["empty_logs_text"],
        bucket_titles=cfg["bucket_titles"],
    )


# ============================================================
# Public activity fetch functions
# ============================================================
def fetch_all_community_activity(username: str, selected_year: int):
    username = (username or "").strip()
    selected_year = int(selected_year)

    cache_key = (username.lower(), selected_year, "community")
    cached = get_cache(cache_key)
    if cached:
        return cached

    if not username:
        state = empty_community_state(selected_year)
        state["fetched"] = True
        state["logs"] = "No username provided."
        set_cache(cache_key, state)
        return state

    processor = CommunityActivityProcessor(username=username)

    result = collect_recent_activity(
        username=username,
        selected_year=selected_year,
        activity_type="discussion",
        processor=processor,
        build_session_fn=build_session,
        rate_limiter_obj=recent_activity_rate_limiter,
    )

    set_cache(cache_key, result)
    return result


def fetch_single_section_activity(section_key: str, username: str, selected_year: int):
    username = (username or "").strip()
    selected_year = int(selected_year)
    cfg = SINGLE_SECTION_CONFIG[section_key]

    cache_key = (username.lower(), selected_year, cfg["cache_scope"])
    cached = get_cache(cache_key)
    if cached:
        return cached

    if not username:
        state = empty_single_section_state(section_key, selected_year)
        state["fetched"] = True
        state["logs"] = "No username provided."
        set_cache(cache_key, state)
        return state

    processor = BucketedActivityProcessor(
        bucket_titles=cfg["bucket_titles"],
        bucket_log_labels=cfg["bucket_log_labels"],
        classifier=cfg["classifier"],
        error_label=cfg["cache_scope"].capitalize(),
    )

    result = collect_recent_activity(
        username=username,
        selected_year=selected_year,
        activity_type=cfg["activity_type"],
        processor=processor,
        build_session_fn=build_session,
        rate_limiter_obj=recent_activity_rate_limiter,
    )

    set_cache(cache_key, result)
    return result


# ============================================================
# Contribution grid helpers
# ============================================================
PALETTES = {
    "green": ["#0e4429", "#006d32", "#26a641", "#39d353"],
    "blue": ["#0a3069", "#0969da", "#54aeff", "#79c0ff"],
    "pink": ["#6e1f4d", "#bf3989", "#db61a2", "#f778ba"],
    "orange": ["#5f370e", "#a14d00", "#d97706", "#f59e0b"],
    "purple": ["#4c1d95", "#6d28d9", "#8b5cf6", "#c4b5fd"],
    "teal": ["#0f766e", "#0d9488", "#14b8a6", "#5eead4"],
}

TOOLTIP_SAFE_COLUMNS = 2


def level_from_count(count: int) -> int:
    if count <= 0:
        return 0
    if count == 1:
        return 1
    if count <= 3:
        return 2
    if count <= 7:
        return 3
    return 4


def level_color(palette_name: str, level: int) -> str:
    if level <= 0:
        return "var(--gh-empty-cell)"
    palette = PALETTES[palette_name]
    return palette[min(level - 1, len(palette) - 1)]


def build_daily_count_map(df: pd.DataFrame):
    if df.empty:
        return {}

    counts = (
        df.copy()
        .assign(date=pd.to_datetime(df["date"]).dt.date, count=1)
        .groupby("date", as_index=False)["count"]
        .sum()
    )
    return {row["date"]: int(row["count"]) for _, row in counts.iterrows()}


def get_calendar_bounds(year: int):
    start = pd.Timestamp(f"{year}-01-01")
    end = pd.Timestamp(f"{year}-12-31")

    grid_start = start - pd.Timedelta(days=start.dayofweek)
    grid_end = end + pd.Timedelta(days=(6 - end.dayofweek))

    all_days = pd.date_range(grid_start, grid_end, freq="D")
    num_weeks = len(all_days) // 7
    return start, end, grid_start, grid_end, all_days, num_weeks


def month_positions_for_year(year: int, grid_start: pd.Timestamp):
    month_starts = pd.date_range(f"{year}-01-01", f"{year}-12-31", freq="MS")
    return [(d.strftime("%b"), int((d - grid_start).days // 7)) for d in month_starts]


# ============================================================
# Name helpers
# ============================================================
def resolve_display_name(
    username: str,
    profile: gr.OAuthProfile | None,
    identity: dict | None = None,
):
    username = (username or "").strip()
    if not username:
        return ""

    profile_username = get_viewer_username(profile)
    profile_name = getattr(profile, "name", None) if profile is not None else None

    if profile_username and profile_username.lower() == username.lower():
        if isinstance(profile_name, str) and profile_name.strip():
            return f"{profile_name.strip()} (@{profile_username})"
        return f"@{profile_username}"

    if identity:
        display_name = identity.get("display_name")
        if isinstance(display_name, str) and display_name.strip():
            return display_name

        fullname = identity.get("fullname")
        identity_username = identity.get("username") or username
        if isinstance(fullname, str) and fullname.strip():
            return f"{fullname.strip()} (@{identity_username})"

        if isinstance(identity_username, str) and identity_username.strip():
            return f"@{identity_username.strip()}"

    return f"@{username}"


# ============================================================
# HTML render helpers
# ============================================================
def render_status_badge(text: str):
    return f'<div class="gh-status">{text}</div>'


def render_metric_cards(
    total_activity: int,
    created_by_type: dict,
    repo_commit_counts_by_type: dict,
    selected_year: int,
):
    return f"""
    <div class="stats-grid">
      <div class="gh-card">
        <div class="gh-card-label">Total activity</div>
        <div class="gh-card-value">{total_activity}</div>
        <div class="gh-card-sub">Creations + repo contributions in {selected_year}</div>
      </div>

      <div class="gh-card">
        <div class="gh-card-label">{REPO_KIND_EMOJIS["model"]} Models created</div>
        <div class="gh-card-value">{created_by_type["model"]}</div>
        <div class="gh-card-sub">{repo_commit_counts_by_type["model"]} contributions on model repos</div>
      </div>

      <div class="gh-card">
        <div class="gh-card-label">{REPO_KIND_EMOJIS["dataset"]} Datasets created</div>
        <div class="gh-card-value">{created_by_type["dataset"]}</div>
        <div class="gh-card-sub">{repo_commit_counts_by_type["dataset"]} contributions on dataset repos</div>
      </div>

      <div class="gh-card">
        <div class="gh-card-label">{REPO_KIND_EMOJIS["space"]} Spaces created</div>
        <div class="gh-card-value">{created_by_type["space"]}</div>
        <div class="gh-card-sub">{repo_commit_counts_by_type["space"]} contributions on space repos</div>
      </div>
    </div>
    """


# ============================================================
# Generic banner helpers
# ============================================================
def viewer_banner_prefix(profile: gr.OAuthProfile | None) -> list[str]:
    viewer = get_viewer_username(profile)
    if viewer:
        return [f"Logged in as <b>{html.escape(viewer)}</b>"]
    return ["Not logged in"]


def render_generic_invalid_banner(username: str, error_text: str | None = None):
    username = (username or "").strip()
    message = error_text or f"Username or org '{username}' was not found."
    return render_status_badge(html.escape(message))


def render_section_idle_banner(
    section_label: str,
    username,
    selected_year,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    selected_year = int(selected_year)

    parts = viewer_banner_prefix(profile)

    if not username:
        parts.append(f"Enter a username to fetch {section_label.lower()}")
        return render_status_badge(" · ".join(parts))

    if is_self_view(username, profile):
        parts.append(f"Fetch your {section_label.lower()} or enter another username")
    else:
        parts.append(f"Ready to fetch {section_label.lower()} for <b>{html.escape(username)}</b>")

    parts.append(str(selected_year))
    return render_status_badge(" · ".join(parts))


def render_section_fetching_banner(
    section_label: str,
    username,
    selected_year,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    selected_year = int(selected_year)

    if not username:
        return render_section_idle_banner(section_label, "", selected_year, profile)

    parts = viewer_banner_prefix(profile)

    if is_self_view(username, profile):
        parts.append(f"Fetching <b>your {section_label.lower()}</b>")
    else:
        parts.append(f"Fetching {section_label.lower()} for <b>{html.escape(username)}</b>")

    parts.append(str(selected_year))
    return render_status_badge(" · ".join(parts))


def render_section_loaded_banner(
    section_label: str,
    state: dict | None,
    profile: gr.OAuthProfile | None,
):
    year = state.get("selected_year", datetime.now().year) if state else datetime.now().year
    if not state or not state.get("username"):
        return render_section_idle_banner(section_label, "", year, profile)

    username = state["username"]
    selected_year = int(state["selected_year"])

    parts = viewer_banner_prefix(profile)

    if is_self_view(username, profile):
        parts.append(f"Viewing <b>your {section_label.lower()}</b>")
    else:
        parts.append(f"Viewing {section_label.lower()} for <b>{html.escape(username)}</b>")

    parts.append(str(selected_year))
    return render_status_badge(" · ".join(parts))


# ============================================================
# Repo-specific banners
# ============================================================
def render_idle_context_banner(
    username: str,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    viewer = get_viewer_username(profile)

    if viewer:
        if not username or username.lower() == viewer.lower():
            return render_status_badge(
                f"Logged in as <b>{html.escape(viewer)}</b> · Fetch your activity or enter another username"
            )
        return render_status_badge(
            f"Logged in as <b>{html.escape(viewer)}</b> · Ready to fetch <b>{html.escape(username)}</b> · Public repos only"
        )

    if username:
        return render_status_badge(
            f"Not logged in · Ready to fetch <b>{html.escape(username)}</b> · Public repos only"
        )

    return render_status_badge("Not logged in · Enter a username to get started")


def render_context_banner(app_state: dict | None, profile: gr.OAuthProfile | None):
    if not app_state or not app_state.get("username"):
        return render_idle_context_banner("", profile)

    username = app_state["username"]
    selected_year = int(app_state["selected_year"])
    is_own = bool(app_state.get("is_own_profile", False))
    can_toggle = bool(app_state.get("can_toggle_visibility", False))
    viewer = get_viewer_username(profile)

    parts = []

    if viewer:
        parts.append(f"Logged in as <b>{html.escape(viewer)}</b>")
    else:
        parts.append("Not logged in")

    if is_self_view(username, profile):
        parts.append("Viewing <b>your activity</b>")
    else:
        parts.append(f"Viewing <b>{html.escape(username)}</b>")

    parts.append(str(selected_year))

    if is_own and can_toggle:
        parts.append("Private repos available")
    else:
        parts.append("Public repos only")

    return render_status_badge(" · ".join(parts))


def render_fetching_context_banner(
    username,
    selected_year,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    selected_year = int(selected_year)
    viewer = get_viewer_username(profile)

    if not username:
        return render_idle_context_banner("", profile)

    parts = []

    if viewer:
        parts.append(f"Logged in as <b>{html.escape(viewer)}</b>")
    else:
        parts.append("Not logged in")

    if is_self_view(username, profile):
        parts.append("Fetching <b>your activity</b>")
        parts.append(str(selected_year))
        parts.append("Checking public and private repos")
    else:
        parts.append(f"Fetching <b>{html.escape(username)}</b>")
        parts.append(str(selected_year))
        parts.append("Checking public repos")

    return render_status_badge(" · ".join(parts))


def render_empty_chart(title: str):
    safe_title = html.escape(title)
    return f"""
    <div class="gh-chart-card">
      <div class="gh-chart-header">
        <div class="gh-chart-title">{safe_title}</div>
      </div>
      <div class="gh-empty">No activity found.</div>
    </div>
    """


def render_contrib_chart(
    df: pd.DataFrame,
    year: int,
    title: str,
    palette_name: str = "green",
    subtitle: str | None = None,
):
    safe_title = html.escape(title)
    safe_subtitle = html.escape(subtitle) if subtitle else ""

    counts_map = build_daily_count_map(df)
    year_start, year_end, grid_start, _, all_days, num_weeks = get_calendar_bounds(year)
    months = month_positions_for_year(year, grid_start)

    padded_weeks = num_weeks + (2 * TOOLTIP_SAFE_COLUMNS)

    cells_html = []
    total = 0

    for day in all_days:
        day_date = day.date()
        in_year = year_start.date() <= day_date <= year_end.date()
        count = counts_map.get(day_date, 0) if in_year else 0
        total += count

        week = int((day - grid_start).days // 7)
        display_week = week + TOOLTIP_SAFE_COLUMNS
        dow = int(day.dayofweek)
        level = level_from_count(count)
        color = level_color(palette_name, level) if in_year else "transparent"
        label = f"{count} contribution{'s' if count != 1 else ''} on {day.strftime('%b %d, %Y')}"

        if in_year:
            classes = ["gh-cell"]
            if dow == 0:
                classes.append("gh-tooltip-bottom")
            if week <= 1:
                classes.append("gh-tooltip-right")
            elif week >= num_weeks - 2:
                classes.append("gh-tooltip-left")

            class_attr = " ".join(classes)
            safe_label = html.escape(label)

            cells_html.append(
                f"""
                <button
                  type="button"
                  class="{class_attr}"
                  style="grid-column:{display_week + 1}; grid-row:{dow + 1}; background:{color};"
                  aria-label="{safe_label}"
                  title="{safe_label}"
                >
                  <span class="gh-tooltip">{safe_label}</span>
                </button>
                """
            )
        else:
            cells_html.append(
                f"""
                <div
                  class="gh-cell gh-cell-outside"
                  style="grid-column:{display_week + 1}; grid-row:{dow + 1}; background:{color};"
                  aria-hidden="true"
                ></div>
                """
            )

    month_labels = []
    for label, pos in months:
        display_pos = pos + TOOLTIP_SAFE_COLUMNS
        month_labels.append(
            f'<div class="gh-month-label" style="grid-column:{display_pos + 1};">{html.escape(label)}</div>'
        )

    legend_colors = ["var(--gh-empty-cell)"] + PALETTES[palette_name]
    legend_html = "".join(
        f'<span class="gh-legend-cell" style="background:{c};"></span>' for c in legend_colors
    )

    subtitle_html = f'<div class="gh-chart-subtitle">{safe_subtitle}</div>' if subtitle else ""

    return f"""
    <div class="gh-chart-card">
      <div class="gh-chart-header">
        <div>
          <div class="gh-chart-title">{safe_title}</div>
          {subtitle_html}
        </div>
        <div class="gh-chart-total">{total} contributions</div>
      </div>

      <div class="gh-chart-wrap">
        <div class="gh-chart-inner">
          <div class="gh-months" style="grid-template-columns: repeat({int(padded_weeks - 2)}, minmax(0, 1fr));">
            {''.join(month_labels)}
          </div>

          <div class="gh-grid-area">
            <div class="gh-weekday weekday-mon">Mon</div>
            <div class="gh-weekday weekday-wed">Wed</div>
            <div class="gh-weekday weekday-fri">Fri</div>

            <div class="gh-grid" style="grid-template-columns: repeat({int(padded_weeks - 2)}, minmax(0, 1fr));">
              {''.join(cells_html)}
            </div>
          </div>
        </div>
      </div>

      <div class="gh-legend">
        <span class="gh-legend-text">Less</span>
        {legend_html}
        <span class="gh-legend-text">More</span>
      </div>
    </div>
    """


def merge_dates(opened_dates: list, activity_dates: list, mode: str):
    if mode == "opened":
        return list(opened_dates)
    if mode == "activity":
        return list(activity_dates)
    return list(opened_dates) + list(activity_dates)


def render_dual_mode_chart(
    state: dict | None,
    *,
    opened_key: str,
    activity_key: str,
    mode: str,
    username: str,
    year: int,
    title: str,
    palette_name: str,
    opened_label: str,
    activity_label: str,
    total_label: str,
):
    if not state or not state.get("fetched"):
        return render_empty_chart(title)

    opened = state[opened_key]["dates"]
    activity = state[activity_key]["dates"]
    merged = merge_dates(opened, activity, mode)
    df = pd.DataFrame(merged, columns=["date"])

    subtitle = {
        "opened": f"{len(opened)} {opened_label} by {username} in {year}",
        "activity": f"{len(activity)} {activity_label} for {username} in {year}",
        "both": f"{len(opened) + len(activity)} total {total_label} for {username} in {year}",
    }[mode]

    return render_contrib_chart(
        df,
        year,
        title,
        palette_name=palette_name,
        subtitle=subtitle,
    )


def render_pr_combined_chart(community_state: dict | None, mode: str, username: str, year: int):
    return render_dual_mode_chart(
        community_state,
        opened_key="pr_opened",
        activity_key="pr_activity",
        mode=mode,
        username=username,
        year=year,
        title="Pull Requests",
        palette_name="purple",
        opened_label="PRs opened",
        activity_label="PR follow-up events",
        total_label="PR events",
    )


def render_discussion_combined_chart(community_state: dict | None, mode: str, username: str, year: int):
    return render_dual_mode_chart(
        community_state,
        opened_key="thread_opened",
        activity_key="discussion_activity",
        mode=mode,
        username=username,
        year=year,
        title="Community Discussions",
        palette_name="teal",
        opened_label="threads opened",
        activity_label="discussion follow-up events",
        total_label="discussion events",
    )


def render_single_section_chart(section_key: str, state: dict | None, mode: str, username: str, year: int):
    cfg = SINGLE_SECTION_CONFIG[section_key]

    if not state or not state.get("fetched"):
        return render_empty_chart(cfg["empty_chart_title"])

    bucket_keys = list(cfg["bucket_titles"].keys())
    bucket_dates = {key: state[key]["dates"] for key in bucket_keys}

    if mode in bucket_dates:
        merged = list(bucket_dates[mode])
        subtitle = f"{len(merged)} {cfg['mode_labels'][mode]} by {username} in {year}"
    else:
        merged = [d for key in bucket_keys for d in bucket_dates[key]]
        subtitle = f"{len(merged)} total {cfg['empty_chart_title'].lower()} event(s) by {username} in {year}"

    df = pd.DataFrame(merged, columns=["date"])

    return render_contrib_chart(
        df,
        year,
        cfg["empty_chart_title"],
        palette_name=cfg["palette_name"],
        subtitle=subtitle,
    )


# ============================================================
# App state + render layer
# ============================================================
def build_empty_repo_kind_data():
    return {
        kind: {"total_items": 0, "repos": [], "errors": []}
        for kind in REPO_KINDS
    }


def build_empty_app_state(
    username: str,
    selected_year: int,
    viewer_username: str | None = None,
    identity: dict | None = None,
):
    resolved_identity = identity or (
        validate_username(username, None) if username else empty_identity("", "No username provided.")
    )

    return {
        "username": username,
        "selected_year": int(selected_year),
        "viewer_username": viewer_username,
        "is_own_profile": False,
        "can_toggle_visibility": False,
        "default_visibility": "public",
        "kind_repo_data": build_empty_repo_kind_data(),
        "identity": resolved_identity,
        "is_valid_username": bool(resolved_identity.get("exists")),
        "validation_error": resolved_identity.get("error"),
    }


def build_app_state(
    username: str,
    selected_year: int,
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None,
):
    username = (username or "").strip()
    selected_year = int(selected_year)

    viewer_username = get_viewer_username(profile)
    token = oauth_token.token if oauth_token is not None else None

    if not username:
        return build_empty_app_state(username, selected_year, viewer_username)

    identity = validate_username(username, profile)
    if not identity.get("exists"):
        return {
            **build_empty_app_state(
                username,
                selected_year,
                viewer_username,
                identity=identity,
            ),
            "identity": identity,
            "is_valid_username": False,
            "validation_error": identity.get("error") or f"Username or org '{username}' was not found.",
        }

    is_own_profile = bool(
        viewer_username
        and username
        and viewer_username.lower() == username.lower()
        and token
    )
    can_toggle_visibility = is_own_profile
    token_for_fetch = token if is_own_profile else None

    scope = "repo_private" if is_own_profile else "repo_public"
    cache_key = (username.lower(), selected_year, scope)
    cached = get_cache(cache_key)
    if cached:
        cached_with_identity = dict(cached)
        cached_with_identity["identity"] = identity
        cached_with_identity["is_valid_username"] = True
        cached_with_identity["validation_error"] = None
        return cached_with_identity

    kind_repo_data = {}
    for kind in REPO_KINDS:
        kind_repo_data[kind] = collect_kind_repo_entries(
            username=username,
            kind=kind,
            selected_year=selected_year,
            token=token_for_fetch,
        )

    result = {
        "username": username,
        "selected_year": selected_year,
        "viewer_username": viewer_username,
        "is_own_profile": is_own_profile,
        "can_toggle_visibility": can_toggle_visibility,
        "default_visibility": "all" if can_toggle_visibility else "public",
        "kind_repo_data": kind_repo_data,
        "identity": identity,
        "is_valid_username": True,
        "validation_error": None,
    }

    set_cache(cache_key, result)
    return result


def render_invalid_app_state(app_state: dict | None):
    username = (app_state or {}).get("username", "")
    selected_year = int((app_state or {}).get("selected_year", datetime.now().year))
    error_text = (app_state or {}).get("validation_error") or f"Username or org '{username}' was not found."

    empty_counts = {kind: 0 for kind in REPO_KINDS}
    empty_metrics = render_metric_cards(
        0,
        empty_counts,
        empty_counts,
        selected_year,
    )

    return (
        "## Ready",
        render_generic_invalid_banner(username, error_text),
        empty_metrics,
        render_empty_chart("All activity"),
        render_empty_chart("Models"),
        render_empty_chart("Datasets"),
        render_empty_chart("Spaces"),
        error_text,
    )


def render_app_state(
    app_state: dict | None,
    visibility_mode: str | None,
    profile: gr.OAuthProfile | None,
):
    if not app_state or not app_state.get("username"):
        selected_year = datetime.now().year
        empty_counts = {kind: 0 for kind in REPO_KINDS}
        empty_metrics = render_metric_cards(
            0,
            empty_counts,
            empty_counts,
            selected_year,
        )
        context_html = render_idle_context_banner("", profile)
        return (
            "## Ready",
            context_html,
            empty_metrics,
            render_empty_chart("All activity"),
            render_empty_chart("Models"),
            render_empty_chart("Datasets"),
            render_empty_chart("Spaces"),
            "No username provided.",
        )

    if not app_state.get("is_valid_username", True):
        return render_invalid_app_state(app_state)

    username = app_state["username"]
    selected_year = int(app_state["selected_year"])
    can_toggle_visibility = bool(app_state["can_toggle_visibility"])

    effective_visibility = "all" if (visibility_mode == "all" and can_toggle_visibility) else "public"
    include_private = effective_visibility == "all"

    kind_views = {}
    warnings = []

    for kind in REPO_KINDS:
        kind_data = app_state["kind_repo_data"][kind]
        kind_views[kind] = aggregate_repo_entries(
            kind_data["repos"],
            include_private=include_private,
        )
        warnings.extend(kind_data["errors"])

    total_activity = sum(v["activity_count"] for v in kind_views.values())

    all_activity_dates = []
    for kind in REPO_KINDS:
        all_activity_dates.extend(kind_views[kind]["activity_dates"])

    all_df = pd.DataFrame(all_activity_dates, columns=["date"])
    kind_dfs = {
        kind: pd.DataFrame(kind_views[kind]["activity_dates"], columns=["date"])
        for kind in REPO_KINDS
    }

    context_html = render_context_banner(app_state, profile)
    display_name = resolve_display_name(username, profile, app_state.get("identity"))

    metrics_html = render_metric_cards(
        total_activity=total_activity,
        created_by_type={kind: kind_views[kind]["created_count"] for kind in REPO_KINDS},
        repo_commit_counts_by_type={kind: kind_views[kind]["repo_commit_count"] for kind in REPO_KINDS},
        selected_year=selected_year,
    )

    all_chart_html = render_contrib_chart(
        all_df,
        selected_year,
        f"{display_name}'s activity",
        palette_name="green",
        subtitle=f"Repo creations + repo contributions in {selected_year}",
    )

    kind_chart_html = {}
    for kind in REPO_KINDS:
        kind_chart_html[kind] = render_contrib_chart(
            kind_dfs[kind],
            selected_year,
            REPO_KIND_LABELS[kind],
            palette_name=REPO_KIND_PALETTES[kind],
            subtitle=(
                f'{kind_views[kind]["created_count"]} created • '
                f'{kind_views[kind]["repo_commit_count"]} repo contributions'
            ),
        )

    logs_text = "\n".join(warnings) if warnings else "Done."

    return (
        f"## {display_name}'s activity in {selected_year}",
        context_html,
        metrics_html,
        all_chart_html,
        kind_chart_html["model"],
        kind_chart_html["dataset"],
        kind_chart_html["space"],
        logs_text,
    )


# ============================================================
# Standardized section responses
# ============================================================
def build_invalid_single_section_response(
    section_key: str,
    username: str,
    selected_year: int,
    identity: dict,
):
    cfg = SINGLE_SECTION_CONFIG[section_key]
    state = build_invalid_section_state(
        username,
        selected_year,
        lambda y: empty_single_section_state(section_key, y),
        identity,
    )
    return (
        state,
        render_generic_invalid_banner(username, identity.get("error")),
        gr.update(value=cfg["default_mode"], visible="hidden"),
        render_empty_chart(cfg["empty_chart_title"]),
        state["logs"],
    )


def build_idle_single_section_response(
    section_key: str,
    username: str,
    selected_year: int,
    profile: gr.OAuthProfile | None,
    logs_text: str | None = None,
):
    cfg = SINGLE_SECTION_CONFIG[section_key]
    state = empty_single_section_state(section_key, selected_year)
    return (
        state,
        render_section_idle_banner(cfg["section_label"], username, selected_year, profile),
        gr.update(value=cfg["default_mode"], visible="hidden"),
        render_empty_chart(cfg["empty_chart_title"]),
        logs_text or cfg["empty_logs_text"],
    )


def build_invalid_community_response(
    username: str,
    selected_year: int,
    identity: dict,
):
    state = build_invalid_section_state(username, selected_year, empty_community_state, identity)
    return (
        state,
        render_generic_invalid_banner(username, identity.get("error")),
        gr.update(value="both", visible="hidden"),
        render_empty_chart("Pull Requests"),
        gr.update(value="both", visible="hidden"),
        render_empty_chart("Community Discussions"),
        state["logs"],
    )


def build_idle_community_response(
    username: str,
    selected_year: int,
    profile: gr.OAuthProfile | None,
    logs_text: str,
):
    state = empty_community_state(selected_year)
    return (
        state,
        render_section_idle_banner("community activity", username, selected_year, profile),
        gr.update(value="both", visible="hidden"),
        render_empty_chart("Pull Requests"),
        gr.update(value="both", visible="hidden"),
        render_empty_chart("Community Discussions"),
        logs_text,
    )


# ============================================================
# Stable return-based fetch / reset logic
# ============================================================
def prepare_repo_fetch_ui(
    username,
    selected_year,
    current_visibility_mode,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    _ = int(selected_year)

    if is_self_view(username, profile):
        value = current_visibility_mode if current_visibility_mode in {"all", "public"} else "all"
        visibility_update = gr.update(
            choices=[("All repos", "all"), ("Public only", "public")],
            value=value,
            visible=True,
            interactive=True,
        )
    else:
        visibility_update = gr.update(
            choices=[("All repos", "all"), ("Public only", "public")],
            value="public",
            visible="hidden",
            interactive=False,
        )

    return render_fetching_context_banner(username, selected_year, profile), visibility_update


def fetch_and_render_repo_only(
    username,
    selected_year,
    current_visibility_mode,
    profile: gr.OAuthProfile | None,
    oauth_token: gr.OAuthToken | None,
):
    username = (username or "").strip()
    selected_year = int(selected_year)

    app_state = build_app_state(username, selected_year, profile, oauth_token)

    if not app_state.get("is_valid_username", True):
        title_md, context_box, metrics_box, all_chart, model_chart, dataset_chart, space_chart, logs_box = render_invalid_app_state(
            app_state
        )
        visibility_update = gr.update(
            choices=[("All repos", "all"), ("Public only", "public")],
            value="public",
            visible="hidden",
            interactive=False,
        )
        return (
            app_state,
            title_md,
            context_box,
            visibility_update,
            metrics_box,
            all_chart,
            model_chart,
            dataset_chart,
            space_chart,
            logs_box,
        )

    requested_visibility = current_visibility_mode if current_visibility_mode in {"all", "public"} else app_state["default_visibility"]
    final_visibility = requested_visibility if app_state["can_toggle_visibility"] else "public"

    title_md, context_box, metrics_box, all_chart, model_chart, dataset_chart, space_chart, logs_box = render_app_state(
        app_state,
        final_visibility,
        profile,
    )

    visibility_update = gr.update(
        choices=[("All repos", "all"), ("Public only", "public")],
        value=final_visibility,
        visible=True if app_state["can_toggle_visibility"] else "hidden",
        interactive=bool(app_state["can_toggle_visibility"]),
    )

    return (
        app_state,
        title_md,
        context_box,
        visibility_update,
        metrics_box,
        all_chart,
        model_chart,
        dataset_chart,
        space_chart,
        logs_box,
    )


def rerender_from_state(app_state, visibility_mode, profile: gr.OAuthProfile | None):
    return render_app_state(app_state, visibility_mode, profile)


def maybe_reset_community_section(
    current_community_state,
    username,
    selected_year,
    pr_mode,
    discussion_mode,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    selected_year = int(selected_year)
    pr_mode = pr_mode or "both"
    discussion_mode = discussion_mode or "both"

    identity = resolve_identity(username, profile)
    if is_invalid_identity(identity, username):
        return build_invalid_community_response(username, selected_year, identity)

    if not current_community_state:
        return build_idle_community_response(
            username,
            selected_year,
            profile,
            "Community activity not fetched yet.",
        )

    previous_username = (current_community_state.get("username") or "").strip()
    previous_year = int(current_community_state.get("selected_year") or selected_year)

    same_username = previous_username.lower() == username.lower()
    same_year = previous_year == selected_year

    if same_username and same_year and current_community_state.get("fetched"):
        pr_chart = render_pr_combined_chart(
            current_community_state,
            pr_mode,
            username=username,
            year=selected_year,
        )
        discussion_chart = render_discussion_combined_chart(
            current_community_state,
            discussion_mode,
            username=username,
            year=selected_year,
        )
        return (
            current_community_state,
            render_section_loaded_banner("community activity", current_community_state, profile),
            gr.update(value=pr_mode, visible=True),
            pr_chart,
            gr.update(value=discussion_mode, visible=True),
            discussion_chart,
            current_community_state.get("logs", "Community activity already fetched."),
        )

    return build_idle_community_response(
        username,
        selected_year,
        profile,
        "Community activity needs to be fetched for the current username/year.",
    )


def prepare_single_section_fetch_ui(
    section_key: str,
    username,
    selected_year,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    section_label = SINGLE_SECTION_CONFIG[section_key]["section_label"]

    identity = resolve_identity(username, profile)
    if is_invalid_identity(identity, username):
        return render_generic_invalid_banner(username, identity.get("error"))

    return render_section_fetching_banner(section_label, username, selected_year, profile)


def maybe_reset_single_chart_section(
    section_key: str,
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    cfg = SINGLE_SECTION_CONFIG[section_key]

    username = (username or "").strip()
    selected_year = int(selected_year)
    mode = mode or cfg["default_mode"]

    identity = resolve_identity(username, profile)
    if is_invalid_identity(identity, username):
        return build_invalid_single_section_response(section_key, username, selected_year, identity)

    if not current_state:
        return build_idle_single_section_response(
            section_key,
            username,
            selected_year,
            profile,
            cfg["empty_logs_text"],
        )

    previous_username = (current_state.get("username") or "").strip()
    previous_year = int(current_state.get("selected_year") or selected_year)

    same_username = previous_username.lower() == username.lower()
    same_year = previous_year == selected_year

    if same_username and same_year and current_state.get("fetched"):
        chart = render_single_section_chart(
            section_key,
            current_state,
            mode,
            username=username,
            year=selected_year,
        )
        return (
            current_state,
            render_section_loaded_banner(cfg["section_label"], current_state, profile),
            gr.update(value=mode, visible=True),
            chart,
            current_state.get("logs", "Already fetched."),
        )

    return build_idle_single_section_response(
        section_key,
        username,
        selected_year,
        profile,
        cfg["needs_fetch_text"],
    )


def fetch_and_render_single_chart_section(
    section_key: str,
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    _ = current_state
    cfg = SINGLE_SECTION_CONFIG[section_key]

    username = (username or "").strip()
    selected_year = int(selected_year)
    mode = mode or cfg["default_mode"]

    identity = resolve_identity(username, profile)
    if is_invalid_identity(identity, username):
        state, context_box, mode_update, chart, logs_text = build_invalid_single_section_response(
            section_key,
            username,
            selected_year,
            identity,
        )
        return (
            state,
            context_box,
            chart,
            logs_text,
            mode_update,
        )

    state = fetch_single_section_activity(section_key, username, selected_year)

    chart = render_single_section_chart(
        section_key,
        state,
        mode,
        username=username,
        year=selected_year,
    )

    return (
        state,
        render_section_loaded_banner(cfg["section_label"], state, profile),
        chart,
        state["logs"],
        gr.update(value=mode, visible=True),
    )


def rerender_single_chart_from_state(section_key: str, state, mode):
    cfg = SINGLE_SECTION_CONFIG[section_key]
    if not state:
        return render_empty_chart(cfg["empty_chart_title"])
    return render_single_section_chart(
        section_key,
        state,
        mode or cfg["default_mode"],
        username=(state.get("username") or ""),
        year=int(state.get("selected_year") or datetime.now().year),
    )


def prepare_community_fetch_ui(username, selected_year, profile: gr.OAuthProfile | None):
    username = (username or "").strip()
    identity = resolve_identity(username, profile)
    if is_invalid_identity(identity, username):
        return render_generic_invalid_banner(username, identity.get("error"))
    return render_section_fetching_banner("community activity", username, selected_year, profile)


def fetch_and_render_community(
    current_state,
    username,
    selected_year,
    pr_mode,
    discussion_mode,
    profile: gr.OAuthProfile | None,
):
    username = (username or "").strip()
    selected_year = int(selected_year)
    pr_mode = pr_mode or "both"
    discussion_mode = discussion_mode or "both"

    identity = resolve_identity(username, profile)
    if is_invalid_identity(identity, username):
        state, context_box, pr_mode_update, pr_chart, discussion_mode_update, discussion_chart, logs_text = build_invalid_community_response(
            username,
            selected_year,
            identity,
        )
        return (
            state,
            context_box,
            pr_chart,
            discussion_chart,
            logs_text,
            pr_mode_update,
            discussion_mode_update,
        )

    state = fetch_all_community_activity(username, selected_year)

    pr_chart = render_pr_combined_chart(
        state,
        pr_mode,
        username=username,
        year=selected_year,
    )

    discussion_chart = render_discussion_combined_chart(
        state,
        discussion_mode,
        username=username,
        year=selected_year,
    )

    return (
        state,
        render_section_loaded_banner("community activity", state, profile),
        pr_chart,
        discussion_chart,
        state["logs"],
        gr.update(value=pr_mode, visible=True),
        gr.update(value=discussion_mode, visible=True),
    )


def rerender_pr_from_state(community_state, pr_mode):
    if not community_state:
        return render_empty_chart("Pull Requests")
    return render_pr_combined_chart(
        community_state,
        pr_mode or "both",
        username=(community_state.get("username") or ""),
        year=int(community_state.get("selected_year") or datetime.now().year),
    )


def rerender_discussions_from_state(community_state, discussion_mode):
    if not community_state:
        return render_empty_chart("Community Discussions")
    return render_discussion_combined_chart(
        community_state,
        discussion_mode or "both",
        username=(community_state.get("username") or ""),
        year=int(community_state.get("selected_year") or datetime.now().year),
    )


# ============================================================
# Explicit wrappers for single sections
# ============================================================
def prepare_upvotes_fetch_ui(username, selected_year, profile: gr.OAuthProfile | None):
    return prepare_single_section_fetch_ui("upvotes", username, selected_year, profile)


def prepare_likes_fetch_ui(username, selected_year, profile: gr.OAuthProfile | None):
    return prepare_single_section_fetch_ui("likes", username, selected_year, profile)


def prepare_papers_fetch_ui(username, selected_year, profile: gr.OAuthProfile | None):
    return prepare_single_section_fetch_ui("papers", username, selected_year, profile)


def fetch_and_render_upvotes_section(
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    return fetch_and_render_single_chart_section(
        "upvotes",
        current_state,
        username,
        selected_year,
        mode,
        profile,
    )


def fetch_and_render_likes_section(
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    return fetch_and_render_single_chart_section(
        "likes",
        current_state,
        username,
        selected_year,
        mode,
        profile,
    )


def fetch_and_render_papers_section(
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    return fetch_and_render_single_chart_section(
        "papers",
        current_state,
        username,
        selected_year,
        mode,
        profile,
    )


def rerender_upvotes_from_state(state, mode):
    return rerender_single_chart_from_state("upvotes", state, mode)


def rerender_likes_from_state(state, mode):
    return rerender_single_chart_from_state("likes", state, mode)


def rerender_papers_from_state(state, mode):
    return rerender_single_chart_from_state("papers", state, mode)


def maybe_reset_upvotes_section(
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    return maybe_reset_single_chart_section(
        "upvotes",
        current_state,
        username,
        selected_year,
        mode,
        profile,
    )


def maybe_reset_likes_section(
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    return maybe_reset_single_chart_section(
        "likes",
        current_state,
        username,
        selected_year,
        mode,
        profile,
    )


def maybe_reset_papers_section(
    current_state,
    username,
    selected_year,
    mode,
    profile: gr.OAuthProfile | None,
):
    return maybe_reset_single_chart_section(
        "papers",
        current_state,
        username,
        selected_year,
        mode,
        profile,
    )


def hydrate_header_on_load(
    current_username,
    selected_year,
    profile: gr.OAuthProfile | None,
):
    current_username = (current_username or "").strip()
    selected_year = int(selected_year)
    profile_username = get_viewer_username(profile)

    username_update = gr.update()
    effective_username = current_username

    if not effective_username and profile_username:
        username_update = gr.update(value=profile_username)
        effective_username = profile_username

    repo_context_html = render_idle_context_banner(effective_username, profile)
    community_context_html = render_section_idle_banner("community activity", effective_username, selected_year, profile)
    upvotes_context_html = render_section_idle_banner("upvotes activity", effective_username, selected_year, profile)
    likes_context_html = render_section_idle_banner("likes activity", effective_username, selected_year, profile)
    papers_context_html = render_section_idle_banner("papers activity", effective_username, selected_year, profile)

    return (
        username_update,
        repo_context_html,
        community_context_html,
        upvotes_context_html,
        likes_context_html,
        papers_context_html,
    )


# ============================================================
# UI helpers
# ============================================================
def build_single_chart_section_ui(section_key: str):
    cfg = SINGLE_SECTION_CONFIG[section_key]

    gr.Markdown(f"## {cfg['section_label'].capitalize()}")

    fetch_button = gr.Button(cfg["button_text"], variant="secondary")
    context_box = gr.HTML(render_status_badge(cfg["empty_context_text"]))

    with gr.Column(elem_classes="toggles-container"):
        view_mode = gr.Radio(
            choices=cfg["radio_choices"],
            value=cfg["default_mode"],
            label=cfg["radio_label"],
            visible="hidden",
            elem_classes=["gh-toggle-radio"],
            elem_id=cfg["radio_elem_id"],
        )

    chart = gr.HTML(render_empty_chart(cfg["empty_chart_title"]))
    logs_box = gr.Textbox(
        label=cfg["logs_label"],
        interactive=False,
        lines=cfg["logs_lines"],
        value=cfg["empty_logs_text"],
    )

    return {
        "fetch_button": fetch_button,
        "context_box": context_box,
        "view_mode": view_mode,
        "chart": chart,
        "logs_box": logs_box,
    }


def wire_single_chart_section(
    *,
    fetch_button,
    context_box,
    state_component,
    mode_component,
    chart_component,
    logs_component,
    username_component,
    year_component,
    prepare_fn,
    fetch_fn,
    rerender_fn,
):
    fetch_button.click(
        fn=prepare_fn,
        inputs=[username_component, year_component],
        outputs=context_box,
        show_progress="hidden",
    ).then(
        fn=fetch_fn,
        inputs=[state_component, username_component, year_component, mode_component],
        outputs=[state_component, context_box, chart_component, logs_component, mode_component],
        show_progress="full",
        show_progress_on=[chart_component, logs_component],
    )

    mode_component.change(
        fn=rerender_fn,
        inputs=[state_component, mode_component],
        outputs=chart_component,
        show_progress="hidden",
    )


# ============================================================
# UI
# ============================================================
year_options = list(range(datetime.now().year, 2017, -1))

with gr.Blocks(title="HF Contributions") as demo:
    app_state = gr.State(value=None)
    community_state = gr.State(value=None)

    section_states = {
        section_key: gr.State(value=None)
        for section_key in SINGLE_SECTION_CONFIG
    }

    gr.Markdown("# 🤗 Hugging Face Contributions")

    with gr.Row(elem_id="top-controls"):
        gr.LoginButton("Sign in with Hugging Face", logout_value="Logout ({})")
        username = gr.Textbox(
            label="Username / org",
            placeholder="Enter a Hugging Face username or org",
            scale=3,
        )
        selected_year = gr.Dropdown(
            choices=year_options,
            value=year_options[0],
            label="Year",
            scale=1,
        )
        run_button = gr.Button("Fetch activity", variant="primary", scale=1)

    context_box = gr.HTML(
        render_status_badge("Not logged in · Enter a username to get started")
    )

    title_md = gr.Markdown("## Ready")

    with gr.Column(elem_classes="toggles-container"):
        visibility_mode = gr.Radio(
            choices=[("All repos", "all"), ("Public only", "public")],
            value="public",
            label="Visibility",
            visible="hidden",
            interactive=False,
            elem_classes=["gh-toggle-radio"],
            elem_id="repo-visibility-toggle",
        )

    zero_counts = {kind: 0 for kind in REPO_KINDS}
    metrics_box = gr.HTML(
        render_metric_cards(
            0,
            zero_counts,
            zero_counts,
            year_options[0],
        )
    )

    all_chart = gr.HTML(render_empty_chart("All activity"))
    model_chart = gr.HTML(render_empty_chart("Models"))
    dataset_chart = gr.HTML(render_empty_chart("Datasets"))
    space_chart = gr.HTML(render_empty_chart("Spaces"))

    logs_box = gr.Textbox(label="Logs / Warnings", interactive=False, lines=8)

    gr.Markdown("## Community activity")

    fetch_community_button = gr.Button("Fetch community activity", variant="secondary")
    community_context_box = gr.HTML(
        render_status_badge("Not logged in · Enter a username to fetch community activity")
    )

    with gr.Column(elem_classes="toggles-container"):
        pr_view_mode = gr.Radio(
            choices=[
                ("Opened", "opened"),
                ("Follow-up", "activity"),
                ("Both", "both"),
            ],
            value="both",
            label="Pull Requests view",
            visible="hidden",
            elem_classes=["gh-toggle-radio"],
            elem_id="pr-view-toggle",
        )

    pr_chart = gr.HTML(render_empty_chart("Pull Requests"))

    with gr.Column(elem_classes="toggles-container"):
        discussion_view_mode = gr.Radio(
            choices=[
                ("Opened", "opened"),
                ("Follow-up", "activity"),
                ("Both", "both"),
            ],
            value="both",
            label="Community Discussions view",
            visible="hidden",
            elem_classes=["gh-toggle-radio"],
            elem_id="discussion-view-toggle",
        )

    discussion_chart = gr.HTML(render_empty_chart("Community Discussions"))

    community_logs_box = gr.Textbox(
        label="Community Fetch Logs",
        interactive=False,
        lines=12,
        value="Community activity not fetched yet.",
    )

    single_section_components = {}
    for section_key in ("upvotes", "likes", "papers"):
        single_section_components[section_key] = build_single_chart_section_ui(section_key)

    repo_fetch_outputs = [
        app_state,
        title_md,
        context_box,
        visibility_mode,
        metrics_box,
        all_chart,
        model_chart,
        dataset_chart,
        space_chart,
        logs_box,
    ]

    repo_render_outputs = [
        title_md,
        context_box,
        metrics_box,
        all_chart,
        model_chart,
        dataset_chart,
        space_chart,
        logs_box,
    ]

    community_reset_outputs = [
        community_state,
        community_context_box,
        pr_view_mode,
        pr_chart,
        discussion_view_mode,
        discussion_chart,
        community_logs_box,
    ]

    community_fetch_outputs = [
        community_state,
        community_context_box,
        pr_chart,
        discussion_chart,
        community_logs_box,
        pr_view_mode,
        discussion_view_mode,
    ]

    single_section_outputs = {}
    for section_key, components in single_section_components.items():
        single_section_outputs[f"{section_key}_reset"] = [
            section_states[section_key],
            components["context_box"],
            components["view_mode"],
            components["chart"],
            components["logs_box"],
        ]
        single_section_outputs[f"{section_key}_fetch"] = [
            section_states[section_key],
            components["context_box"],
            components["chart"],
            components["logs_box"],
            components["view_mode"],
        ]

    demo.load(
        fn=hydrate_header_on_load,
        inputs=[username, selected_year],
        outputs=[username, context_box, community_context_box]
        + [single_section_components[k]["context_box"] for k in ("upvotes", "likes", "papers")],
        show_progress="hidden",
    )

    repo_chain = run_button.click(
        fn=prepare_repo_fetch_ui,
        inputs=[username, selected_year, visibility_mode],
        outputs=[context_box, visibility_mode],
        show_progress="hidden",
    ).then(
        fn=fetch_and_render_repo_only,
        inputs=[username, selected_year, visibility_mode],
        outputs=repo_fetch_outputs,
        show_progress="full",
        show_progress_on=[
            metrics_box,
            all_chart,
            model_chart,
            dataset_chart,
            space_chart,
            logs_box,
        ],
    ).then(
        fn=maybe_reset_community_section,
        inputs=[community_state, username, selected_year, pr_view_mode, discussion_view_mode],
        outputs=community_reset_outputs,
        show_progress="hidden",
    ).then(
        fn=maybe_reset_upvotes_section,
        inputs=[
            section_states["upvotes"],
            username,
            selected_year,
            single_section_components["upvotes"]["view_mode"],
        ],
        outputs=single_section_outputs["upvotes_reset"],
        show_progress="hidden",
    ).then(
        fn=maybe_reset_likes_section,
        inputs=[
            section_states["likes"],
            username,
            selected_year,
            single_section_components["likes"]["view_mode"],
        ],
        outputs=single_section_outputs["likes_reset"],
        show_progress="hidden",
    ).then(
        fn=maybe_reset_papers_section,
        inputs=[
            section_states["papers"],
            username,
            selected_year,
            single_section_components["papers"]["view_mode"],
        ],
        outputs=single_section_outputs["papers_reset"],
        show_progress="hidden",
    )

    visibility_mode.change(
        fn=rerender_from_state,
        inputs=[app_state, visibility_mode],
        outputs=repo_render_outputs,
        show_progress="hidden",
    )

    fetch_community_button.click(
        fn=prepare_community_fetch_ui,
        inputs=[username, selected_year],
        outputs=community_context_box,
        show_progress="hidden",
    ).then(
        fn=fetch_and_render_community,
        inputs=[community_state, username, selected_year, pr_view_mode, discussion_view_mode],
        outputs=community_fetch_outputs,
        show_progress="full",
        show_progress_on=[
            pr_chart,
            discussion_chart,
            community_logs_box,
        ],
    )

    pr_view_mode.change(
        fn=rerender_pr_from_state,
        inputs=[community_state, pr_view_mode],
        outputs=pr_chart,
        show_progress="hidden",
    )

    discussion_view_mode.change(
        fn=rerender_discussions_from_state,
        inputs=[community_state, discussion_view_mode],
        outputs=discussion_chart,
        show_progress="hidden",
    )

    wire_single_chart_section(
        fetch_button=single_section_components["upvotes"]["fetch_button"],
        context_box=single_section_components["upvotes"]["context_box"],
        state_component=section_states["upvotes"],
        mode_component=single_section_components["upvotes"]["view_mode"],
        chart_component=single_section_components["upvotes"]["chart"],
        logs_component=single_section_components["upvotes"]["logs_box"],
        username_component=username,
        year_component=selected_year,
        prepare_fn=prepare_upvotes_fetch_ui,
        fetch_fn=fetch_and_render_upvotes_section,
        rerender_fn=rerender_upvotes_from_state,
    )

    wire_single_chart_section(
        fetch_button=single_section_components["likes"]["fetch_button"],
        context_box=single_section_components["likes"]["context_box"],
        state_component=section_states["likes"],
        mode_component=single_section_components["likes"]["view_mode"],
        chart_component=single_section_components["likes"]["chart"],
        logs_component=single_section_components["likes"]["logs_box"],
        username_component=username,
        year_component=selected_year,
        prepare_fn=prepare_likes_fetch_ui,
        fetch_fn=fetch_and_render_likes_section,
        rerender_fn=rerender_likes_from_state,
    )

    wire_single_chart_section(
        fetch_button=single_section_components["papers"]["fetch_button"],
        context_box=single_section_components["papers"]["context_box"],
        state_component=section_states["papers"],
        mode_component=single_section_components["papers"]["view_mode"],
        chart_component=single_section_components["papers"]["chart"],
        logs_component=single_section_components["papers"]["logs_box"],
        username_component=username,
        year_component=selected_year,
        prepare_fn=prepare_papers_fetch_ui,
        fetch_fn=fetch_and_render_papers_section,
        rerender_fn=rerender_papers_from_state,
    )

demo.queue().launch(ssr_mode=False, mcp_server=False, css_paths=["styles.css"])