File size: 185,714 Bytes
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702b153
060bb47
 
 
 
 
 
550d5be
e64c086
060bb47
 
9f4bc89
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
063809e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb5e8ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26914b4
060bb47
 
 
 
 
550d5be
 
 
 
060bb47
 
 
 
 
 
752bedc
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88a7131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
843e792
 
 
060bb47
 
 
843e792
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d76a369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
d76a369
 
 
 
 
 
 
060bb47
 
 
d76a369
 
 
 
 
 
 
 
060bb47
 
 
a635fbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a635fbe
060bb47
 
 
 
 
a635fbe
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20cdca4
 
 
060bb47
20cdca4
060bb47
 
 
 
 
 
 
 
 
a635fbe
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
f0c3f5a
 
 
 
 
 
eeea851
 
 
 
 
 
 
 
 
 
 
 
 
 
f0c3f5a
 
 
 
 
 
 
 
 
eeea851
438edb5
f0c3f5a
 
eeea851
f0c3f5a
 
 
 
 
 
 
 
eeea851
 
 
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438edb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeea851
 
 
 
 
 
 
 
 
 
 
438edb5
 
 
 
eeea851
 
 
 
 
 
 
 
 
 
 
 
f0c3f5a
 
 
eeea851
 
 
 
 
 
 
f0c3f5a
 
 
 
 
eeea851
f0c3f5a
 
 
 
 
 
 
 
 
 
eeea851
 
 
 
 
f0c3f5a
eeea851
f0c3f5a
 
 
 
 
 
eeea851
 
 
 
 
438edb5
eeea851
 
 
 
 
 
 
 
 
 
 
 
7df48f4
 
 
 
f0c3f5a
7df48f4
f0c3f5a
 
 
 
 
 
 
 
 
 
d76a369
 
 
060bb47
d76a369
 
 
 
 
 
 
 
060bb47
 
 
 
d76a369
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
702b153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
843e792
 
 
 
702b153
843e792
 
 
 
 
 
 
702b153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
d67ba8e
 
 
 
 
 
550d5be
 
 
 
 
1259937
 
 
 
 
 
702b153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
cb5e8ef
 
 
060bb47
 
 
 
063809e
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7446d10
060bb47
7446d10
 
 
 
 
060bb47
 
 
550d5be
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
5a0e83d
 
 
 
060bb47
 
d76a369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550d5be
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550d5be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a15b07
 
 
 
 
 
550d5be
 
 
 
 
060bb47
752bedc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
752bedc
 
 
060bb47
 
 
 
 
 
 
752bedc
 
 
060bb47
 
752bedc
 
 
 
060bb47
 
 
 
 
26914b4
060bb47
 
 
 
 
 
88a7131
 
 
 
 
 
 
 
 
 
 
e52101b
 
 
88a7131
 
 
 
752bedc
 
 
88a7131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
752bedc
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752bedc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438edb5
eeea851
 
 
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeea851
438edb5
 
f0c3f5a
 
 
 
 
 
 
 
 
 
eeea851
438edb5
f0c3f5a
 
 
 
 
 
 
 
 
 
 
867ce54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0c3f5a
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d67ba8e
 
 
be23b1b
 
d67ba8e
be23b1b
 
 
 
 
 
 
 
 
21dfced
be23b1b
21dfced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d67ba8e
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91ed780
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0167c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e64c086
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995ee2a
 
 
 
 
 
 
345b9c9
 
 
 
 
 
 
 
 
 
 
7a41c01
 
 
 
 
 
dd2d535
 
 
 
 
 
 
 
 
 
e64c086
 
995ee2a
345b9c9
dd2d535
e64c086
 
 
 
 
 
 
 
 
 
995ee2a
 
 
 
6983e3b
 
 
 
 
 
 
 
 
05da2fa
 
e64c086
995ee2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db7532c
 
 
7c54abf
db7532c
 
 
 
345b9c9
 
 
 
 
 
 
 
 
7a41c01
 
 
 
 
 
 
dd2d535
 
 
 
 
 
 
 
73b3e85
 
e64c086
 
05da2fa
 
 
 
 
 
 
 
 
 
 
 
 
 
e64c086
 
7a41c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd2d535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73b3e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4229225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e171c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13a90b2
 
 
 
 
 
 
 
 
61e171c
 
 
 
 
1c7c498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7446d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26914b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3317015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21b1923
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3317015
a0ee590
3317015
 
 
 
 
 
 
 
 
21b1923
3317015
 
 
674bee6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e64c086
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995ee2a
 
 
 
345b9c9
 
 
 
 
 
 
 
 
7a41c01
 
 
 
 
 
dd2d535
 
 
 
 
 
 
 
 
0360d9f
 
 
 
 
 
 
e64c086
345b9c9
 
 
dd2d535
345b9c9
e64c086
 
 
0360d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec5933d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db7532c
 
7c54abf
345b9c9
 
 
dd2d535
 
ec5933d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db7532c
7c54abf
db7532c
345b9c9
 
 
 
7a41c01
 
 
ec5933d
 
 
 
 
 
 
 
e64c086
 
 
ec5933d
 
 
e64c086
ec5933d
e64c086
 
 
752bedc
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
2017fcd
 
 
 
 
477cee9
060bb47
 
 
 
 
 
2017fcd
 
 
 
 
477cee9
 
5a0e83d
 
 
 
 
 
5dde9d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a0e83d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dde9d0
 
 
 
 
 
 
 
5a0e83d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
5a0e83d
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
5a0e83d
 
 
 
 
 
060bb47
 
 
 
 
 
5a0e83d
 
 
 
060bb47
 
 
 
 
 
 
 
a5e129b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5e129b
060bb47
 
 
 
 
 
 
 
 
 
d76a369
 
 
060bb47
 
 
 
 
a5e129b
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
5a0e83d
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5e129b
060bb47
 
 
 
 
 
 
d76a369
 
 
 
 
 
 
060bb47
 
 
26914b4
 
 
3317015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05da2fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21b1923
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dde9d0
21b1923
 
 
 
 
 
 
 
 
 
 
26914b4
 
 
 
 
 
 
 
 
5dde9d0
 
 
 
 
26914b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5e129b
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5dde9d0
 
 
 
060bb47
 
 
 
 
 
 
 
3317015
 
 
a0ee590
3317015
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f4bc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d76a369
 
 
 
 
 
 
9f4bc89
d76a369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f4bc89
 
 
 
060bb47
 
 
 
550d5be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26914b4
 
 
550d5be
 
 
 
 
 
 
 
 
 
26914b4
550d5be
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
88a7131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e52101b
 
 
 
88a7131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e52101b
 
 
 
 
 
 
88a7131
e52101b
88a7131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
db78650
 
 
 
 
 
 
 
060bb47
 
 
db78650
 
 
060bb47
 
 
 
db78650
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78650
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d76a369
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
d76a369
 
060bb47
d76a369
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
db78650
060bb47
 
 
 
db78650
060bb47
 
db78650
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78650
 
060bb47
db78650
 
 
 
 
060bb47
 
 
 
 
 
 
db78650
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78650
060bb47
 
 
db78650
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db78650
 
060bb47
 
db78650
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
db78650
 
 
 
 
 
060bb47
db78650
 
 
060bb47
 
 
 
 
 
 
 
 
 
db78650
 
 
 
 
060bb47
 
 
db78650
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
db78650
 
 
 
 
 
 
 
d76a369
 
 
 
 
 
 
060bb47
 
d76a369
 
 
 
 
 
 
db78650
 
 
 
d76a369
060bb47
d76a369
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1259937
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
6983e3b
 
 
 
 
 
 
 
1259937
060bb47
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
"""Local web UI for the Digital Evolution Engine.

Single-user Flask server intended to be launched by the desktop ``.app`` and
opened in the user's browser. Stateful by design (long-running jobs are kept
in memory, results held until a new job replaces them) — this is *not* a
multi-tenant service.

API surface:
    POST /api/preview     parse a sequence (file upload OR JSON body) and
                          return its metadata + any CDS features.
    POST /api/run         enqueue a pipeline job. Returns immediately with
                          a job_id; the work runs in a background thread.
    GET  /api/status/:id  poll job progress.
    GET  /api/result/:id  fetch the variant table once a job has finished.
    GET  /api/download/:id?format=csv|fasta  download outputs.
    POST /api/shutdown    cleanly stop the server (used by the desktop app
                          when the user explicitly quits).
"""

from __future__ import annotations

import hashlib
import io
import json
import logging
import os
import re
import tempfile
import threading
import time
import traceback
import uuid
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional

from flask import Flask, Response, jsonify, request, send_file, send_from_directory

from dee import auth as _auth
from dee.core.crispr import find_guides as _find_crispr_guides, guides_to_csv_rows as _crispr_csv_rows
from dee.core.codon import (
    DEFAULT_FORBIDDEN_SITES,
    pcr_metrics,
    reverse_translate,
    scrub_restriction_sites,
    variants_to_dataframe,
    write_library_csv,
)
from dee.core.sequence import (
    SequenceValidationError,
    find_orfs_in_dna,
    list_cds_features,
    parse_input,
)
from dee.models.scorer import ESM2Scorer, ScorerConfig, top_percentile_pool
from dee.optimizer.search import SearchConfig, apply_variant, evolve

logger = logging.getLogger("dee.server")

STATIC_DIR = Path(__file__).resolve().parent / "static"


# Production assets are minified on the fly (cached by mtime) so the served JS/CSS
# is compact + comment-free — source files stay the single source of truth.
# Conservative minifiers (rjsmin/rcssmin); any failure falls back to the raw file.
_MIN_CACHE: Dict[str, tuple] = {}


def _minified_asset(filename: str) -> Optional[str]:
    path = STATIC_DIR / filename
    try:
        mtime = path.stat().st_mtime
    except OSError:
        return None
    ent = _MIN_CACHE.get(filename)
    if ent and ent[0] == mtime:
        return ent[1]
    try:
        src = path.read_text(encoding="utf-8")
        if filename.endswith(".js"):
            import rjsmin
            out = rjsmin.jsmin(src)
        else:
            import rcssmin
            out = rcssmin.cssmin(src)
        _MIN_CACHE[filename] = (mtime, out)
        return out
    except Exception:  # noqa: BLE001 — never let minification break asset serving
        logger.exception("minify failed for %s; serving raw", filename)
        return None


def _clean_html(html: str) -> str:
    """Strip developer HTML comments + minify inline <script>/<style> so the
    SERVED page carries no internal engineering notes (source stays commented).
    Protects script/style regions before removing comments; keeps conditional
    comments; minifies inline JS/CSS with rjsmin/rcssmin."""
    import re as _re
    blocks: list = []

    def _stash(m):
        blocks.append(m.group(0))
        return f"\x00{len(blocks) - 1}\x00"

    tmp = _re.sub(r'<script\b[^>]*>.*?</script>|<style\b[^>]*>.*?</style>',
                  _stash, html, flags=_re.S | _re.I)
    tmp = _re.sub(r'<!--(?!\[if).*?-->', '', tmp, flags=_re.S)   # drop HTML comments (keep conditional)

    def _restore(m):
        blk = blocks[int(m.group(1))]
        sm = _re.match(r'(<script\b[^>]*>)(.*)(</script>)', blk, flags=_re.S | _re.I)
        if sm:
            if _re.search(r'\bsrc\s*=', sm.group(1), _re.I):
                return blk
            try:
                import rjsmin
                return sm.group(1) + rjsmin.jsmin(sm.group(2)) + sm.group(3)
            except Exception:  # noqa: BLE001
                return blk
        cm = _re.match(r'(<style\b[^>]*>)(.*)(</style>)', blk, flags=_re.S | _re.I)
        if cm:
            try:
                import rcssmin
                return cm.group(1) + rcssmin.cssmin(cm.group(2)) + cm.group(3)
            except Exception:  # noqa: BLE001
                return blk
        return blk

    return _re.sub(r'\x00(\d+)\x00', _restore, tmp)


def _cleaned_html(filename: str) -> Optional[str]:
    """Cached comment-stripped HTML (mtime-keyed). None on failure → serve raw."""
    path = STATIC_DIR / filename
    try:
        mtime = path.stat().st_mtime
    except OSError:
        return None
    ent = _MIN_CACHE.get("html::" + filename)
    if ent and ent[0] == mtime:
        return ent[1]
    try:
        out = _clean_html(path.read_text(encoding="utf-8"))
        _MIN_CACHE["html::" + filename] = (mtime, out)
        return out
    except Exception:  # noqa: BLE001
        logger.exception("html clean failed for %s; serving raw", filename)
        return None


STATE_DIR = Path.home() / ".dee" / "state"
OUTPUT_DIR = Path.home() / ".dee" / "output"
DESKTOP_DIR = Path.home() / "Desktop"
STATE_DIR.mkdir(parents=True, exist_ok=True)
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)


def _patch_ssl_for_macos() -> None:
    """Some macOS Python builds ship without a system CA bundle, so
    ``urllib.request.urlopen`` (which Biopython's NCBIWWW.qblast uses
    internally) blows up with ``CERTIFICATE_VERIFY_FAILED: self-signed
    certificate in certificate chain`` when it tries to reach
    https://blast.ncbi.nlm.nih.gov.

    Fix it by installing a default urllib opener whose HTTPS handler uses
    certifi's bundled CA roots (certifi is already a transitive dep of
    huggingface-hub). Idempotent and safe to call multiple times.
    """
    import ssl
    import urllib.request

    try:
        import certifi
    except ImportError:  # pragma: no cover — certifi is a dep of HF hub
        logger.warning("certifi not installed; BLAST may fail on macOS Pythons.")
        return

    try:
        ctx = ssl.create_default_context(cafile=certifi.where())
        https_handler = urllib.request.HTTPSHandler(context=ctx)
        opener = urllib.request.build_opener(https_handler)
        urllib.request.install_opener(opener)
        # Also override the module-level default context so callers that go
        # around urllib (e.g. http.client direct) still get the certifi roots.
        ssl._create_default_https_context = lambda: ssl.create_default_context(
            cafile=certifi.where()
        )
        logger.info("Patched urllib SSL context with certifi CA bundle.")
    except Exception as exc:  # noqa: BLE001 — best-effort patch
        logger.warning("Could not patch SSL CA bundle: %s", exc)


_patch_ssl_for_macos()


# ----------------------------------------------------------------- job state


@dataclass
class JobState:
    job_id: str
    status: str = "pending"
    progress: float = 0.0
    message: str = "Queued."
    started_at: float = field(default_factory=time.time)
    finished_at: Optional[float] = None
    wt_identifier: str = ""
    wt_protein: str = ""
    csv_path: Optional[str] = None
    desktop_path: Optional[str] = None
    variants: Optional[List[Dict[str, Any]]] = None
    library_id: Optional[str] = None   # set on save → lets the client log outcomes
    error: Optional[str] = None
    # Frozen copy of the user's settings + the parameters the engine actually
    # used. Surfaces in the UI's metadata pills and the auto-generated
    # methods paragraph; also a paper-trail for reproducibility.
    settings_used: Dict[str, Any] = field(default_factory=dict)
    # Supabase user_id captured at request time, used to attribute the
    # library to the user when the pipeline finishes. None for anonymous
    # runs; the save-to-Storage path no-ops in that case.
    user_id: Optional[str] = None

    def elapsed(self) -> float:
        end = self.finished_at if self.finished_at else time.time()
        return round(end - self.started_at, 1)

    def public(self) -> Dict[str, Any]:
        # csv_path / desktop_path intentionally omitted (audit H2): they
        # leak the server's filesystem layout. They remain on the dataclass
        # for internal use by /api/download and the library-save worker.
        return {
            "job_id": self.job_id,
            "status": self.status,
            "progress": round(self.progress, 3),
            "message": self.message,
            "started_at": self.started_at,
            "elapsed_seconds": self.elapsed(),
            "wt_identifier": self.wt_identifier,
            "wt_protein_length": len(self.wt_protein),
            "error": self.error,
        }


_JOBS: Dict[str, JobState] = {}
_JOBS_LOCK = threading.Lock()

# Per-job mutex for editing variant rows. The edit handler reads
# job.variants, mutates one row, and rewrites the CSV on disk; without
# this lock two near-simultaneous edits could interleave and write a
# torn library file. _EDIT_LOCKS is itself guarded by _JOBS_LOCK on
# create. Holds one lock per job for the lifetime of the process —
# small enough not to bother evicting.
_EDIT_LOCKS: Dict[str, threading.Lock] = {}


def _edit_lock_for(job_id: str) -> threading.Lock:
    with _JOBS_LOCK:
        lock = _EDIT_LOCKS.get(job_id)
        if lock is None:
            lock = threading.Lock()
            _EDIT_LOCKS[job_id] = lock
        return lock


def _get_job(job_id: str) -> Optional[JobState]:
    with _JOBS_LOCK:
        return _JOBS.get(job_id)


_JOBS_MAX = 2000   # cap retained jobs so a long-lived process can't grow forever


def _put_job(job: JobState) -> None:
    with _JOBS_LOCK:
        _JOBS[job.job_id] = job
        # Bound memory: previously every job + its edit lock was kept for the
        # process lifetime. Dicts preserve insertion order, so evict the oldest
        # (long-finished) jobs once we're over the cap.
        while len(_JOBS) > _JOBS_MAX:
            old_id = next(iter(_JOBS))
            _JOBS.pop(old_id, None)
            _EDIT_LOCKS.pop(old_id, None)


# ----------------------------------------------------------------- preview cache


# Uploaded files / pasted strings are cached briefly so /api/preview and the
# subsequent /api/run don't have to re-receive the same payload. Keyed by a
# session_id we hand back to the browser.
_SESSIONS: Dict[str, Dict[str, Any]] = {}
_SESSIONS_LOCK = threading.Lock()


# ----------------------------------------------------------------- BLAST jobs

@dataclass
class BlastJob:
    """One asynchronous NCBI-BLAST submission. Keyed by sequence hash so
    repeat lookups on the same WT protein return instantly from cache."""

    job_id: str
    seq_hash: str
    status: str = "pending"
    started_at: float = field(default_factory=time.time)
    finished_at: Optional[float] = None
    hits: List[Dict[str, Any]] = field(default_factory=list)
    error: Optional[str] = None

    def elapsed(self) -> float:
        end = self.finished_at if self.finished_at else time.time()
        return round(end - self.started_at, 1)

    def public(self) -> Dict[str, Any]:
        return {
            "job_id": self.job_id,
            "status": self.status,
            "elapsed_seconds": self.elapsed(),
            "hits": self.hits,
            "error": self.error,
        }


_BLAST_CACHE: Dict[str, BlastJob] = {}   # seq_hash -> BlastJob
_BLAST_BY_ID: Dict[str, BlastJob] = {}   # job_id -> BlastJob
_BLAST_LOCK = threading.Lock()


def _hash_sequence(protein: str) -> str:
    return hashlib.sha256(protein.encode("utf-8")).hexdigest()[:16]


def _extract_organism(hit_def: str) -> str:
    """NCBI hit descriptions look like 'GFP [Aequorea victoria]'. Pull out
    the bracketed organism if present; fall back to empty string."""
    m = re.search(r"\[([^\]]+)\]", hit_def or "")
    return m.group(1) if m else ""


def _trim_description(hit_def: str) -> str:
    """Strip the trailing '[organism]' from the description for cleaner
    display — the organism is shown separately."""
    return re.sub(r"\s*\[[^\]]+\]\s*$", "", hit_def or "").strip()


def _extract_uniprot(alignment) -> Optional[str]:
    """Pull a UniProt accession out of an NCBI BLAST alignment if there is one.

    NCBI hit_id strings look like:
       ``sp|P12345|HUMAN_GENE``   (SwissProt — has UniProt accession)
       ``ref|NP_001234.1|``       (RefSeq — no direct UniProt mapping)
       ``pdb|1ABC|A``             (PDB)
       ``gb|AAA12345.1|``         (GenBank)

    AlphaFold-DB only indexes UniProt entries, so we only return something
    when we see ``sp|`` (SwissProt) or ``tr|`` (TrEMBL) prefixes.

    Audit M4: the previous regex ``^[A-Z0-9]+(?:-\\d+)?$`` matched the
    modern accession formats only — the canonical ``P12345`` /
    ``Q9NPB9`` 6-char form, the 10-char form (``A0A1B2C3D4``), and the
    isoform suffix (``-2``). It missed two legitimate formats still
    occasionally seen in NCBI hits:

      * Lowercase-letter accessions returned by some legacy mirrors
        (``p12345``) — UniProt's own API is case-insensitive on lookup.
      * Underscore-prefixed entry names ("``HUMAN_INSR``" without the
        accession token) where the upstream RefSeq pipe is missing.

    Now the regex accepts case-insensitive accessions and validates the
    structure rather than just the alphabet, and we additionally try the
    third pipe-segment as an entry name in case the second segment
    didn't match.
    """
    # UniProt accession structure (UniProt knowledgebase, kept in sync with
    # https://www.uniprot.org/help/accession_numbers): 6-char or 10-char,
    # alternating letter / digit groups. The detail is too fiddly to
    # encode strictly in a regex without rejecting legitimate hits, so
    # we use the documented "anything matching this character class of
    # length 6 or 10" form and an optional isoform suffix.
    _ACCESSION_RE = re.compile(r"^([A-Za-z0-9]{6}|[A-Za-z0-9]{10})(?:-\d+)?$")
    hit_id = getattr(alignment, "hit_id", "") or ""
    for token in hit_id.split(";"):
        token = token.strip()
        parts = token.split("|")
        # Format: sp|<accession>|<entry_name>
        if len(parts) >= 2 and parts[0].lower() in ("sp", "tr"):
            candidate = parts[1].upper()
            m = _ACCESSION_RE.match(candidate)
            if m:
                # Normalize to the canonical upper-case form.
                return m.group(0).upper()
    return None


def _swissprot_uniprot(protein: str) -> Optional[Dict[str, Any]]:
    """Resolve the nearest REVIEWED (Swiss-Prot) protein for ``protein``.

    Why this exists: the primary search hits ``nr``, which is excellent for
    *identifying* a protein but is crowded with redundant GenBank / TPA records
    (e.g. thousands of near-identical Cas9 orthologs deposited as ``tpg|HER…``).
    Those have no UniProt accession, so a heavily-sequenced protein can come
    back from ``nr`` with **zero** UniProt hits in the top results even though a
    structure plainly exists — the one curated UniProt entry is simply buried.

    Every UniProtKB/Swiss-Prot entry has an AlphaFold-DB model, so a homology
    search against the small, curated ``swissprot`` database reliably surfaces
    the closest *known* structure (SpCas9 → Q99ZW2). Returns the accession plus
    identity / organism for honest labelling, or ``None`` if nothing close.
    """
    try:
        from Bio.Blast import NCBIWWW, NCBIXML

        handle = NCBIWWW.qblast(
            program="blastp",
            database="swissprot",
            sequence=protein,
            hitlist_size=1,
            expect=1e-3,
        )
        for record in NCBIXML.parse(handle):
            for alignment in record.alignments[:1]:
                if not alignment.hsps:
                    continue
                acc = _extract_uniprot(alignment)
                if not acc:
                    continue
                hsp = alignment.hsps[0]
                return {
                    "uniprot": acc,
                    "identity_pct": round(
                        100.0 * hsp.identities / max(1, hsp.align_length), 1
                    ),
                    "organism": _extract_organism(alignment.hit_def),
                    "description": _trim_description(alignment.hit_def),
                }
            break  # only one query record
    except Exception:  # noqa: BLE001 — best-effort; absence is handled honestly
        logger.exception("Swiss-Prot structure-resolution BLAST failed.")
    return None


def _attach_structure_homolog(job: BlastJob, protein: str) -> None:
    """If no parsed hit carries a UniProt accession, fall back to a Swiss-Prot
    homology search and pin the resolved accession onto the top hit so the
    frontend AlphaFold embed lights up. Records the homolog's organism +
    identity separately so the UI can label it honestly as the *closest known*
    structure rather than the exact query."""
    if not job.hits or any(h.get("uniprot") for h in job.hits):
        return
    sp = _swissprot_uniprot(protein)
    if not sp:
        return
    acc = sp["uniprot"]
    top = job.hits[0]
    top["uniprot"] = acc
    top["alphafold_url"] = f"https://alphafold.ebi.ac.uk/files/AF-{acc}-F1-model_v6.pdb"
    top["alphafold_page"] = f"https://alphafold.ebi.ac.uk/entry/{acc}"
    # Provenance: this UniProt entry is the nearest reviewed homolog, NOT the
    # nr top hit itself — keep its organism / identity distinct for the label.
    top["uniprot_via"] = "swissprot_homolog"
    top["uniprot_organism"] = sp.get("organism") or ""
    top["uniprot_identity_pct"] = sp.get("identity_pct")
    top["uniprot_description"] = sp.get("description") or ""


def _run_blast(job: BlastJob, protein: str) -> None:
    """Submit to NCBI BLAST and parse the top hits.

    Uses Biopython's NCBIWWW wrapper (the public web service). Polite delays
    and rate limits are imposed by NCBI server-side; we keep hitlist small
    and expect strict to minimize bandwidth.
    """
    try:
        # Biopython is heavy; import lazily so the rest of the server boots
        # without a hard Bio dependency at startup.
        from Bio.Blast import NCBIWWW, NCBIXML

        job.status = "submitting"
        result_handle = NCBIWWW.qblast(
            program="blastp",
            database="nr",
            sequence=protein,
            hitlist_size=8,
            expect=1e-5,
        )
        job.status = "parsing"

        for record in NCBIXML.parse(result_handle):
            for alignment in record.alignments[:8]:
                if not alignment.hsps:
                    continue
                # Use the best (lowest-evalue) HSP from each alignment.
                hsp = alignment.hsps[0]
                identity_pct = round(
                    100.0 * hsp.identities / max(1, hsp.align_length), 1
                )
                coverage_pct = round(
                    100.0 * hsp.align_length / max(1, len(protein)), 1
                )
                uniprot = _extract_uniprot(alignment)
                job.hits.append(
                    {
                        "accession": getattr(alignment, "accession", "") or "",
                        "hit_id": getattr(alignment, "hit_id", "") or "",
                        "description": _trim_description(alignment.hit_def),
                        "organism": _extract_organism(alignment.hit_def),
                        "length": alignment.length,
                        "identity_pct": identity_pct,
                        "coverage_pct": coverage_pct,
                        "evalue": float(hsp.expect),
                        "bit_score": float(hsp.bits),
                        # UniProt accession when available — gates the
                        # AlphaFold-DB structure embed on the frontend.
                        "uniprot": uniprot,
                        # Fallback URL only — the client re-resolves the current
                        # model version via the AlphaFold prediction API
                        # (the DB bumps versions over time: v4 → v6 → …).
                        "alphafold_url": (
                            f"https://alphafold.ebi.ac.uk/files/AF-{uniprot}-F1-model_v6.pdb"
                            if uniprot else None
                        ),
                        "alphafold_page": (
                            f"https://alphafold.ebi.ac.uk/entry/{uniprot}"
                            if uniprot else None
                        ),
                    }
                )
            break  # only one query record

        # nr is great for ID but buries the curated UniProt entry under
        # redundant GenBank/TPA records — so if nothing came back with a
        # UniProt accession, resolve the closest reviewed homolog (which always
        # has an AlphaFold model) before finishing.
        _attach_structure_homolog(job, protein)
        job.status = "done"
    except Exception as exc:  # noqa: BLE001 — surface anything as an error
        logger.exception("BLAST failed.")
        job.status = "error"
        job.error = f"{type(exc).__name__}: {exc}"
    finally:
        job.finished_at = time.time()


# --------------------------------------------------- Primer Picker (multi-BLAST)
# Batch primer analysis: the deterministic scoring lives in core/primers.py;
# here we own the async NCBI specificity scan. All primers go to NCBI in ONE
# blastn-short submission (a multi-FASTA query) — literally "blast them all
# together" — and NCBIXML yields one record per primer, in query order.

# Organism targeting for the specificity scan — mirrors Primer-BLAST's
# "Organism" field. Restricts the BLAST via an Entrez query so off-target =
# "would mis-prime in THIS genome", not "matches something, somewhere, in nt".
_PRIMER_ORGANISMS = {
    "human":   '"Homo sapiens"[Organism]',
    "mouse":   '"Mus musculus"[Organism]',
    "ecoli":   '"Escherichia coli"[Organism]',
    "yeast":   '"Saccharomyces cerevisiae"[Organism]',
    "rat":     '"Rattus norvegicus"[Organism]',
    "zebrafish": '"Danio rerio"[Organism]',
    "all":     "",     # whole nt — broad, noisier
}


@dataclass
class PrimerJob:
    job_id: str
    seq_hash: str
    status: str = "pending"               # pending|scanning|done|error
    started_at: float = field(default_factory=time.time)
    finished_at: Optional[float] = None
    primers: List[Dict[str, Any]] = field(default_factory=list)   # scored, pre-spec
    template: str = ""
    organism: str = "human"
    three_prime_strict: bool = False
    warnings: List[str] = field(default_factory=list)
    specificity: Optional[Dict[str, Dict[str, Any]]] = None       # id -> {...}
    products: List[Dict[str, Any]] = field(default_factory=list)  # in-silico PCR
    error: Optional[str] = None

    def elapsed(self) -> float:
        end = self.finished_at if self.finished_at else time.time()
        return round(end - self.started_at, 1)

    def result(self) -> Dict[str, Any]:
        from .core import primers as _P
        out = _P.rank(self.primers, self.template, self.specificity, self.products)
        out["organism"] = self.organism
        return out

    def public(self) -> Dict[str, Any]:
        return {
            "job_id": self.job_id,
            "status": self.status,
            "elapsed_seconds": self.elapsed(),
            "warnings": self.warnings,
            "specificity_done": self.specificity is not None,
            "result": self.result(),
            "error": self.error,
        }


_PRIMER_CACHE: Dict[str, PrimerJob] = {}
_PRIMER_BY_ID: Dict[str, PrimerJob] = {}
_PRIMER_LOCK = threading.Lock()


_3P_STRICT_LEN = 5    # strict mode: the 3'-terminal window that must match exactly


def _three_prime_clean(hsp, plen: int, k: int = _3P_STRICT_LEN) -> bool:
    """True if the primer's 3'-terminal ``k`` bases match the subject perfectly
    (no mismatch, no gap). The 3' end is what licenses extension, so this is the
    high-confidence priming test. Reads the tail of the BLAST alignment strings;
    falls back to True if they're unavailable (degrade to lenient)."""
    if hsp.query_end < plen:          # the very 3' base wasn't even aligned
        return False
    match = getattr(hsp, "match", None)
    if not match or len(match) < k:
        return True                   # can't tell → don't over-reject
    if " " in match[-k:]:             # a mismatch column in the last k bases
        return False
    q = getattr(hsp, "query", "") or ""
    s = getattr(hsp, "sbjct", "") or ""
    if "-" in q[-k:] or "-" in s[-k:]:   # a gap in the last k bases
        return False
    return True


def _hsp_to_event(alignment, hsp, primer: Dict[str, Any],
                  strict_3p: bool = False) -> Optional[Dict[str, Any]]:
    """Turn one BLAST HSP into a 'priming event' for in-silico PCR — but only if
    it's 3'-anchored enough to actually extend. Returns None otherwise.

    Direction: the primer's 3' end maps to ``hsp.sbjct_end`` in both strand
    cases; the polymerase runs toward higher coords when sbjct_end > sbjct_start
    ('+') and toward lower coords otherwise ('-')."""
    plen = len(primer["seq"])
    ident = hsp.identities / max(1, hsp.align_length)
    # Must cover the primer's 3' end and be a near-full, high-identity match.
    if ident < 0.90 or hsp.align_length < plen - 3 or hsp.query_end < plen - 1:
        return None
    # Strict mode: also require a perfect 3'-terminal match (cuts borderline
    # sites that share a body but mismatch at the 3' end and wouldn't extend).
    if strict_3p and not _three_prime_clean(hsp, plen):
        return None
    ss, se = hsp.sbjct_start, hsp.sbjct_end
    direction = "+" if se >= ss else "-"
    return {
        "primer_id": primer["id"],
        "name": primer.get("name", primer["id"]),
        "pos5": ss,            # 5' end of the primer on the subject
        "pos3": se,            # 3' end (where extension starts)
        "dir": direction,
        "title": _trim_description(getattr(alignment, "hit_def", ""))[:80],
        "organism": _extract_organism(getattr(alignment, "hit_def", "")),
        "identity_pct": round(100.0 * ident, 1),
    }


def _run_primer_blast(job: PrimerJob) -> None:
    """One blastn-short submission for ALL primers, then in-silico PCR.

    Pairs every forward-oriented priming site with every downstream reverse
    site on the same subject (within MAX_PRODUCT bp) to predict the actual PCR
    products — the same specificity check Primer-BLAST runs, done here so the
    user never leaves the site."""
    from .core import primers as _P
    try:
        from Bio.Blast import NCBIWWW, NCBIXML

        job.status = "scanning"
        fasta = "\n".join(f">{p['id']}\n{p['seq']}" for p in job.primers)
        qblast_kw = dict(
            program="blastn",
            database="nt",
            sequence=fasta,
            megablast=False,          # short, sensitive search
            word_size=7,
            expect=1000,
            nucl_reward=1,
            nucl_penalty=-3,
            hitlist_size=50,
        )
        entrez = _PRIMER_ORGANISMS.get(job.organism, "")
        if entrez:
            qblast_kw["entrez_query"] = entrez
        handle = NCBIWWW.qblast(**qblast_kw)

        spec: Dict[str, Dict[str, Any]] = {}
        events_by_subject: Dict[str, List[Dict[str, Any]]] = {}
        records = list(NCBIXML.parse(handle))
        # Records come back in query order; align them to job.primers.
        for i, record in enumerate(records):
            if i >= len(job.primers):
                break
            p = job.primers[i]
            strong, top = 0, []
            for alignment in record.alignments:
                acc = getattr(alignment, "accession", "") or getattr(alignment, "hit_id", "")
                hit_strong = False
                for hsp in alignment.hsps:
                    ev = _hsp_to_event(alignment, hsp, p, job.three_prime_strict)
                    if ev:
                        events_by_subject.setdefault(acc, []).append(ev)
                        hit_strong = True
                if hit_strong:
                    strong += 1
                    if len(top) < 5:
                        top.append({
                            "title": _trim_description(getattr(alignment, "hit_def", ""))[:80],
                            "organism": _extract_organism(getattr(alignment, "hit_def", "")),
                        })
            spec[p["id"]] = {"strong_offtargets": strong, "top_hits": top}

        # In-silico PCR across ALL primers. rank() collapses these redundant
        # hits into DISTINCT amplicons and splits intended vs off-target, so we
        # just hand it the raw product list here.
        job.products = _P.insilico_pcr(events_by_subject)
        for p in job.primers:
            spec.setdefault(p["id"], {"strong_offtargets": 0, "top_hits": []})
        job.specificity = spec
        job.status = "done"
    except Exception as exc:  # noqa: BLE001
        logger.exception("Primer BLAST failed.")
        job.status = "error"
        job.error = f"{type(exc).__name__}: {exc}"
    finally:
        job.finished_at = time.time()


_SESSION_TTL_SECONDS = 6 * 60 * 60  # 6 h — long enough to cover lunch, calls, etc.


def _new_session(payload: Dict[str, Any]) -> str:
    """Cache an uploaded sequence under a fresh session id and prune stale entries.

    Audit M3: previously the TTL was 30 minutes, which kicked the user out
    if they paused to refine settings, take a call, or step away for lunch.
    Bumping to 6 hours covers a typical workday's "designed a library
    before lunch, came back to download it" pattern without unbounded
    memory growth (sessions only hold the uploaded path + ORF map).
    """
    sid = uuid.uuid4().hex[:12]
    payload["created_at"] = time.time()
    with _SESSIONS_LOCK:
        _SESSIONS[sid] = payload
        cutoff = time.time() - _SESSION_TTL_SECONDS
        stale = [k for k, v in _SESSIONS.items() if v.get("created_at", 0) < cutoff]
        for k in stale:
            _SESSIONS.pop(k, None)
    return sid


def _get_session(sid: str) -> Optional[Dict[str, Any]]:
    with _SESSIONS_LOCK:
        return _SESSIONS.get(sid)


# ----------------------------------------------------------------- Flask app


# ─── Rate limiting (in-process, per-IP sliding window) ────────────────
# A single HF Space container serves everyone, and the heavy endpoints
# (run, identify/BLAST, primer design) are CPU-bound and reachable on the
# anonymous trial — so an unthrottled client can starve every other user or
# run up compute cost. This is a lightweight in-memory limiter: no Redis,
# bounded memory, and fail-open on its own errors (a limiter hiccup must never
# block a legitimate request). Tune via env without a code change.
_RL_LOCK = threading.Lock()
_RL_HITS: "Dict[str, deque]" = {}     # client-key -> deque[monotonic timestamps]
_RL_MAX_KEYS = int(os.environ.get("TURINGDNA_RL_MAX_KEYS", "20000"))  # evict if exceeded
_RL_DISABLED = os.environ.get("TURINGDNA_RL_DISABLED", "") == "1"      # escape hatch

# (max_requests, window_seconds) per path prefix. Longest matching prefix wins;
# the "/api" entry is the catch-all default. Heavy endpoints are tighter.
_RL_RULES = [
    ("/api/run",                       (20,  60)),   # full pipeline — expensive
    ("/api/identify",                  (20,  60)),   # BLAST — expensive
    ("/api/preview",                   (40,  60)),
    ("/api/primers/local-specificity", (20,  60)),   # genome scan — expensive
    ("/api/primers/design",            (30,  60)),
    ("/api/primers/multiplex",         (30,  60)),
    ("/api/primers/analyze",           (40,  60)),
    ("/api/crispr",                    (40,  60)),
    ("/api/plasmid",                   (60,  60)),
    ("/api",                           (120, 60)),   # default for any other API call
]
# Sort longest-prefix-first so the most specific rule matches.
_RL_RULES.sort(key=lambda r: len(r[0]), reverse=True)


def _client_key() -> str:
    """Best-effort client identifier for rate limiting: first hop of
    X-Forwarded-For (HF sits behind a proxy), falling back to remote_addr."""
    fwd = request.headers.get("X-Forwarded-For", "")
    ip = fwd.split(",")[0].strip() if fwd else (request.remote_addr or "")
    return ip or "unknown"


def _rate_limit_rule(path: str):
    """Most-specific matching rule as (prefix, max_requests, window_s), or
    None if the path isn't rate-limited."""
    for prefix, (limit, window) in _RL_RULES:
        if path.startswith(prefix):
            return (prefix, limit, window)
    return None


def _check_rate_limit(path: str, key: str):
    """Returns (limited: bool, retry_after_s: int) over a sliding window.
    The window is per (client, rule) so heavy and cheap endpoints have
    independent budgets — bursting the plasmid editor never locks a user out
    of running a pipeline. Bounded memory; fail-open on any internal error."""
    if _RL_DISABLED:
        return (False, 0)
    matched = _rate_limit_rule(path)
    if matched is None:
        return (False, 0)
    prefix, limit, window = matched
    bucket = f"{key}|{prefix}"
    now = time.monotonic()
    try:
        with _RL_LOCK:
            # Protect against an IP-rotating flood bloating the table — but evict
            # the STALEST buckets (oldest last-hit), not the whole table. A blunt
            # clear() would reset every honest user's window, and a unique-IP
            # flood could exploit that to wipe limits on demand.
            if len(_RL_HITS) > _RL_MAX_KEYS:
                try:
                    victims = sorted(_RL_HITS.items(),
                                     key=lambda kv: (kv[1][-1] if kv[1] else 0.0))
                    for vk, _dq in victims[: max(1, len(_RL_HITS) // 5)]:
                        _RL_HITS.pop(vk, None)
                except Exception:  # noqa: BLE001
                    _RL_HITS.clear()  # last-ditch fallback
            dq = _RL_HITS.get(bucket)
            if dq is None:
                dq = deque()
                _RL_HITS[bucket] = dq
            cutoff = now - window
            while dq and dq[0] < cutoff:
                dq.popleft()
            if len(dq) >= limit:
                retry = int(dq[0] + window - now) + 1
                return (True, max(1, retry))
            dq.append(now)
            return (False, 0)
    except Exception:  # noqa: BLE001 — never block a request on limiter failure
        return (False, 0)


def create_app() -> Flask:
    app = Flask(__name__, static_folder=None)

    # Global request-body cap (defense-in-depth against memory-exhaustion POSTs).
    # 25 MB comfortably covers the largest legitimate payload (CRISPR's 1 Mbp
    # paste ≈ 1 MB, sequence-file uploads) while blocking 100 MB+ floods;
    # oversized requests get a 413 before any handler/parser runs.
    app.config["MAX_CONTENT_LENGTH"] = 25 * 1024 * 1024

    # Wire up auth middleware: before_request hook that parses the
    # Authorization header + signed anon cookie into flask.g.auth.
    # See dee/auth.py for the full design + env-var requirements.
    _auth.init_app(app)

    @app.get("/healthz")
    def _healthz() -> Response:
        """Liveness probe for uptime monitors / the platform supervisor. No auth,
        no rate limit (not under /api/), fast + side-effect-free."""
        return jsonify({"status": "ok"}), 200

    @app.before_request
    def _enforce_rate_limit() -> Optional[Response]:
        # Throttle only API calls — the SPA shell + static assets are cheap and
        # heavily cached. Returning a response here short-circuits the handler.
        path = request.path or ""
        if not path.startswith("/api/"):
            return None
        limited, retry = _check_rate_limit(path, _client_key())
        if not limited:
            return None
        resp = jsonify({
            "error": "Too many requests — please slow down and try again in a moment.",
            "kind": "rate_limited",
        })
        resp.status_code = 429
        resp.headers["Retry-After"] = str(retry)
        return resp

    @app.after_request
    def _security_headers(resp: Response) -> Response:
        # Safe, iframe-compatible hardening. setdefault so we never clobber a
        # header a handler set deliberately (e.g. Cache-Control on assets).
        resp.headers.setdefault("X-Content-Type-Options", "nosniff")
        resp.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
        resp.headers.setdefault(
            "Permissions-Policy",
            "geolocation=(), microphone=(), camera=(), payment=(), usb=()",
        )
        # HSTS — the engine is always HTTPS on hf.space. No includeSubDomains /
        # preload: we don't want to make claims about sibling *.hf.space hosts.
        resp.headers.setdefault("Strict-Transport-Security", "max-age=31536000")
        # Clickjacking defense that RESPECTS the embed: only turingdna.com may
        # frame the engine (the /app wrapper iframes it). An allowlist, not a
        # blanket deny — direct (un-framed) access to the engine is unaffected.
        resp.headers.setdefault(
            "Content-Security-Policy",
            "frame-ancestors 'self' https://turingdna.com https://*.turingdna.com",
        )
        return resp

    @app.get("/")
    def index() -> Response:
        body = _cleaned_html("index.html")   # strip internal comments; source stays commented
        if body is not None:
            return Response(body, mimetype="text/html")
        return send_from_directory(STATIC_DIR, "index.html")

    @app.get("/static/<path:filename>")
    def static_file(filename: str) -> Response:
        # Serve minified JS/CSS (cached) for a clean, compact production surface.
        if "/" not in filename and filename.endswith((".js", ".css")):
            body = _minified_asset(filename)
            if body is not None:
                mime = "application/javascript" if filename.endswith(".js") else "text/css"
                resp = Response(body, mimetype=mime)
                # safe to cache hard: every reference is query-string cache-busted (?v=)
                resp.headers["Cache-Control"] = "public, max-age=31536000"
                return resp
        return send_from_directory(STATIC_DIR, filename)

    @app.post("/api/preview")
    def preview() -> Response:
        """Accept a sequence and report what we found (no scoring yet).

        Accepts EITHER:
          * multipart/form-data with ``file`` field, or
          * application/json with ``{"text": "..."}``.

        If the input parses cleanly as a single CDS or protein, returns its
        metadata. If it's a structured plasmid file or a raw DNA blob with
        multiple ORFs, returns a list of choices in ``cds_options`` so the
        UI can show a picker before kicking off a run.
        """
        try:
            tmp_path, original_name = _materialize_input()
            payload, session_extras = _summarize(tmp_path, original_name)
            sid = _new_session(
                {"path": str(tmp_path), "name": original_name, **session_extras}
            )
            payload["session_id"] = sid
            return jsonify(payload)
        except SequenceValidationError as exc:
            return jsonify(
                {
                    "error": str(exc),
                    "kind": "validation",
                    "nt_position": exc.nt_position,
                    "code": exc.code,
                }
            ), 400
        except Exception:  # noqa: BLE001 — surface anything else as 500.
            logger.exception("Preview failed.")
            # Detail is logged; don't leak the raw exception text to the client
            # (confusing for users, and avoids exposing internals).
            return jsonify({"error": "Couldn't read that input — check it's a valid "
                                     "sequence or file and try again.",
                            "kind": "internal"}), 500

    @app.post("/api/run")
    def start_run() -> Response:
        # Auth-or-quota gate. Anonymous users get one free run; after
        # that this returns a 402 with kind="auth_required" and the
        # frontend pops the sign-up gate. Signed-in users (valid Supabase
        # JWT in Authorization header) bypass entirely.
        gate = _auth.require_auth_or_quota()
        if gate is not None:
            return gate

        body = request.get_json(force=True, silent=True) or {}
        sid = body.get("session_id")
        if not sid:
            return jsonify({"error": "missing session_id"}), 400
        session = _get_session(sid)
        if not session:
            return jsonify({"error": "session expired; re-upload the sequence"}), 410

        try:
            settings = _validate_run_settings(body.get("settings") or {})
        except ValueError as exc:
            return jsonify({"error": str(exc), "kind": "validation"}), 400
        cds_feature = body.get("cds_feature")

        # Audit M7: require explicit CDS selection for multi-CDS uploads.
        # Previously, when the user uploaded an annotated file with >1 CDS
        # feature, the pipeline defaulted to the LONGEST CDS if the user
        # hadn't picked one — sometimes silently swapping in a 5'-flanking
        # ORF instead of the intended target gene. Now: if the session
        # offers a chooser (cds_options) and the user didn't pick one,
        # 400 instead of guessing.
        cds_options = session.get("cds_options") or []
        if cds_options and len(cds_options) > 1 and not cds_feature:
            return jsonify({
                "error": "This input has multiple CDS features. Pick which one "
                         "to design against — auto-selection is disabled to "
                         "avoid silently designing the wrong gene.",
                "kind": "needs_cds_choice",
                "cds_options": cds_options,
            }), 400

        # Capture the signed-in user_id at request time (while flask.g.auth
        # is still populated) so the background pipeline thread can
        # attribute the library to them on completion. None for anon users.
        _auth_ctx = _auth.get_auth()
        job = JobState(
            job_id=uuid.uuid4().hex[:12],
            user_id=_auth_ctx.user_id if not _auth_ctx.anonymous else None,
        )
        _put_job(job)

        # If the session has an ORF map and the user picked an ORF, materialize
        # that ORF's DNA into a fresh temp file and use it as the pipeline input.
        run_path = Path(session["path"])
        run_name = session["name"]
        orf_map = session.get("orfs") or {}
        if orf_map and cds_feature and cds_feature in orf_map:
            tmp = tempfile.NamedTemporaryFile(
                delete=False, suffix=".fasta", mode="w", encoding="utf-8",
                dir=str(STATE_DIR),
            )
            tmp.write(f">{cds_feature}\n{orf_map[cds_feature]}\n")
            tmp.close()
            run_path = Path(tmp.name)
            run_name = f"{Path(run_name).stem}_{cds_feature}"
            # Already extracted a clean ORF — don't re-pass the label downstream.
            cds_feature = None

        thread = threading.Thread(
            target=_run_pipeline,
            args=(job, run_path, run_name, cds_feature, settings),
            daemon=True,
        )
        thread.start()

        # Best-effort: log the run to Supabase public.runs for analytics.
        # Never blocks the response. Stores only hash + length of the
        # sequence (per the privacy policy — no sequence content leaves
        # the engine memory for analytics purposes).
        try:
            with open(run_path, "rb") as _f:
                _sequence_hash = hashlib.sha256(_f.read()).hexdigest()[:32]
            _sequence_length = run_path.stat().st_size
        except OSError:
            _sequence_hash = "unknown"
            _sequence_length = 0
        _auth.log_run_async(
            job_id=job.job_id,
            sequence_hash=_sequence_hash,
            sequence_length=_sequence_length,
            model=settings.get("model"),
            host_organism=settings.get("host"),
        )

        # Lazy cleanup of expired libraries (free-tier TTL, 90d by default).
        # Piggybacks on the user's own /api/run so we don't need pg_cron
        # or an Edge Function — active users keep their storage tidy.
        # Anonymous users skipped (no saved libraries to clean).
        _auth.cleanup_expired_libraries_async(_auth.get_auth().user_id)

        # If the requester is anonymous, bump their signed-cookie counter
        # so subsequent /api/run calls hit the 402 above. Signed-in users
        # are no-ops here.
        resp = jsonify({"job_id": job.job_id})
        return _auth.increment_anon_runs_on_response(resp)

    # ─── Ownership guard (audit C1) ────────────────────────────────────
    # Engine endpoints that take a ``<job_id>`` historically had no
    # ownership check — anyone with the id could read or modify any
    # other user's job. Closes that gap: signed-in users can only touch
    # their own jobs; anonymous jobs (created during a trial) remain
    # accessible to anyone with the id (acceptable for the 5-min trial
    # scope and required so anon polling still works without a JWT).
    def _require_owner_or_403(job: "JobState") -> Optional[Response]:
        if job.user_id is None:
            return None  # anonymous-created job; id-based access only
        auth = _auth.get_auth()
        if auth.anonymous or auth.user_id != job.user_id:
            return jsonify({"error": "not authorized", "kind": "forbidden"}), 403
        return None

    @app.get("/api/status/<job_id>")
    def status(job_id: str) -> Response:
        job = _get_job(job_id)
        if not job:
            return jsonify({"error": "unknown job"}), 404
        denied = _require_owner_or_403(job)
        if denied is not None:
            return denied
        return jsonify(job.public())

    @app.get("/api/result/<job_id>")
    def result(job_id: str) -> Response:
        job = _get_job(job_id)
        if not job:
            return jsonify({"error": "unknown job"}), 404
        denied = _require_owner_or_403(job)
        if denied is not None:
            return denied
        if job.status != "done":
            return jsonify({"error": f"job not done (status={job.status})"}), 409
        # csv_path / desktop_path intentionally omitted (audit H2): they
        # leak the server's filesystem layout. Downloads use the
        # /api/download/<job_id> endpoint, which constructs the path
        # server-side.
        return jsonify(
            {
                "wt_identifier": job.wt_identifier,
                "wt_protein": job.wt_protein,
                "variants": job.variants or [],
                "library_id": job.library_id,
                "settings_used": job.settings_used,
                "started_at": job.started_at,
                "elapsed_seconds": job.elapsed(),
            }
        )

    @app.post("/api/variants/<job_id>/<variant_id>/dna")
    def edit_variant_dna(job_id: str, variant_id: str) -> Response:
        """Persist a user-edited DNA sequence for one variant.

        The frontend POSTs ``{"dna": "ACGT..."}``. We re-derive every
        column from those bytes (translation, mutations diff, PCR metrics,
        restriction-site count), replace ``job.variants[i]`` in place, and
        rewrite the on-disk CSV atomically so subsequent /api/download
        calls return the edited sequence. Returns the full updated row so
        the frontend can replace its local copy without a second fetch.

        Rejects with 400 if the DNA isn't ACGT or isn't a multiple of 3.
        A premature stop is allowed (nonsense/truncation mutation) and simply
        truncates the encoded product.
        """
        job = _get_job(job_id)
        if not job:
            return jsonify({"error": "unknown job"}), 404
        denied = _require_owner_or_403(job)
        if denied is not None:
            return denied
        if job.status != "done":
            return jsonify({"error": f"job not done (status={job.status})"}), 409
        if not job.variants:
            return jsonify({"error": "job has no variants"}), 404

        body = request.get_json(force=True, silent=True) or {}
        edited_dna = (body.get("dna") or "").strip()

        with _edit_lock_for(job_id):
            idx = next(
                (i for i, v in enumerate(job.variants)
                 if v.get("Variant_ID") == variant_id),
                None,
            )
            if idx is None:
                return jsonify({"error": f"unknown variant {variant_id!r}"}), 404
            try:
                new_row = _rederive_variant_row(
                    variant_id=variant_id,
                    edited_dna=edited_dna,
                    wt_protein=job.wt_protein,
                    original_row=job.variants[idx],
                )
            except ValueError as exc:
                return jsonify({"error": str(exc), "kind": "validation"}), 400
            except Exception as exc:  # noqa: BLE001
                logger.exception("Re-derive failed for %s/%s", job_id, variant_id)
                return jsonify({"error": f"{type(exc).__name__}: {exc}"}), 500

            job.variants[idx] = new_row
            try:
                _atomic_rewrite_csv(job)
            except Exception as exc:  # noqa: BLE001
                # The in-memory state was updated but the on-disk CSV
                # rewrite failed. Surface this so the user knows downloads
                # may temporarily diverge from screen state.
                logger.exception("CSV rewrite failed for %s", job_id)
                return jsonify(
                    {"error": f"saved in memory but CSV rewrite failed: {exc}",
                     "row": new_row, "kind": "csv_warning"},
                ), 207

        return jsonify({"row": new_row})

    @app.get("/api/download/<job_id>")
    def download(job_id: str) -> Response:
        job = _get_job(job_id)
        if not job or not job.csv_path:
            return jsonify({"error": "no result available"}), 404
        denied = _require_owner_or_403(job)
        if denied is not None:
            return denied
        fmt = request.args.get("format", "csv").lower()
        stem = Path(job.csv_path).stem
        try:
            data, mimetype, ext = _render_download(job, fmt)
        except ValueError as exc:
            return jsonify({"error": str(exc)}), 400
        return send_file(
            io.BytesIO(data) if isinstance(data, bytes) else data,
            mimetype=mimetype,
            as_attachment=True,
            download_name=f"{stem}.{ext}",
        )

    @app.post("/api/identify")
    def identify_start() -> Response:
        """Kick off an NCBI-BLAST identification for the session's WT protein.

        Returns ``{job_id, cached, hits?}``. If we already ran BLAST on this
        exact sequence we return the prior result inline with cached=true.
        """
        body = request.get_json(force=True, silent=True) or {}
        sid = body.get("session_id")
        if not sid:
            return jsonify({"error": "missing session_id"}), 400
        session = _get_session(sid)
        if not session:
            return jsonify({"error": "session expired"}), 410

        # Audit H1: BLAST consent must be enforced server-side, not just
        # by the consent modal in the UI. The frontend posts
        # `blast_consent: true` only after the user has clicked Continue
        # in the modal; we require it here so anyone calling /api/identify
        # directly (curl, script, etc.) still has to opt in to leak the
        # sequence to NCBI.
        if not body.get("blast_consent"):
            return jsonify({
                "error": (
                    "BLAST consent is required. The wild-type protein "
                    "sequence is sent to ncbi.nlm.nih.gov; please confirm "
                    "in the UI before retrying."
                ),
                "kind": "consent_required",
            }), 403

        cds_feature = body.get("cds_feature")
        # Re-derive the protein to BLAST. For sessions with discovered ORFs
        # the user may have picked a specific one — use that if provided.
        orf_map = session.get("orfs") or {}
        if orf_map and cds_feature and cds_feature in orf_map:
            tmp_path = Path(STATE_DIR / f"blast_input_{uuid.uuid4().hex[:8]}.fa")
            tmp_path.write_text(f">{cds_feature}\n{orf_map[cds_feature]}\n")
            record = parse_input(tmp_path, require_start=False, require_stop=False)
            tmp_path.unlink(missing_ok=True)
        else:
            record = parse_input(
                Path(session["path"]),
                require_start=False,
                require_stop=False,
                cds_feature=cds_feature,
            )
        protein = record.protein
        if not protein:
            return jsonify({"error": "no protein available to identify"}), 400

        seq_hash = _hash_sequence(protein)
        with _BLAST_LOCK:
            cached = _BLAST_CACHE.get(seq_hash)
            if cached and cached.status in {"done", "running", "submitting", "parsing", "pending"}:
                return jsonify(
                    {
                        "job_id": cached.job_id,
                        "cached": cached.status == "done",
                        **cached.public(),
                    }
                )

            job = BlastJob(job_id=uuid.uuid4().hex[:12], seq_hash=seq_hash)
            _BLAST_CACHE[seq_hash] = job
            _BLAST_BY_ID[job.job_id] = job

        threading.Thread(
            target=_run_blast, args=(job, protein), daemon=True
        ).start()
        return jsonify({"job_id": job.job_id, "cached": False, **job.public()})

    @app.get("/api/identify/<job_id>")
    def identify_status(job_id: str) -> Response:
        with _BLAST_LOCK:
            job = _BLAST_BY_ID.get(job_id)
        if not job:
            return jsonify({"error": "unknown job"}), 404
        return jsonify(job.public())

    # ============================================================ PRIMER PICKER
    # Batch-analyse candidate primers: score each against the user's template
    # (on-server, private) and against NCBI nt for off-target specificity
    # (opt-in), then rank and recommend the best. Sign-in gated like CRISPR.

    @app.post("/api/primers/analyze")
    def primers_analyze() -> Response:
        from .core import primers as _P

        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({
                "error": "The Primer Picker requires a free account. Sign in to continue.",
                "kind": "signin_required",
                "signup_url": "https://turingdna.com/signin/?from=primers",
            }), 403

        body = request.get_json(force=True, silent=True) or {}
        primers_text = (body.get("primers") or "").strip()
        template = re.sub(r"\s+", "", (body.get("template") or "")).upper()
        scan_ncbi = bool(body.get("scan_ncbi"))
        strict_3p = bool(body.get("strict_3p"))
        organism = (body.get("organism") or "human").lower()
        if organism not in _PRIMER_ORGANISMS:
            organism = "human"
        if not primers_text:
            return jsonify({"error": "Paste at least one primer."}), 400
        if template and not re.fullmatch(r"[ACGTN]+", template):
            return jsonify({"error": "Template must be DNA (A/C/G/T/N) only."}), 400
        if len(template) > _P.MAX_TEMPLATE:
            return jsonify({"error": (
                f"Template is longer than {_P.MAX_TEMPLATE:,} bp — paste just the "
                "region you're amplifying.")}), 400

        parsed, warnings = _P.parse_primers(primers_text)
        if not parsed:
            return jsonify({"error": "No valid primers found.", "warnings": warnings}), 400

        scored = [_P.score_primer(p, template) for p in parsed]

        if not scan_ncbi:
            return jsonify({
                "status": "done",
                "result": _P.rank(scored, template),
                "warnings": warnings,
            })

        # NCBI scan sends the primers off-server → require explicit consent
        # (same posture as the BLAST identify gate).
        if not body.get("blast_consent"):
            return jsonify({
                "error": ("The specificity scan sends your primers to "
                          "blast.ncbi.nlm.nih.gov; confirm in the UI before retrying."),
                "kind": "consent_required",
            }), 403

        seq_hash = _hash_sequence("|".join(p["seq"] for p in parsed)
                                  + "::" + template + "::" + organism
                                  + ("::strict" if strict_3p else ""))
        with _PRIMER_LOCK:
            cached = _PRIMER_CACHE.get(seq_hash)
            if cached and cached.status in {"done", "scanning", "pending"}:
                return jsonify({
                    "job_id": cached.job_id,
                    "status": cached.status,
                    "result": cached.result(),
                    "warnings": cached.warnings,
                })
            job = PrimerJob(job_id=uuid.uuid4().hex[:12], seq_hash=seq_hash,
                            primers=scored, template=template, organism=organism,
                            three_prime_strict=strict_3p, warnings=warnings)
            _PRIMER_CACHE[seq_hash] = job
            _PRIMER_BY_ID[job.job_id] = job

        threading.Thread(target=_run_primer_blast, args=(job,), daemon=True).start()
        return jsonify({
            "job_id": job.job_id,
            "status": "scanning",
            "result": job.result(),     # template-only ranking while NCBI runs
            "warnings": warnings,
        })

    def _primers_signin_gate():
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"error": "This requires a free account. Sign in to continue.",
                            "kind": "signin_required",
                            "signup_url": "https://turingdna.com/signin/?from=primers"}), 403
        return None

    @app.post("/api/primers/design")
    def primers_design() -> Response:
        """De novo primer design from a template (offline — no NCBI)."""
        from .core import primers as _P
        gate = _primers_signin_gate()
        if gate is not None:
            return gate
        body = request.get_json(force=True, silent=True) or {}
        template = re.sub(r"\s+", "", (body.get("template") or "")).upper()
        if not template:
            return jsonify({"error": "Paste a template to design primers against."}), 400
        if not re.fullmatch(r"[ACGTN]+", template):
            return jsonify({"error": "Template must be DNA (A/C/G/T/N) only."}), 400
        if len(template) > _P.MAX_TEMPLATE:
            return jsonify({"error": f"Template longer than {_P.MAX_TEMPLATE:,} bp — trim to the region of interest."}), 400

        def _oi(v):
            try:
                return int(v)
            except (TypeError, ValueError):
                return None

        def _f(v, d):
            try:
                return float(v)
            except (TypeError, ValueError):
                return d
        s = body.get("settings") if isinstance(body.get("settings"), dict) else {}
        kw = dict(
            product_min=max(40, _oi(s.get("product_min")) or 100),
            product_max=min(_P.MAX_PRODUCT, _oi(s.get("product_max")) or 1000),
            len_min=max(_P.MIN_LEN, _oi(s.get("len_min")) or 18),
            len_max=min(_P.MAX_LEN, _oi(s.get("len_max")) or 27),
            tm_min=_f(s.get("tm_min"), 57.0), tm_max=_f(s.get("tm_max"), 63.0),
            tm_opt=_f(s.get("tm_opt"), 60.0),
            gc_min=_f(s.get("gc_min"), 40.0), gc_max=_f(s.get("gc_max"), 60.0),
            max_pairs=max(1, min(20, _oi(s.get("max_pairs")) or 5)),
        )
        try:
            result = _P.design_primers(template, _oi(body.get("target_start")),
                                       _oi(body.get("target_end")), **kw)
        except Exception:  # noqa: BLE001
            logger.exception("primer design failed")
            return jsonify({"error": "Primer design failed — check the inputs."}), 500
        return jsonify(result), (200 if result.get("ok") else 400)

    @app.post("/api/primers/multiplex")
    def primers_multiplex() -> Response:
        """Multiplex compatibility: pairwise cross-dimers + amplicon size clashes."""
        from .core import primers as _P
        gate = _primers_signin_gate()
        if gate is not None:
            return gate
        body = request.get_json(force=True, silent=True) or {}
        prims = body.get("primers")
        if isinstance(prims, str):
            parsed, _w = _P.parse_primers(prims)
            prims = [{"name": p["name"], "seq": p["seq"]} for p in parsed]
        if not isinstance(prims, list) or not prims:
            return jsonify({"error": "Provide at least two primers."}), 400
        products = body.get("products") if isinstance(body.get("products"), list) else None
        try:
            result = _P.multiplex_check(prims[:_P.MAX_PRIMERS], products=products)
        except Exception:  # noqa: BLE001
            logger.exception("multiplex check failed")
            return jsonify({"error": "Multiplex check failed — check the inputs."}), 500
        return jsonify({"ok": True, **result})

    @app.post("/api/primers/local-specificity")
    def primers_local_spec() -> Response:
        """In-silico PCR against a user-uploaded genome/FASTA — runs entirely on
        our server, so primers never leave (unlike the NCBI scan)."""
        from .core import primers as _P
        gate = _primers_signin_gate()
        if gate is not None:
            return gate
        body = request.get_json(force=True, silent=True) or {}
        prims = body.get("primers")
        if isinstance(prims, str):
            parsed, _w = _P.parse_primers(prims)
            prims = [{"id": p["id"], "name": p["name"], "seq": p["seq"]} for p in parsed]
        if not isinstance(prims, list) or not prims:
            return jsonify({"error": "Provide the primers to check."}), 400
        fasta = body.get("fasta") or body.get("genome") or ""
        if not fasta.strip():
            return jsonify({"error": "Upload a genome or paste a FASTA to scan against."}), 400
        if len(fasta) > 12_000_000:
            return jsonify({"error": "Genome larger than ~12 Mb — for human-scale targets use the NCBI scan instead."}), 413
        try:
            result = _P.local_specificity(prims[:_P.MAX_PRIMERS], fasta)
        except Exception:  # noqa: BLE001
            logger.exception("local specificity failed")
            return jsonify({"error": "Local specificity scan failed — check the inputs."}), 500
        return jsonify(result), (200 if result.get("ok") else 400)

    @app.get("/api/primers/<job_id>")
    def primers_status(job_id: str) -> Response:
        with _PRIMER_LOCK:
            job = _PRIMER_BY_ID.get(job_id)
        if not job:
            return jsonify({"error": "unknown job"}), 404
        return jsonify(job.public())

    # ============================================================ PLASMID STUDIO
    # Import GenBank/FASTA/raw → annotated plasmid model; restriction analysis +
    # digest (1088 REBASE enzymes via Biopython); GenBank/FASTA export; per-user
    # saved-plasmid library. Sign-in gated like CRISPR / the Primer Picker.

    def _plasmid_signin_guard():
        auth = _auth.get_auth()
        if auth.anonymous:
            return None, (jsonify({
                "error": "Plasmid Studio requires a free account. Sign in to continue.",
                "kind": "signin_required",
                "signup_url": "https://turingdna.com/signin/?from=plasmid",
            }), 403)
        return auth, None

    def _validate_plasmid_body(body):
        """Pull (sequence, topology, name, features) from a request body for the
        analysis/export endpoints, with bounds. Returns (data, error_response)."""
        from .core import plasmid as _PL
        seq = re.sub(r"\s+", "", (body.get("sequence") or "")).upper()
        if not seq:
            return None, (jsonify({"error": "missing 'sequence'"}), 400)
        if len(seq) > _PL.MAX_LEN:
            return None, (jsonify({"error": f"Sequence longer than {_PL.MAX_LEN:,} bp."}), 400)
        if not re.fullmatch(r"[ACGTNRYSWKMBDHV]+", seq):
            return None, (jsonify({"error": "Sequence must be DNA."}), 400)
        topology = "linear" if (body.get("topology") == "linear") else "circular"
        # Sanitize features: clamp coords, force colors to safe hex, cap count.
        # Defends export/save + the SVG/style rendering from malformed or
        # injection-laden feature dicts (audit hardening).
        return {"sequence": seq, "topology": topology,
                "name": str(body.get("name", "") or "plasmid")[:120],
                "features": _PL.sanitize_features(body.get("features"), len(seq))}, None

    @app.post("/api/plasmid/import")
    def plasmid_import() -> Response:
        from .core import plasmid as _PL
        _auth_ctx, denied = _plasmid_signin_guard()
        if denied:
            return denied
        body = request.get_json(force=True, silent=True) or {}
        topology = body.get("topology") if body.get("topology") in ("circular", "linear") else None
        b64 = body.get("b64")
        try:
            if b64:
                # Binary upload (e.g. SnapGene .dna) base64-encoded in the JSON
                # body. Bound the decoded size BEFORE handing to the parser.
                import base64
                import binascii
                if not isinstance(b64, str) or len(b64) > 4 * (_PL.MAX_INPUT_TEXT // 3 + 4):
                    return jsonify({"error": "File too large."}), 400
                try:
                    raw = base64.b64decode(b64, validate=True)
                except (binascii.Error, ValueError):
                    return jsonify({"error": "Could not decode the uploaded file."}), 400
                filename = str(body.get("filename") or "")[:200]
                plasmid = _PL.parse_binary(raw, filename=filename, topology=topology)
            else:
                text = body.get("text") or ""
                plasmid = _PL.parse_plasmid(text, topology=topology)
        except ValueError as exc:
            return jsonify({"error": str(exc)}), 400
        if body.get("annotate", True):
            _PL.auto_annotate(plasmid)
        return jsonify({"ok": True, "plasmid": plasmid})

    @app.post("/api/plasmid/restriction")
    def plasmid_restriction() -> Response:
        from .core import plasmid as _PL
        _auth_ctx, denied = _plasmid_signin_guard()
        if denied:
            return denied
        body = request.get_json(force=True, silent=True) or {}
        data, err = _validate_plasmid_body(body)
        if err:
            return err
        enzymes = body.get("enzymes") if isinstance(body.get("enzymes"), list) else None
        enzymes = [str(e)[:24] for e in enzymes][:120] if enzymes else None
        return jsonify({"ok": True,
                        "analysis": _PL.restriction_analysis(data["sequence"], data["topology"], enzymes)})

    @app.post("/api/plasmid/digest")
    def plasmid_digest() -> Response:
        from .core import plasmid as _PL
        _auth_ctx, denied = _plasmid_signin_guard()
        if denied:
            return denied
        body = request.get_json(force=True, silent=True) or {}
        data, err = _validate_plasmid_body(body)
        if err:
            return err
        enzymes = body.get("enzymes") if isinstance(body.get("enzymes"), list) else []
        enzymes = [str(e)[:24] for e in enzymes][:20]
        if not enzymes:
            return jsonify({"error": "Pick at least one enzyme to digest with."}), 400
        return jsonify({"ok": True,
                        "digest": _PL.digest(data["sequence"], data["topology"], enzymes)})

    @app.post("/api/plasmid/export")
    def plasmid_export() -> Response:
        from .core import plasmid as _PL
        _auth_ctx, denied = _plasmid_signin_guard()
        if denied:
            return denied
        body = request.get_json(force=True, silent=True) or {}
        data, err = _validate_plasmid_body(body)
        if err:
            return err
        fmt = (body.get("format") or "genbank").lower()
        plasmid = {"name": data["name"], "sequence": data["sequence"],
                   "topology": data["topology"], "length": len(data["sequence"]),
                   "features": data["features"]}
        stem = re.sub(r"[^A-Za-z0-9_.-]", "_", data["name"]) or "plasmid"
        try:
            if fmt in ("fasta", "fa"):
                payload, mime, ext = _PL.build_fasta(plasmid), "text/x-fasta", "fasta"
            else:
                payload, mime, ext = _PL.build_genbank(plasmid), "chemical/x-genbank", "gb"
        except Exception as exc:  # noqa: BLE001
            return jsonify({"error": f"Export failed: {exc}"}), 500
        return send_file(io.BytesIO(payload.encode("utf-8")), mimetype=mime,
                         as_attachment=True, download_name=f"{stem}.{ext}")

    @app.post("/api/align")
    def align_sequences() -> Response:
        """Pairwise alignment (global/local) of two sequences. Stateless utility,
        no sign-in needed; bounded by align()'s size cap + the global rate limit."""
        from .core import align as _AL
        body = request.get_json(force=True, silent=True) or {}
        a, b = body.get("a") or "", body.get("b") or ""
        mode = "local" if body.get("mode") == "local" else "global"
        try:
            result = _AL.align(a, b, mode=mode)
        except ValueError as exc:
            return jsonify({"error": str(exc)}), 400
        except Exception:  # noqa: BLE001
            logger.exception("alignment failed")
            return jsonify({"error": "Alignment failed — check the two sequences."}), 500
        return jsonify({"ok": True, **result})

    @app.post("/api/plasmid/save")
    def plasmid_save() -> Response:
        auth, denied = _plasmid_signin_guard()
        if denied:
            return denied
        body = request.get_json(force=True, silent=True) or {}
        data, err = _validate_plasmid_body(body)
        if err:
            return err
        try:
            gc = float(body.get("gc")) if body.get("gc") is not None else None
        except (TypeError, ValueError):
            gc = None
        result = _auth.save_plasmid(
            auth.user_id,
            name=data["name"], topology=data["topology"],
            length=len(data["sequence"]), gc=gc,
            source=str(body.get("source", "") or "")[:16] or None,
            sequence=data["sequence"], features=data["features"],
        )
        _auth.cleanup_expired_plasmids_async(auth.user_id)
        return jsonify(result), (200 if result.get("ok") else 502)

    @app.get("/api/plasmid/library")
    def plasmid_library() -> Response:
        auth, denied = _plasmid_signin_guard()
        if denied:
            return denied
        return jsonify({"ok": True, "plasmids": _auth.list_plasmids(auth.user_id)})

    @app.get("/api/plasmid/library/<plasmid_id>")
    def plasmid_library_get(plasmid_id: str) -> Response:
        auth, denied = _plasmid_signin_guard()
        if denied:
            return denied
        p = _auth.get_plasmid(auth.user_id, plasmid_id)
        if p is None:
            return jsonify({"ok": False, "error": "Plasmid not found."}), 404
        return jsonify({"ok": True, "plasmid": p})

    @app.delete("/api/plasmid/library/<plasmid_id>")
    def plasmid_library_delete(plasmid_id: str) -> Response:
        auth, denied = _plasmid_signin_guard()
        if denied:
            return denied
        return jsonify(_auth.delete_plasmid(auth.user_id, plasmid_id))

    @app.post("/api/plasmid/clone")
    def plasmid_clone() -> Response:
        """Cloning simulation: Gibson / Golden Gate / restriction. Returns the
        assembled construct in the standard plasmid-ish shape."""
        from .core import cloning as _CL
        _auth_ctx, denied = _plasmid_signin_guard()
        if denied:
            return denied
        body = request.get_json(force=True, silent=True) or {}
        method = (body.get("method") or "gibson").lower()
        try:
            if method == "gibson":
                frags = body.get("fragments")
                if not isinstance(frags, list):
                    return jsonify({"error": "Provide a list of fragments."}), 400
                res = _CL.gibson(frags, circular=bool(body.get("circular", True)))
            elif method == "golden_gate":
                frags = body.get("fragments")
                if not isinstance(frags, list):
                    return jsonify({"error": "Provide a list of parts."}), 400
                res = _CL.golden_gate(frags, enzyme=str(body.get("enzyme", "BsaI"))[:12])
            elif method == "restriction":
                res = _CL.restriction_clone(
                    str(body.get("vector", "")), str(body.get("insert", "")),
                    str(body.get("enzyme", ""))[:24],
                    vector_topology="linear" if body.get("vector_topology") == "linear" else "circular")
            else:
                return jsonify({"error": f"Unknown method: {method}."}), 400
        except Exception as exc:  # noqa: BLE001
            logger.exception("clone failed")
            return jsonify({"error": f"Assembly failed: {exc}"}), 500
        if not res.get("ok"):
            return jsonify(res), 200      # business-level failure (bad overlaps etc.)
        return jsonify(res)

    # ================================================================= CRISPR
    # Cas9 gRNA design for knockout applications. MVP scope: pasted DNA
    # → ranked SpCas9 guides with Doench-style heuristic on-target
    # scoring. Sign-in gated (free for any account); anonymous users
    # get a 403 with a sign-in CTA so the frontend can route them to
    # /signin instead of the engine's trial gate. Whole-genome off-target,
    # Cas12a, base editors, and HDR donor design are deferred — see
    # dee/core/crispr.py module docstring for the full scope ladder.

    @app.post("/api/crispr/design")
    def crispr_design() -> Response:
        # Sign-in gate. Distinct from the trial timer (which is per-anon-
        # session): CRISPR requires an account, no anonymous use. The
        # 403 carries kind="signin_required" so static auth.js can route
        # the parent window to /signin instead of showing the trial modal.
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({
                "error": (
                    "CRISPR design requires a free account. "
                    "Sign in or create one to keep going."
                ),
                "kind": "signin_required",
                "signup_url": "https://turingdna.com/signin/?from=crispr",
            }), 403

        body = request.get_json(force=True, silent=True) or {}
        seq = (body.get("sequence") or "").strip()
        if not seq:
            return jsonify({"error": "missing 'sequence'"}), 400

        # Bound the input so a 10 MB paste doesn't tie up the worker.
        # 1 Mbp covers any reasonable cloning-scale region (largest
        # human genes are ~2.4 Mbp, but at that scale you'd use a
        # whole-genome tool, not a paste box).
        if len(seq) > 1_000_000:
            return jsonify({
                "error": (
                    "Sequence too long. Cap is 1 Mbp — paste just the "
                    "gene / region you're editing, not a whole "
                    "chromosome."
                ),
                "kind": "input_too_large",
            }), 400

        try:
            max_results = int(body.get("max_results", 50))
        except (TypeError, ValueError):
            max_results = 50
        max_results = max(1, min(500, max_results))  # bound

        try:
            min_score = float(body.get("min_score", 0.0))
        except (TypeError, ValueError):
            min_score = 0.0
        min_score = max(0.0, min(1.0, min_score))

        # Enzyme picker — Phase 1 supports SpCas9 and Cas12a. Default cas9
        # for backward compat with the existing frontend (which sends no
        # `enzyme` field on the current build).
        enzyme = str(body.get("enzyme", "cas9")).lower()
        if enzyme not in ("cas9", "cas12a"):
            enzyme = "cas9"

        # Phase 2B-1: optional genome off-target + Ensembl exon context.
        # Both are opt-in; default empty means "skip" so existing
        # frontends keep working unchanged.
        target_organism = str(body.get("target_organism", "")).lower().strip()
        gene_symbol     = str(body.get("gene_symbol", "")).strip()
        # Light input validation — anything else gets ignored.
        if target_organism not in ("", "ecoli", "human", "mouse"):
            target_organism = ""
        if len(gene_symbol) > 32 or not re.match(r"^[A-Za-z0-9._-]*$", gene_symbol):
            gene_symbol = ""

        # Phase 2C-1: optional cloning vector for per-guide oligo gen.
        from dee.core import crispr_cloning as _cc
        vector_id = str(body.get("vector_id", "")).lower().strip()
        if vector_id and vector_id not in _cc.CRISPR_VECTORS:
            vector_id = ""

        # Phase 3 (M1): base-editing mode. Defaults to knockout so the
        # existing frontend (which sends no `mode`) is unaffected.
        from dee.core import base_editor as _be
        mode = str(body.get("mode", "knockout")).lower()
        if mode not in ("knockout", "base_edit"):
            mode = "knockout"
        base_editor = str(body.get("base_editor", "")).lower().strip()
        if base_editor and _be.get_base_editor(base_editor) is None:
            base_editor = ""

        try:
            guides = _find_crispr_guides(
                seq, enzyme=enzyme, max_results=max_results, min_score=min_score,
                target_organism=target_organism, gene_symbol=gene_symbol,
                vector_id=vector_id, mode=mode, base_editor=base_editor,
            )
        except ValueError as exc:
            return jsonify({"error": str(exc), "kind": "validation"}), 400
        except Exception as exc:  # noqa: BLE001
            logger.exception("CRISPR design failed.")
            return jsonify({
                "error": f"{type(exc).__name__}: {exc}",
                "kind": "internal",
            }), 500

        # Flatten dataclasses into plain dicts for JSON. New Phase 1
        # fields (composite_score, cfd_max_offtarget, offtarget_count,
        # ko_efficacy, ko_reasoning, enzyme) get exposed so the frontend
        # table can render them.
        #
        # Phase 2D: genome_index_status surfaces whether the off-target
        # search actually ran. "ready" = index hit, hits are real.
        # "building" = first-time index build is in flight, guides
        # returned without genome data; the frontend shows a banner
        # telling the user to refresh in 2 min. "n/a" = no organism
        # requested.
        from dee.core import offtarget as _ot_status
        genome_index_status = _ot_status.index_status(target_organism)
        from dee.core import outcomes as _O
        guide_dicts = [
                {
                    "rank":              g.rank,
                    "enzyme":            g.enzyme,
                    "strand":            g.strand,
                    "position":          g.position,
                    "spacer":            g.spacer,
                    "pam":               g.pam,
                    "target_context":    g.target_context,
                    "composite_score":   g.composite_score,
                    "on_target_score":   g.on_target_score,
                    "cfd_max_offtarget": g.cfd_max_offtarget,
                    "offtarget_count":   g.offtarget_count,
                    "ko_efficacy":       g.ko_efficacy,
                    "ko_reasoning":      g.ko_reasoning,
                    "gc_pct":            g.gc_pct,
                    "flag_high_gc":      g.flag_high_gc,
                    "flag_low_gc":       g.flag_low_gc,
                    "flag_polyT":        g.flag_polyT,
                    "notes":             g.notes,
                    # Phase 2A — indel prediction + base editor
                    "top_indel_label":   g.top_indel_label,
                    "frameshift_pct":    g.frameshift_pct,
                    "top_dominance_pct": g.top_dominance_pct,
                    "predicted_indels":  g.predicted_indels,   # list[[lbl, freq]]
                    "be_cbe_positions":  g.be_cbe_positions,
                    "be_abe_positions":  g.be_abe_positions,
                    "be_summary":        g.be_summary,
                    # Phase 2B-1 — genome off-target + exon context
                    "genome_organism":           g.genome_organism,
                    "genome_offtarget_count":    g.genome_offtarget_count,
                    "genome_offtarget_max_cfd":  g.genome_offtarget_max_cfd,
                    "genome_offtarget_top_loc":  g.genome_offtarget_top_loc,
                    "exon_number":               g.exon_number,
                    "distance_to_splice":        g.distance_to_splice,
                    "in_nmd_zone":               g.in_nmd_zone,
                    "exon_context_summary":      g.exon_context_summary,
                    # Phase 2C-1 — cloning oligos
                    "cloning_vector_id":   g.cloning_vector_id,
                    "cloning_vector_name": g.cloning_vector_name,
                    "cloning_enzyme":      g.cloning_enzyme,
                    "cloning_addgene_id":  g.cloning_addgene_id,
                    "sense_oligo":         g.sense_oligo,
                    "antisense_oligo":     g.antisense_oligo,
                    # Phase 3 (M1) — base editing
                    "be_editor":           g.be_editor,
                    "be_editability":      g.be_editability,
                    "be_has_bystander":    g.be_has_bystander,
                    "be_edits":            g.be_edits,         # [[pos, from, to, act], …]
                    "be_outcome_label":    g.be_outcome_label,
                    "be_aa_change":        g.be_aa_change,
                    "be_creates_stop":     g.be_creates_stop,
                    # Phase 3 (M5) — structure viewer
                    "cut_residue":         g.cut_residue,
                }
                for g in guides
        ]
        # Cross-user CRISPR on-target prior → fold into scores + re-rank. No-op
        # until public.outcome_priors has a 'crispr' aggregate (post effective date).
        guide_dicts = _O.calibrate_crispr_guides(guide_dicts, _load_tool_prior("crispr"))
        return jsonify({
            "input_length":        len(seq.strip()),
            "n_guides":            len(guide_dicts),
            "enzyme":              enzyme,
            "mode":                mode,
            "base_editor":         base_editor or (_be.DEFAULT_BASE_EDITOR if mode == "base_edit" else ""),
            "genome_organism":     target_organism,
            "genome_index_status": genome_index_status,
            "calibrated":          any("calibration" in g for g in guide_dicts),
            "guides":              guide_dicts,
        })

    @app.get("/api/crispr/vectors")
    def crispr_vectors() -> Response:
        """List the curated CRISPR expression vectors the engine supports.
        Used by the frontend to populate the vector dropdown above the
        results table. Filterable by ?enzyme=cas9|cas12a."""
        from dee.core import crispr_cloning as _cc
        enzyme = request.args.get("enzyme", "").strip().lower()
        if enzyme not in ("", "cas9", "cas12a"):
            enzyme = ""
        vectors = _cc.list_vectors(enzyme)
        return jsonify({
            "default":  _cc.default_vector_for(enzyme or "cas9"),
            "vendors":  _cc.VENDORS,
            "vectors": [
                {
                    "id":          v.id,
                    "name":        v.name,
                    "addgene_id":  v.addgene_id,
                    "enzyme":      v.enzyme,
                    "nuclease":    v.nuclease,
                    "selection":   v.selection,
                    "description": v.description,
                }
                for v in vectors
            ],
        })

    @app.get("/api/crispr/base-editors")
    def crispr_base_editors() -> Response:
        """List the base editors the engine supports, for the base-edit
        mode dropdown. Filterable by ?kind=CBE|ABE."""
        from dee.core import base_editor as _be
        kind = request.args.get("kind", "").strip().upper()
        if kind not in ("", "CBE", "ABE"):
            kind = ""
        editors = _be.list_base_editors(kind)
        return jsonify({
            "default": _be.DEFAULT_BASE_EDITOR,
            "editors": [
                {
                    "id":          e.id,
                    "name":        e.name,
                    "kind":        e.kind,
                    "target_base": e.target_base,
                    "result_base": e.result_base,
                    "window":      list(e.window),
                    "citation":    e.citation,
                    "note":        e.note,
                }
                for e in editors
            ],
        })

    @app.post("/api/crispr/structure")
    def crispr_structure() -> Response:
        """Resolve a gene → UniProt + AlphaFold model URL for the structure
        viewer (Phase 3, M5). Body: {organism, gene_symbol}. Sign-in gated.
        Only (organism, gene_symbol) leaves the Space."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        body = request.get_json(force=True, silent=True) or {}
        organism = str(body.get("organism", "")).lower().strip()
        gene_symbol = str(body.get("gene_symbol", "")).strip()
        if organism not in ("human", "mouse"):
            return jsonify({"ok": False,
                            "error": "Structure view is available for Human / Mouse genes."}), 422
        if not gene_symbol or len(gene_symbol) > 32 or not re.match(r"^[A-Za-z0-9._-]+$", gene_symbol):
            return jsonify({"ok": False, "error": "Provide a valid gene symbol."}), 422
        from dee.core import resolve as _resolve
        try:
            result = _resolve.resolve_uniprot(organism, gene_symbol)
        except Exception as exc:  # noqa: BLE001
            logger.exception("CRISPR structure resolve failed.")
            return jsonify({"ok": False, "error": f"{type(exc).__name__}: {exc}"}), 500
        return jsonify(result), (200 if result.get("ok") else 422)

    @app.post("/api/crispr/resolve")
    def crispr_resolve() -> Response:
        """Paste-anything resolver (Phase 3, M2). Body: {text, organism}.
        Resolves a gene symbol / accession / raw sequence to an editable
        DNA sequence + a human label. Same sign-in gate as /design.
        Privacy: only (organism, identifier) leaves the Space for lookups;
        a raw sequence makes no outbound call."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({
                "ok": False,
                "error": "Sign in or create a free account to keep going.",
                "kind": "signin_required",
                "signup_url": "https://turingdna.com/signin/?from=crispr",
            }), 403

        body = request.get_json(force=True, silent=True) or {}
        text = (body.get("text") or "").strip()
        if not text:
            return jsonify({"ok": False, "error": "missing 'text'"}), 400
        # Bound input: a sequence paste can be up to 1 Mbp; an identifier is
        # tiny. Cap defensively so a giant blob can't tie up the resolver.
        if len(text) > 1_000_000:
            return jsonify({"ok": False, "error": "Input too long (1 Mbp cap)."}), 400
        organism = str(body.get("organism", "")).lower().strip()
        if organism not in ("", "ecoli", "human", "mouse"):
            organism = ""

        from dee.core import resolve as _resolve
        try:
            result = _resolve.resolve_target(text, organism=organism)
        except Exception as exc:  # noqa: BLE001
            logger.exception("CRISPR resolve failed.")
            return jsonify({"ok": False, "error": f"{type(exc).__name__}: {exc}"}), 500
        return jsonify(result), (200 if result.get("ok") else 422)

    @app.post("/api/crispr/ip_radar")
    def crispr_ip_radar() -> Response:
        """Live Collision IP Radar (v1, literature via Europe PMC). Opt-in,
        metadata-first: only the gene symbol, validated point-mutation set, and
        the 20-mer guide spacer are accepted — never a full novel sequence.
        Sign-in gated. Non-critical: any failure returns ok:False with 200 so
        the UI degrades quietly instead of erroring."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        body = request.get_json(force=True, silent=True) or {}

        gene_symbol = str(body.get("gene_symbol", "")).strip()
        if len(gene_symbol) > 32 or not re.match(r"^[A-Za-z0-9._-]*$", gene_symbol):
            gene_symbol = ""
        spacer = str(body.get("spacer", "")).strip().upper()[:25]
        if not re.match(r"^[ACGT]*$", spacer):
            spacer = ""
        raw_muts = body.get("mutations")
        mutations = []
        if isinstance(raw_muts, list):
            for m in raw_muts[:8]:
                m = str(m).strip()
                # Only accept HGVS-ish point mutations (e.g. T47A) — refuse
                # arbitrary strings so the field can't smuggle a raw sequence.
                if re.match(r"^[A-Za-z]\d{1,5}[A-Za-z*]$", m):
                    mutations.append(m)
        mode = str(body.get("mode", "knockout")).lower()

        from dee.core import ip_radar as _ipr
        try:
            result = _ipr.check_literature(
                gene_symbol=gene_symbol, mutations=mutations,
                spacer=spacer, mode=mode,
            )
            # Patent layer (free PatentsView, gene-level "related patents").
            # Off unless PATENTSVIEW_API_KEY is set; never blocks literature.
            try:
                pat = _ipr.check_patents(gene_symbol=gene_symbol)
                result["patents"] = pat.get("patents", [])
                result["patents_available"] = pat.get("available", False)
            except Exception:  # noqa: BLE001
                result["patents"] = []
                result["patents_available"] = False
        except Exception:  # noqa: BLE001
            logger.exception("IP radar failed.")
            return jsonify({"ok": False, "error": "radar_unavailable"}), 200
        return jsonify(result)

    # ─── Phase 3 (M4): save & revisit designs ─────────────────────────
    @app.post("/api/crispr/save")
    def crispr_save() -> Response:
        """Save the current guide set to the signed-in user's library."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required",
                            "signup_url": "https://turingdna.com/signin/?from=crispr"}), 403
        body = request.get_json(force=True, silent=True) or {}
        guides = body.get("guides")
        if not isinstance(guides, list) or not guides:
            return jsonify({"ok": False, "error": "Nothing to save — run a design first."}), 400
        mode = str(body.get("mode", "knockout")).lower()
        if mode not in ("knockout", "base_edit"):
            mode = "knockout"
        try:
            input_length = int(body.get("input_length") or 0)
        except (TypeError, ValueError):
            input_length = 0
        result = _auth.save_crispr_design(
            auth.user_id,
            label=str(body.get("label", ""))[:120],
            mode=mode,
            enzyme=str(body.get("enzyme", ""))[:16] or None,
            base_editor=str(body.get("base_editor", ""))[:32] or None,
            organism=str(body.get("organism", ""))[:16] or None,
            gene_symbol=str(body.get("gene_symbol", ""))[:32] or None,
            input_length=input_length,
            guides=guides,
        )
        _auth.cleanup_expired_crispr_designs_async(auth.user_id)  # lazy sweep
        return jsonify(result), (200 if result.get("ok") else 502)

    @app.get("/api/crispr/designs")
    def crispr_designs_list() -> Response:
        """The signed-in user's saved designs (metadata only)."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        return jsonify({"ok": True, "designs": _auth.list_crispr_designs(auth.user_id)})

    @app.get("/api/crispr/designs/<design_id>")
    def crispr_design_get(design_id: str) -> Response:
        """One saved design incl. guides (owner-only, server-enforced)."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        design = _auth.get_crispr_design(auth.user_id, design_id)
        if design is None:
            return jsonify({"ok": False, "error": "Design not found."}), 404
        return jsonify({"ok": True, "design": design})

    # ── Primer Analysis: saved sets (unified "My designs" hub) ──
    # Static routes win over /api/primers/<job_id> in Werkzeug, so no clash.
    @app.post("/api/primers/save")
    def primers_save() -> Response:
        """Save the current primer analysis to the signed-in user's library."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required",
                            "signup_url": "https://turingdna.com/signin/?from=primers"}), 403
        body = request.get_json(force=True, silent=True) or {}
        result_obj = body.get("result")
        if not isinstance(result_obj, dict) or not result_obj.get("primers"):
            return jsonify({"ok": False, "error": "Nothing to save — analyse some primers first."}), 400
        try:
            template_len = int(body.get("template_len") or 0)
        except (TypeError, ValueError):
            template_len = 0
        try:
            n_primers = int(body.get("n_primers") or len(result_obj.get("primers") or []))
        except (TypeError, ValueError):
            n_primers = len(result_obj.get("primers") or [])
        result = _auth.save_primer_analysis(
            auth.user_id,
            label=str(body.get("label", ""))[:120],
            organism=str(body.get("organism", ""))[:32] or None,
            template_len=template_len,
            n_primers=n_primers,
            result=result_obj,
        )
        _auth.cleanup_expired_primer_analyses_async(auth.user_id)  # lazy sweep
        return jsonify(result), (200 if result.get("ok") else 502)

    @app.get("/api/primers/analyses")
    def primers_analyses_list() -> Response:
        """The signed-in user's saved primer sets (metadata only)."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        return jsonify({"ok": True, "analyses": _auth.list_primer_analyses(auth.user_id)})

    @app.get("/api/primers/analyses/<analysis_id>")
    def primers_analysis_get(analysis_id: str) -> Response:
        """One saved primer set incl. result (owner-only, server-enforced)."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        analysis = _auth.get_primer_analysis(auth.user_id, analysis_id)
        if analysis is None:
            return jsonify({"ok": False, "error": "Primer set not found."}), 404
        return jsonify({"ok": True, "analysis": analysis})

    @app.delete("/api/primers/analyses/<analysis_id>")
    def primers_analysis_delete(analysis_id: str) -> Response:
        """Delete one saved primer set (owner-only)."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        return jsonify(_auth.delete_primer_analysis(auth.user_id, analysis_id))

    @app.post("/api/primers/export")
    def primers_export() -> Response:
        """CSV / XLSX of a primer analysis the client already holds — so
        researchers can take the ranked table to the bench. The client posts
        the analyze result back (no re-run); we flatten + stream it. Sign-in
        gated like the rest of Primer Analysis."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"error": "signin_required", "kind": "signin_required"}), 403
        body = request.get_json(force=True, silent=True) or {}
        result = body.get("result")
        primers = result.get("primers") if isinstance(result, dict) else None
        if not isinstance(primers, list) or not primers:
            return jsonify({"error": "Nothing to export — analyse some primers first."}), 400
        primers = primers[:1000]   # bound the export size
        fmt = str(body.get("format", "xlsx")).lower().strip()
        if fmt not in ("csv", "xlsx"):
            fmt = "xlsx"

        header = ["Rank", "Name", "Sequence", "Length (nt)", "GC %", "Tm (C)",
                  "3' G/C clamp", "Sites on template", "Off-target products", "Fitness (0-1)"]

        def _row(i, p):
            if not isinstance(p, dict):
                p = {}
            ot = p.get("on_template") if isinstance(p.get("on_template"), dict) else {}
            sp = p.get("specificity") if isinstance(p.get("specificity"), dict) else {}
            offt = sp.get("offtarget_products")
            if offt is None:
                offt = sp.get("strong_offtargets")
            fit = p.get("fitness")
            return [
                i + 1,
                str(p.get("name", "") or ""),
                str(p.get("seq", "") or ""),
                p.get("length", ""),
                p.get("gc", ""),
                p.get("tm", ""),
                "yes" if p.get("gc_clamp") else "no",
                ot.get("n_strong_sites", "") if ot else "",
                offt if offt is not None else "",
                round(fit, 3) if isinstance(fit, (int, float)) else "",
            ]

        rows = [header] + [_row(i, p) for i, p in enumerate(primers)]

        if fmt == "csv":
            import csv as _csv
            from io import StringIO as _SIO
            from flask import make_response as _mr
            sio = _SIO()
            w = _csv.writer(sio, quoting=_csv.QUOTE_MINIMAL, lineterminator="\r\n")
            for r in rows:
                w.writerow(r)
            data = ("" + sio.getvalue()).encode("utf-8")   # BOM → Excel detects UTF-8
            resp = _mr(data)
            resp.headers["Content-Type"] = "text/csv; charset=utf-8"
            resp.headers["Content-Disposition"] = 'attachment; filename="turingdna_primers.csv"'
            return resp

        from io import BytesIO as _BIO
        from openpyxl import Workbook as _WB
        from openpyxl.styles import Font as _Font
        wb = _WB()
        ws = wb.active
        ws.title = "Primers"
        for r in rows:
            ws.append(r)
        for cell in ws[1]:
            cell.font = _Font(bold=True)
        buf = _BIO()
        wb.save(buf)
        buf.seek(0)
        return send_file(
            buf,
            mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            as_attachment=True,
            download_name="turingdna_primers.xlsx",
        )

    # ── Directed-Evolution libraries: per-user list + signed CSV download ──
    # Per-user, RLS-safe replacement for the shared-filesystem /api/library
    # removed in audit C2 — reads public.libraries filtered by the JWT user.
    @app.get("/api/library")
    def library_list() -> Response:
        """The signed-in user's saved DE libraries (metadata only)."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        return jsonify({"ok": True, "libraries": _auth.list_libraries(auth.user_id)})

    @app.get("/api/library/<library_id>/download")
    def library_download(library_id: str) -> Response:
        """Return a short-lived signed URL for the library CSV (owner-only).
        The browser fetches the CSV straight from Storage; the service key
        never leaves the server."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        url = _auth.library_csv_url(auth.user_id, library_id)
        if not url:
            return jsonify({"ok": False, "error": "Library not found."}), 404
        return jsonify({"ok": True, "url": url})

    # ── DE learning flywheel: log outcomes + active-learning round 2 ──
    @app.post("/api/de/outcomes")
    def de_outcomes_save() -> Response:
        """Save this user's measured variants for a saved DE library."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        body = request.get_json(force=True, silent=True) or {}
        library_id = str(body.get("library_id", "")).strip()
        outcomes = body.get("outcomes")
        if not isinstance(outcomes, list):
            return jsonify({"ok": False, "error": "No outcomes provided."}), 400
        result = _auth.save_de_outcomes(auth.user_id, library_id, outcomes)
        _auth.cleanup_expired_de_outcomes_async(auth.user_id)  # lazy sweep
        return jsonify(result), (200 if result.get("ok") else 502)

    @app.get("/api/de/outcomes/<library_id>")
    def de_outcomes_list(library_id: str) -> Response:
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required"}), 403
        return jsonify({"ok": True, "outcomes": _auth.list_de_outcomes(auth.user_id, library_id)})

    @app.post("/api/de/round2")
    def de_round2() -> Response:
        """Propose a round-2 library learned from this user's logged outcomes."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required",
                            "kind": "signin_required",
                            "signup_url": "https://turingdna.com/signin/?from=de"}), 403
        body = request.get_json(force=True, silent=True) or {}
        library_id = str(body.get("library_id", "")).strip()
        wt_protein = re.sub(r"\s+", "", str(body.get("wt_protein", ""))).upper()
        if not wt_protein or not re.match(r"^[ACDEFGHIKLMNPQRSTVWY*]+$", wt_protein):
            return jsonify({"ok": False, "error": "Missing or non-standard wild-type protein."}), 400
        if len(wt_protein) > _DE_ROUND2_MAX_AA:
            return jsonify({"ok": False, "error":
                f"Round 2 runs in real time for proteins up to {_DE_ROUND2_MAX_AA} aa on the "
                "free tier — yours is longer."}), 400

        # Outcomes: DB is authoritative; allow inline only as a fallback.
        rows = _auth.list_de_outcomes(auth.user_id, library_id) if library_id else []
        if not rows and isinstance(body.get("measurements"), list):
            rows = body["measurements"]
        _OUT_VAL = {"worked": 1.0, "partial": 0.5, "failed": 0.0}
        measurements = []
        for r in rows:
            if not isinstance(r, dict):
                continue
            mv = r.get("measured_value")
            try:
                val = (float(mv) if mv is not None and mv != ""
                       else _OUT_VAL.get(str(r.get("outcome", "")).lower()))
            except (TypeError, ValueError):
                val = None
            if val is None:
                continue
            measurements.append((r.get("mutations", ""), val))

        # Sanitize settings — clamp model + host to known values (never load an
        # arbitrary HF model id from the client).
        s = body.get("settings") if isinstance(body.get("settings"), dict) else {}
        model = s.get("model", "small")
        if model not in ("small", "medium", "large"):
            model = "small"
        host = s.get("host", "e_coli")
        if host not in ("e_coli", "yeast", "human"):
            host = "e_coli"
        try:
            pct = float(s.get("percentile", 85.0))
        except (TypeError, ValueError):
            pct = 85.0
        pct = min(99.0, max(1.0, pct))

        def _clampi(v, lo, hi, d):
            try:
                return max(lo, min(hi, int(v)))
            except (TypeError, ValueError):
                return d
        settings = {
            "model": model, "host": host, "percentile": pct,
            "k": _clampi(s.get("k", 30), 1, 200, 30),
            "min_mutations": _clampi(s.get("min_mutations", 2), 1, 10, 2),
            "max_mutations": _clampi(s.get("max_mutations", 5), 1, 12, 5),
            "restarts": _clampi(s.get("restarts", 8), 1, 24, 8),
            "steps": _clampi(s.get("steps", 1200), 100, 5000, 1200),
            "seed": s.get("seed"),
        }
        try:
            rows2, surrogate = _de_round2_library(wt_protein, settings, measurements)
        except Exception:  # noqa: BLE001
            logger.exception("DE round-2 failed.")
            return jsonify({"ok": False, "error":
                "Couldn't compute round 2 — check the sequence and try again."}), 500
        _auth.cleanup_expired_de_outcomes_async(auth.user_id)
        return jsonify({
            "ok": True,
            "variants": rows2,
            "wt_protein": wt_protein,
            "wt_identifier": str(body.get("wt_identifier", "") or "round 2"),
            "settings_used": settings,
            "surrogate": surrogate,
            "round": 2,
        })

    @app.get("/api/admin/mutation-priors")
    def admin_mutation_priors() -> Response:
        """View the stored cross-user aggregate (de-identified). Admin-token gated."""
        from dee.core import aggregate as _agg
        if not _admin_ok():
            return jsonify({"ok": False, "error": "forbidden"}), 403
        rows = _auth.get_mutation_priors()
        return jsonify({"ok": True, "count": len(rows), "priors": rows,
                        "effective_date": _agg.EFFECTIVE_DATE.isoformat(),
                        "min_users": _agg.MIN_USERS})

    @app.post("/api/admin/rebuild-priors")
    def admin_rebuild_priors() -> Response:
        """Recompute the cross-user aggregate from all logged outcomes and store
        it. Admin-token gated AND date-gated (refuses before the v2.0 effective
        date). De-identified by construction; k-anonymity floor MIN_USERS."""
        from dee.core import aggregate as _agg
        if not _admin_ok():
            return jsonify({"ok": False, "error": "forbidden"}), 403
        # Opt-in richer aggregate: split each substitution by its ESM ΔLL bin.
        # Heavy (one ESM pass per library) → off by default; the plain path is
        # the tested default. Any ESM failure degrades to unbinned keys.
        esm_bins = bool((request.get_json(force=True, silent=True) or {}).get("esm_bins"))
        import datetime as _dt2
        gate_open = _dt2.date.today() >= _agg.EFFECTIVE_DATE
        ll_maps = None
        if esm_bins and gate_open:                      # don't load ESM pre-gate
            grouped_lib = _auth.list_all_de_outcomes_grouped_with_lib()
            grouped = [(uid, meas) for uid, _lib, meas in grouped_lib]
            try:
                ll_maps = _compute_de_ll_maps(grouped_lib)
            except Exception:  # noqa: BLE001
                logger.exception("esm-bin ll_maps failed; falling back to plain aggregate")
                ll_maps = None
        else:
            grouped = _auth.list_all_de_outcomes_grouped()
        try:
            prior = _agg.build_priors(grouped, ll_maps=ll_maps)   # enforces the 2026-07-08 gate
        except _agg.AggregationGateError as exc:
            return jsonify({"ok": False, "error": "gated", "detail": str(exc),
                            "effective_date": _agg.EFFECTIVE_DATE.isoformat()}), 423
        rows = prior.to_rows()
        result = _auth.replace_mutation_priors(rows)
        _GLOBAL_PRIOR_CACHE["data"] = None              # bust the scorer cache
        return jsonify({"ok": bool(result.get("ok")),
                        "substitutions": len(rows),
                        "contributing_libraries": len(grouped),
                        "esm_binned": bool(esm_bins and ll_maps and any(ll_maps)),
                        "written": result.get("written", 0),
                        "priors": rows})

    # ── Unified outcomes framework — generic capture + per-tool aggregate ─────
    @app.post("/api/outcomes")
    def outcomes_save() -> Response:
        """Save this user's wet-lab outcomes for any tool's saved design."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required", "kind": "signin_required"}), 403
        body = request.get_json(force=True, silent=True) or {}
        tool = str(body.get("tool", "")).strip().lower()
        design_id = str(body.get("design_id", "")).strip()
        rows = body.get("outcomes")
        if not isinstance(rows, list):
            return jsonify({"ok": False, "error": "No outcomes provided."}), 400
        result = _auth.save_outcomes(auth.user_id, tool, design_id, rows)
        return jsonify(result), (200 if result.get("ok") else 400)

    @app.get("/api/outcomes/<tool>/<design_id>")
    def outcomes_list(tool: str, design_id: str) -> Response:
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"ok": False, "error": "signin_required", "kind": "signin_required"}), 403
        return jsonify({"ok": True,
                        "outcomes": _auth.list_outcomes(auth.user_id, tool.lower(), design_id)})

    @app.get("/api/admin/priors/<tool>")
    def admin_priors(tool: str) -> Response:
        from dee.core import outcomes as _O
        if not _admin_ok():
            return jsonify({"ok": False, "error": "forbidden"}), 403
        rows = _auth.get_outcome_priors(tool.lower())
        return jsonify({"ok": True, "tool": tool.lower(), "count": len(rows), "priors": rows,
                        "effective_date": _O.EFFECTIVE_DATE.isoformat(),
                        "registered_tools": _O.registered_tools()})

    @app.post("/api/admin/rebuild-priors/<tool>")
    def admin_rebuild_priors_tool(tool: str) -> Response:
        """Recompute one tool's cross-user aggregate from public.outcomes.
        Admin-token + date gated. De-identified; k-anonymity per the ToolSpec."""
        from dee.core import outcomes as _O
        if not _admin_ok():
            return jsonify({"ok": False, "error": "forbidden"}), 403
        tool = tool.lower()
        if _O.get_spec(tool) is None:
            return jsonify({"ok": False, "error": "unknown_tool",
                            "registered_tools": _O.registered_tools()}), 404
        grouped = _auth.list_all_outcomes_grouped(tool)
        try:
            prior = _O.build_priors(tool, grouped)         # enforces the effective-date gate
        except _O.AggregationGateError as exc:
            return jsonify({"ok": False, "error": "gated", "detail": str(exc),
                            "effective_date": _O.EFFECTIVE_DATE.isoformat()}), 423
        rows = prior.to_rows()
        result = _auth.replace_outcome_priors(tool, rows)
        return jsonify({"ok": bool(result.get("ok")), "tool": tool,
                        "keys": len(rows), "contributing_designs": len(grouped),
                        "written": result.get("written", 0), "priors": rows})

    @app.post("/api/crispr/download")
    def crispr_download() -> Response:
        """Return the CSV body for a fresh design. We re-design from the
        sequence on download rather than caching per-job to avoid a
        whole job-state layer for what's essentially a pure function
        of the input. Same sign-in gate as /api/crispr/design."""
        auth = _auth.get_auth()
        if auth.anonymous:
            return jsonify({"error": "signin_required"}), 403

        body = request.get_json(force=True, silent=True) or {}
        seq = (body.get("sequence") or "").strip()
        if not seq:
            return jsonify({"error": "missing 'sequence'"}), 400
        if len(seq) > 1_000_000:
            return jsonify({"error": "input_too_large"}), 400

        try:
            max_results = int(body.get("max_results", 50))
        except (TypeError, ValueError):
            max_results = 50
        max_results = max(1, min(500, max_results))

        enzyme = str(body.get("enzyme", "cas9")).lower()
        if enzyme not in ("cas9", "cas12a"):
            enzyme = "cas9"

        # Phase 2B-1 — same optional context as /api/crispr/design so the
        # downloaded XLSX matches what the user saw in the table.
        target_organism = str(body.get("target_organism", "")).lower().strip()
        gene_symbol     = str(body.get("gene_symbol", "")).strip()
        if target_organism not in ("", "ecoli", "human", "mouse"):
            target_organism = ""
        if len(gene_symbol) > 32 or not re.match(r"^[A-Za-z0-9._-]*$", gene_symbol):
            gene_symbol = ""

        # Phase 2C-1 passthrough
        from dee.core import crispr_cloning as _cc_dl
        vector_id = str(body.get("vector_id", "")).lower().strip()
        if vector_id and vector_id not in _cc_dl.CRISPR_VECTORS:
            vector_id = ""

        # Phase 3 (M1) passthrough so the XLSX matches the on-screen mode.
        from dee.core import base_editor as _be_dl
        mode = str(body.get("mode", "knockout")).lower()
        if mode not in ("knockout", "base_edit"):
            mode = "knockout"
        base_editor = str(body.get("base_editor", "")).lower().strip()
        if base_editor and _be_dl.get_base_editor(base_editor) is None:
            base_editor = ""

        # Export format. XLSX (default) is locale-safe for Excel users in
        # ;-delimiter locales; CSV is the universal format for pipelines /
        # pandas / R that some users explicitly need.
        fmt = str(body.get("format", "xlsx")).lower().strip()
        if fmt not in ("xlsx", "csv"):
            fmt = "xlsx"

        try:
            guides = _find_crispr_guides(
                seq, enzyme=enzyme, max_results=max_results,
                target_organism=target_organism, gene_symbol=gene_symbol,
                vector_id=vector_id, mode=mode, base_editor=base_editor,
            )
        except ValueError as exc:
            return jsonify({"error": str(exc)}), 400

        rows = _crispr_csv_rows(guides)

        # ── CSV export ──────────────────────────────────────────────────
        # Comma-delimited, RFC-4180 quoting (csv module quotes any field
        # containing a comma/quote/newline — e.g. KO reasoning — so it stays
        # in one column even when opened in a ;-delimiter locale). A UTF-8
        # BOM makes Excel (any locale) detect the encoding correctly.
        if fmt == "csv":
            import csv as _csv
            from io import StringIO as _SIO
            from flask import make_response as _mr_csv
            sio = _SIO()
            writer = _csv.writer(sio, quoting=_csv.QUOTE_MINIMAL, lineterminator="\r\n")
            for r in rows:
                writer.writerow(r)
            # Lead with a UTF-8 BOM so Excel auto-detects the encoding.
            body_bytes = ("" + sio.getvalue()).encode("utf-8")
            resp = _mr_csv(body_bytes)
            resp.headers["Content-Type"] = "text/csv; charset=utf-8"
            resp.headers["Content-Disposition"] = (
                'attachment; filename="turingdna_crispr_guides.csv"'
            )
            return resp

        # ── XLSX export (default) ───────────────────────────────────────
        # openpyxl produces a true Excel file with explicit column types;
        # opens cleanly in Excel/Numbers/Google Sheets regardless of locale.
        from io import BytesIO as _BIO
        from openpyxl import Workbook as _WB
        from openpyxl.styles import Font as _Font, Alignment as _Align, PatternFill as _Fill

        wb = _WB()
        ws = wb.active
        ws.title = "Guides"

        header_row, data_rows = rows[0], rows[1:]
        ws.append(header_row)

        # Numeric-typed cells where appropriate so Excel sorts + formats them
        # correctly (sort by Composite is the most useful thing the user
        # will do in Excel; force scientific notation off, keep 3 decimals).
        # Header → indices for the cells we want numeric.
        header_index = {name: i for i, name in enumerate(header_row)}
        num_cols = {
            header_index.get("Rank"),
            header_index.get("Position"),
            header_index.get("Composite score"),
            header_index.get("On-target"),
            header_index.get("Max self-CFD"),
            header_index.get("Off-target count"),
            header_index.get("KO efficacy"),
            header_index.get("GC %"),
            # Phase 2A numeric columns
            header_index.get("Frameshift %"),
            header_index.get("Top outcome dominance %"),
            # Phase 2B-1 numeric columns
            header_index.get("Genome off-target count"),
            header_index.get("Genome off-target max CFD"),
            # Phase 3 (M1) numeric column
            header_index.get("Editability"),
        }
        num_cols.discard(None)
        for r in data_rows:
            converted = []
            for col_idx, cell in enumerate(r):
                if col_idx in num_cols:
                    try:
                        converted.append(float(cell) if "." in str(cell) else int(cell))
                    except (TypeError, ValueError):
                        converted.append(cell)
                else:
                    converted.append(cell)
            ws.append(converted)

        # Header styling — bold + light paper-tone fill so the header
        # row reads as the table caption, not data.
        bold = _Font(bold=True, color="0A0A0A")
        paper_fill = _Fill(start_color="EFECE5", end_color="EFECE5", fill_type="solid")
        for cell in ws[1]:
            cell.font = bold
            cell.fill = paper_fill
            cell.alignment = _Align(vertical="center")

        # Freeze the header row so it sticks when the user scrolls down a
        # large guide list. Also widen columns to something sensible —
        # Excel's autosize logic is browser-dependent.
        ws.freeze_panes = "A2"
        widths = {
            "Rank": 6, "Enzyme": 8, "Strand": 8, "Position": 10,
            "Spacer": 28, "PAM": 8, "Target context (5'→3')": 36,
            "Composite score": 16, "On-target": 12, "Max self-CFD": 14,
            "Off-target count": 16, "KO efficacy": 12, "KO reasoning": 56,
            "GC %": 8, "Flags": 18,
            # Phase 2A
            "Top predicted indel": 22, "Frameshift %": 14, "Top outcome dominance %": 22,
            "Indel distribution": 64, "Base-editor compatibility": 30,
            # Phase 2B-1
            "Genome searched": 14, "Genome off-target count": 18,
            "Genome off-target max CFD": 22, "Top genome off-target": 44,
            "Exon context": 32,
            # Phase 2C-1
            "Cloning vector": 36, "Addgene #": 12, "Cloning enzyme": 14,
            "Sense oligo (5'→3')": 32, "Antisense oligo (5'→3')": 32,
        }
        from openpyxl.utils import get_column_letter as _col_letter
        for i, name in enumerate(header_row, start=1):
            ws.column_dimensions[_col_letter(i)].width = widths.get(name, 14)

        bio = _BIO()
        wb.save(bio)
        body_bytes = bio.getvalue()

        from flask import make_response as _mr
        resp = _mr(body_bytes)
        resp.headers["Content-Type"] = (
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        )
        resp.headers["Content-Disposition"] = (
            f'attachment; filename="turingdna_crispr_guides.xlsx"'
        )
        return resp

    # NOTE: /api/library, /api/library/<filename> (GET + DELETE), and
    # /api/shutdown were removed on 2026-05-26 per SECURITY_AUDIT findings
    # C2 + C3.
    #
    # The library endpoints listed every CSV under the Space-shared
    # ~/.dee/output/ directory and let anyone download or delete files
    # by guessing filenames — they pre-dated the per-user storage we now
    # ship in Supabase. The dashboard (planned task #98) will be the
    # replacement, querying public.libraries via Supabase RLS-gated reads.
    #
    # /api/shutdown was an unauthenticated DoS vector — POSTing to it
    # killed the Flask process. Reasonable for the original macOS .app
    # use case, dangerous in the hosted multi-tenant deployment. The
    # HF Space's own restart mechanism replaces this for ops needs.

    # NOTE: the /api/chat endpoint (BioMistral-7B proxy via gradio_client to
    # winter4000/turingdna-assistant) was removed on 2026-05-25. The full
    # implementation lives in _llm_backup_2026-05-25/server/server.py.pre-strip
    # alongside the frontend chat panel + WebLLM browser-side LLM. Re-wire
    # when the assistant is ready to ship again.

    return app


# ----------------------------------------------------------------- helpers


# NOTE: the ASSISTANT block (gradio_client connection to
# winter4000/turingdna-assistant, _AssistantUnavailable, _get_assistant_client,
# _format_history_into_message, _call_assistant) was removed on 2026-05-25.
# Full implementation lives in _llm_backup_2026-05-25/server/server.py.pre-strip
# and can be restored when the assistant is ready to ship again.


_VALID_MODELS = {"small", "medium", "large"}
_VALID_HOSTS = {"e_coli", "ecoli", "yeast", "s_cerevisiae", "human", "h_sapiens"}
_VALID_DEVICES = {None, "", "cpu", "cuda", "mps", "auto"}
_VALID_QUANT = {None, "", "none", "int8", "int4", "fp16", "bf16"}


# ─── ESM-2 scorer cache + CPU model gate ──────────────────────────────────
# Two problems this block solves:
#  (1) Building a scorer LOADS the model weights (expensive). We were doing it
#      on every /api/run. Cache one instance per effective model and reuse it —
#      huge warm-latency win, and it stops N concurrent runs from each loading
#      their own copy (which multiplies memory → OOM).
#  (2) The 650M/3B models are unusable on the free CPU tier: a 3B fp32 load is
#      ~12–24 GB and OOM-KILLS THE WHOLE CONTAINER for every user. So on a
#      non-CUDA host we transparently downgrade to 'small' and neutralise any
#      'cuda'/quantization request (which would also crash the load on CPU).
_SCORER_CACHE: "Dict[str, Any]" = {}
_SCORER_CACHE_LOCK = threading.Lock()
_GPU_AVAILABLE: Optional[bool] = None


def _gpu_available() -> bool:
    """True only if a CUDA device is actually present. Cached; treats a
    missing/broken torch as CPU-only."""
    global _GPU_AVAILABLE
    if _GPU_AVAILABLE is None:
        try:
            import torch
            _GPU_AVAILABLE = bool(torch.cuda.is_available())
        except Exception:  # noqa: BLE001
            _GPU_AVAILABLE = False
    return _GPU_AVAILABLE


def _effective_model(requested: Optional[str]) -> str:
    """Downgrade a GPU-class model to 'small' on a CPU-only box so a single
    user request can't OOM-kill the shared instance."""
    model = requested or "small"
    if model in ("medium", "large") and not _gpu_available():
        logger.warning("Model %r requested on a CPU-only host — downgrading to 'small'.", model)
        return "small"
    return model


def _get_scorer(model_name: Optional[str] = None,
                device: Optional[str] = None,
                quantization: Optional[str] = None):
    """Process-global, lock-guarded ESM-2 scorer cache. Weights load at most
    once per (effective) configuration and are reused across runs."""
    from dee.models.scorer import ESM2Scorer, ScorerConfig
    model = _effective_model(model_name)
    if not _gpu_available():
        device = None          # ignore a user 'cuda'/'mps' on a CPU box
        quantization = None    # bitsandbytes quant is CUDA-only anyway
    key = f"{model}|{device or 'auto'}|{quantization or 'none'}"
    cached = _SCORER_CACHE.get(key)
    if cached is not None:
        return cached
    with _SCORER_CACHE_LOCK:
        cached = _SCORER_CACHE.get(key)   # double-checked under the lock
        if cached is None:
            cached = ESM2Scorer(ScorerConfig(
                model_name=model, device=device, quantization=quantization))
            _SCORER_CACHE[key] = cached
        return cached


def _validate_run_settings(raw: Dict[str, Any]) -> Dict[str, Any]:
    """Normalize and bounds-check the user-supplied run settings.

    Returns a clean dict ready to hand to ``_run_pipeline``. Raises
    ``ValueError`` (the route turns this into HTTP 400) on any invalid
    value — better to fail loudly at submission than have the worker
    thread crash silently or produce a degenerate library.

    The original code did ``int(settings.get("k", 30))`` with no bounds,
    so a malformed request (k=-1, max_mutations=99999, percentile=200,
    host="postgres") would either crash the SearchConfig with an
    InternalError or return a 200 with a useless result. The bounds here
    are intentionally generous — the goal is to catch garbage, not
    second-guess the user's intent.
    """
    def _num(field: str, default, lo, hi, kind):
        value = raw.get(field, default)
        try:
            value = kind(value)
        except (TypeError, ValueError):
            raise ValueError(
                f"{field!r} must be a {kind.__name__}; got {raw.get(field)!r}.",
            )
        if value < lo or value > hi:
            raise ValueError(
                f"{field!r}={value} is outside the allowed range [{lo}, {hi}].",
            )
        return value

    model = (raw.get("model") or "small")
    if model not in _VALID_MODELS:
        raise ValueError(f"model must be one of {sorted(_VALID_MODELS)}; got {model!r}.")

    host = (raw.get("host") or "e_coli")
    if host not in _VALID_HOSTS:
        raise ValueError(f"host must be one of {sorted(_VALID_HOSTS)}; got {host!r}.")

    device = raw.get("device")
    if device not in _VALID_DEVICES:
        raise ValueError(f"device must be one of {sorted(d or '<auto>' for d in _VALID_DEVICES)}; got {device!r}.")

    quant = raw.get("quantization")
    if quant not in _VALID_QUANT:
        raise ValueError(f"quantization must be one of {sorted(q or '<none>' for q in _VALID_QUANT)}; got {quant!r}.")

    seed = raw.get("seed")
    if seed not in (None, ""):
        try:
            seed = int(seed)
        except (TypeError, ValueError):
            raise ValueError(f"seed must be an integer or null; got {seed!r}.")

    percentile    = _num("percentile",    85.0, 0.0,  100.0, float)
    k             = _num("k",             30,   1,    500,   int)
    min_mutations = _num("min_mutations", 2,    1,    50,    int)
    max_mutations = _num("max_mutations", 5,    1,    50,    int)
    restarts      = _num("restarts",      8,    1,    100,   int)
    steps         = _num("steps",         1200, 50,   50000, int)

    if min_mutations > max_mutations:
        raise ValueError(
            f"min_mutations ({min_mutations}) must be ≤ max_mutations ({max_mutations}).",
        )

    # CPU-tier safety: downgrade GPU-class models + drop a 'cuda'/quant request
    # so the run can't OOM the shared instance. Reflected in the returned dict
    # so analytics + the methods note describe what actually ran.
    model = _effective_model(model)
    if not _gpu_available():
        device = None
        quant = None

    return {
        "model": model,
        "percentile": percentile,
        "k": k,
        "min_mutations": min_mutations,
        "max_mutations": max_mutations,
        "restarts": restarts,
        "steps": steps,
        "host": host,
        "seed": seed,
        "device": device,
        "quantization": quant,
    }


def _safe_decode_text(path: Path) -> str:
    """Decode an uploaded sequence file as text without silently losing bytes.

    The previous code used ``path.read_text(errors="ignore")`` in the
    ORF-fallback branch, which silently drops any byte that isn't valid
    UTF-8 — a corrupted upload could yield a different ORF than the user
    intended. This helper tries common encodings in order of likelihood for
    a sequence file:

      1. UTF-8 with BOM (UTF-8-SIG) — Windows Notepad's default for files
         containing any non-ASCII char.
      2. Plain UTF-8 — the modern default everywhere else.
      3. UTF-16 LE/BE — older Windows tooling, especially when the user
         exported from Excel as "Unicode Text".
      4. Latin-1 — never raises, accepts all 256 byte values. Last-resort
         fallback for genuinely odd inputs (will pass through whatever
         bytes are there; downstream alphabet validation rejects them).

    Sequences are pure ASCII anyway (ACGTU and amino-acid letters), so for
    every legitimate input one of the early encodings produces a usable
    string. The point of the chain is to never SILENTLY drop a byte.
    """
    raw = path.read_bytes()
    for enc in ("utf-8-sig", "utf-8", "utf-16", "utf-16-le", "utf-16-be"):
        try:
            return raw.decode(enc)
        except UnicodeDecodeError:
            continue
    # latin-1 cannot fail; this branch is the universal fallback.
    return raw.decode("latin-1")


def _materialize_input() -> tuple[Path, str]:
    """Pull the request's sequence into a temp file we can hand to parse_input.

    For uploads we also impose a generous-but-finite size cap (8 MiB) so a
    runaway client or accidental binary-file drop can't blow up the server.
    Real protein CDS uploads top out under ~50 kB even for the largest
    genes; 8 MiB covers full plasmid GenBank files with comfortable margin.
    """
    MAX_UPLOAD_BYTES = 8 * 1024 * 1024  # 8 MiB

    if "file" in request.files:
        file = request.files["file"]
        suffix = Path(file.filename or "").suffix or ".txt"
        tmp = tempfile.NamedTemporaryFile(
            delete=False, suffix=suffix, dir=str(STATE_DIR)
        )
        file.save(tmp.name)
        tmp.close()
        if Path(tmp.name).stat().st_size > MAX_UPLOAD_BYTES:
            Path(tmp.name).unlink(missing_ok=True)
            raise SequenceValidationError(
                f"Uploaded file exceeds the {MAX_UPLOAD_BYTES // (1024 * 1024)} MiB limit. "
                "Trim to just the gene of interest before uploading.",
            )
        return Path(tmp.name), file.filename or "uploaded"

    body = request.get_json(force=True, silent=True) or {}
    text = body.get("text", "").strip()
    if not text:
        raise SequenceValidationError("No sequence provided.")
    if len(text.encode("utf-8")) > MAX_UPLOAD_BYTES:
        raise SequenceValidationError(
            f"Pasted text exceeds the {MAX_UPLOAD_BYTES // (1024 * 1024)} MiB limit.",
        )
    tmp = tempfile.NamedTemporaryFile(
        delete=False, suffix=".txt", mode="w", encoding="utf-8", dir=str(STATE_DIR)
    )
    tmp.write(text)
    tmp.close()
    return Path(tmp.name), body.get("name") or "pasted"


def _humanize_paste_name(original_name: str) -> str:
    """A clean display label for a raw paste/upload that carries no real name."""
    stem = Path(original_name or "").stem.strip()
    if stem and stem.lower() not in ("pasted", "uploaded"):
        return stem            # a real uploaded filename, e.g. "TP53_exon2"
    return "Pasted sequence"


def _clean_record_identifier(record, path: Path, original_name: str) -> None:
    """When a raw (non-FASTA) sequence has no header, parse_input falls back to
    the file stem as the identifier — and for our temp files that stem is a
    random 'tmpXXXXXXXX'. That leaked through as the displayed identifier
    ("random letters"). Replace it in place with a human label so it never
    surfaces. FASTA headers / GenBank LOCUS names are untouched (their
    identifier never equals the temp stem)."""
    try:
        if record.identifier and record.identifier == path.stem:
            record.identifier = _humanize_paste_name(original_name)
    except Exception:  # noqa: BLE001 — display nicety must never break parsing
        pass


def _summarize(path: Path, original_name: str) -> tuple[Dict[str, Any], Dict[str, Any]]:
    """Return (JSON-friendly summary, extra session payload to cache).

    Three flow modes:
      1. Structured file (.dna/.gb/...) → list annotated CDS features.
      2. Raw input parses cleanly as a single CDS or protein → return preview.
      3. Raw input fails CDS validation (e.g. user pasted a whole plasmid) →
         fall back to a 6-frame ORF scan and return ORF choices.
    """
    suffix = path.suffix.lower()

    # Mode 1 — annotated structured file.
    if suffix in {".dna", ".gb", ".gbk", ".genbank", ".embl"}:
        features = list_cds_features(path)
        cds_options = [
            {"label": label, "length_nt": length} for label, length in features
        ]
        record = parse_input(path, require_start=False, require_stop=False)
        _clean_record_identifier(record, path, original_name)
        return (
            {
                "original_name": original_name,
                "detected_kind": "plasmid",
                "identifier": record.identifier,
                "protein_length": len(record.protein),
                "protein_preview": record.protein[:80]
                + ("…" if len(record.protein) > 80 else ""),
                "cds_options": cds_options,
            },
            # cds_options carried into the session so /api/run can enforce
            # the "pick one explicitly" check (audit M7).
            {"mode": "structured_file", "cds_options": cds_options},
        )

    # Mode 2 — try clean single-CDS / protein parse.
    try:
        record = parse_input(path, require_start=False, require_stop=False)
        _clean_record_identifier(record, path, original_name)
        return (
            {
                "original_name": original_name,
                "detected_kind": "protein" if not record.dna else "dna",
                "identifier": record.identifier,
                "protein_length": len(record.protein),
                "protein_preview": record.protein[:80]
                + ("…" if len(record.protein) > 80 else ""),
                "cds_options": None,
            },
            {"mode": "single"},
        )
    except SequenceValidationError as clean_exc:
        # Mode 3 — fall back to 6-frame ORF discovery for raw DNA. Use the
        # safe-decode chain instead of read_text(errors="ignore") so a UTF-16
        # or BOM-prefixed file doesn't silently lose every other byte and
        # surface a different ORF than the user pasted.
        text = _safe_decode_text(path)
        orfs = find_orfs_in_dna(text)
        if not orfs:
            # Not recoverable; bubble the original parse error up.
            raise clean_exc
        cds_options = [
            {
                "label": o.label,
                "length_nt": len(o.dna),
                "frame": o.frame,
                "protein_length": len(o.protein),
            }
            for o in orfs
        ]
        return (
            {
                "original_name": original_name,
                "detected_kind": "multi_orf",
                "identifier": f"{_humanize_paste_name(original_name)} (no annotation)",
                "protein_length": 0,
                "protein_preview": (
                    f"{len(orfs)} ORFs detected across 6 reading frames "
                    "(no annotated CDS features). Pick one below."
                ),
                "cds_options": cds_options,
            },
            # Same here: carry cds_options into the session so the
            # multi-ORF chooser is enforced server-side too (audit M7).
            {
                "mode": "orf",
                "orfs": {o.label: o.dna for o in orfs},
                "cds_options": cds_options,
            },
        )


_DE_ROUND2_MAX_AA = 500   # sync round-2 length cap (bounds ESM score time on free CPU)


# ── Cross-user aggregate prior (the data moat) ──────────────────────────
# Admin access is gated on a shared secret (env TURINGDNA_ADMIN_TOKEN). If the
# env var is unset, the admin endpoints are CLOSED (403) — no admin by default.
_GLOBAL_PRIOR_CACHE: Dict[str, Any] = {"data": None, "ts": 0.0}
_GLOBAL_PRIOR_TTL_S = 600.0


def _admin_ok() -> bool:
    token = os.environ.get("TURINGDNA_ADMIN_TOKEN", "")
    if not token:
        return False
    import hmac
    supplied = request.headers.get("X-Admin-Token", "")
    return bool(supplied) and hmac.compare_digest(supplied, token)


def _load_global_prior():
    """Load + cache the stored aggregate prior. Returns a GlobalPrior (possibly
    empty). Empty → apply_global_prior is a no-op, so this is inert until the
    first post-effective-date rebuild populates public.mutation_priors."""
    import time as _t
    from dee.core import aggregate as _agg
    now = _t.time()
    if _GLOBAL_PRIOR_CACHE["data"] is not None and (now - _GLOBAL_PRIOR_CACHE["ts"]) < _GLOBAL_PRIOR_TTL_S:
        return _GLOBAL_PRIOR_CACHE["data"]
    try:
        prior = _agg.GlobalPrior.from_rows(_auth.get_mutation_priors())
    except Exception:  # noqa: BLE001
        prior = _agg.GlobalPrior(effects={}, n_users={}, n_obs={})
    _GLOBAL_PRIOR_CACHE["data"] = prior
    _GLOBAL_PRIOR_CACHE["ts"] = now
    return prior


# Per-tool unified-outcomes prior cache (CRISPR, primer, …). Empty until the
# tool's post-effective-date rebuild populates public.outcome_priors → inert.
_TOOL_PRIOR_CACHE: Dict[str, Any] = {}


def _load_tool_prior(tool: str):
    """Cached outcomes.Prior for a tool from public.outcome_priors."""
    import time as _t
    from dee.core import outcomes as _O
    now = _t.time()
    ent = _TOOL_PRIOR_CACHE.get(tool)
    if ent is not None and (now - ent["ts"]) < _GLOBAL_PRIOR_TTL_S:
        return ent["data"]
    spec = _O.get_spec(tool)
    weight = spec.weight if spec else 0.2
    try:
        prior = _O.Prior.from_rows(tool, _auth.get_outcome_priors(tool), weight=weight)
    except Exception:  # noqa: BLE001
        prior = _O.Prior(tool=tool, effects={}, n_users={}, n_obs={}, weight=weight)
    _TOOL_PRIOR_CACHE[tool] = {"data": prior, "ts": now}
    return prior


def _compute_de_ll_maps(grouped_with_lib):
    """Best-effort {single-site label: ESM ΔLL} per library, for the richer
    (substitution × ESM-bin) DE aggregate. HEAVY (one ESM pass per distinct
    library) → only the opt-in rebuild calls it. Any failure for a library
    yields None for that unit (its keys stay unbinned). Returns a list parallel
    to grouped_with_lib."""
    from dee.models.scorer import ESM2Scorer, ScorerConfig
    cache: Dict[str, Any] = {}
    scorer = None
    maps = []
    for _uid, lib, _rows in grouped_with_lib:
        if lib in cache:
            maps.append(cache[lib]); continue
        m = None
        try:
            wt = _auth.get_library_wt(lib)
            if (wt and re.match(r"^[ACDEFGHIKLMNPQRSTVWY*]+$", wt)
                    and len(wt) <= _DE_ROUND2_MAX_AA):
                if scorer is None:
                    scorer = _get_scorer("small")
                df = scorer.score_all_substitutions(wt)
                m = {f"{r.wt_aa}{int(r.position) + 1}{r.mut_aa}": float(r.delta_ll)
                     for r in df.itertuples(index=False)}
        except Exception:  # noqa: BLE001
            logger.exception("ll-map compute failed for library %s", lib)
            m = None
        cache[lib] = m
        maps.append(m)
    return maps


def _de_round2_library(wt_protein: str, settings: Dict[str, Any],
                       measurements: list) -> tuple[list, Dict[str, Any]]:
    """Active-learning round 2 (Design→Build→Test→Learn). Score the WT, fit the
    surrogate on the user's measured variants, re-rank the single-site pool by
    the learned acquisition score, evolve, and assemble the same variant table
    shape as a normal run. Returns (variant_rows, surrogate_info)."""
    from dee.core import active_learning as _al
    from dee.optimizer.search import Mutation as _Mut

    scorer = _get_scorer(
        settings.get("model", "small"),
        settings.get("device"),
        settings.get("quantization"),
    )
    scores_df = scorer.score_all_substitutions(wt_protein)
    pool_df = top_percentile_pool(scores_df, percentile=float(settings.get("percentile", 85.0)))

    # Fit the surrogate on the round-1 single-site pool + the user's results,
    # then overwrite the pool's per-mutation score with the learned acquisition
    # (additive ⇒ evolve() consumes it unchanged).
    muts = [_Mut(int(r.position), str(r.wt_aa), str(r.mut_aa), float(r.delta_ll))
            for r in pool_df.itertuples(index=False)]
    surrogate = _al.fit_surrogate(muts, measurements)
    adj_df = pool_df.copy()
    adj_df["delta_ll"] = [
        surrogate.adjusted.get((int(r.position), str(r.mut_aa)), float(r.delta_ll))
        for r in pool_df.itertuples(index=False)
    ]

    variants = evolve(adj_df, SearchConfig(
        k=int(settings.get("k", 30)),
        max_mutations=int(settings.get("max_mutations", 5)),
        min_mutations=int(settings.get("min_mutations", 2)),
        n_restarts=int(settings.get("restarts", 8)),
        steps_per_restart=int(settings.get("steps", 1200)),
        seed=settings.get("seed"),
    ))
    df = variants_to_dataframe(
        wt_protein, variants,
        host=settings.get("host", "e_coli"),
        forbidden_sites=DEFAULT_FORBIDDEN_SITES,
    )
    return df.to_dict(orient="records"), {
        "learned":   surrogate.learned,
        "n_train":   surrogate.n_train,
        "w_prior":   round(surrogate.w_prior, 3),
        "n_effects": surrogate.n_effects,
        "note":      surrogate.note,
    }


def _run_pipeline(
    job: JobState,
    input_path: Path,
    original_name: str,
    cds_feature: Optional[str],
    settings: Dict[str, Any],
) -> None:
    """Background worker. Updates ``job`` in place as it makes progress."""
    try:
        job.status = "parsing"
        job.message = "Reading sequence…"
        job.progress = 0.05
        record = parse_input(
            input_path,
            require_start=False,
            require_stop=False,
            cds_feature=cds_feature,
        )
        _clean_record_identifier(record, input_path, original_name)
        job.wt_identifier = record.identifier
        job.wt_protein = record.protein
        job.settings_used = {
            "model": settings.get("model", "small"),
            "percentile": float(settings.get("percentile", 85.0)),
            "k": int(settings.get("k", 30)),
            "min_mutations": int(settings.get("min_mutations", 2)),
            "max_mutations": int(settings.get("max_mutations", 5)),
            "restarts": int(settings.get("restarts", 8)),
            "steps_per_restart": int(settings.get("steps", 1200)),
            "host": settings.get("host", "e_coli"),
            "seed": settings.get("seed"),
            "device": settings.get("device") or "cpu",
            "cds_feature": cds_feature,
        }

        job.status = "scoring"
        job.message = (
            f"Scoring {len(record.protein)} residues × 19 substitutions with ESM-2…"
        )
        job.progress = 0.15

        scorer = _get_scorer(
            settings.get("model", "small"),
            settings.get("device"),
            settings.get("quantization"),
        )
        scores_df = scorer.score_all_substitutions(record.protein)
        job.progress = 0.55

        pool = top_percentile_pool(scores_df, percentile=float(settings.get("percentile", 85.0)))
        job.message = f"Filtered to {len(pool)} high-impact single-site mutations."
        job.progress = 0.60

        # Soft-blend the cross-user AGGREGATE prior into round-1 scores: every
        # design benefits from the field's pooled wet-lab results. No-op until a
        # post-effective-date rebuild populates public.mutation_priors (so this
        # is inert before 2026-07-08). Individual designs stay ESM-driven; this
        # is a small nudge by amino-acid substitution type only.
        try:
            _gp = _load_global_prior()
            if _gp and _gp.effects:
                _w = 0.3
                pool = pool.copy()
                pool["delta_ll"] = [
                    float(r.delta_ll) + _w * _gp.effects.get(
                        (str(r.wt_aa).upper(), str(r.mut_aa).upper()), 0.0)
                    for r in pool.itertuples(index=False)
                ]
                job.message = (f"Filtered to {len(pool)} mutations; blended field-wide "
                               f"priors ({len(_gp.effects)} substitution types).")
        except Exception:  # noqa: BLE001
            logger.exception("global-prior blend skipped")

        job.status = "searching"
        job.message = (
            f"Optimizing multi-mutants (K={int(settings.get('k', 30))}, "
            f"max {int(settings.get('max_mutations', 5))} subs)…"
        )
        variants = evolve(
            pool,
            SearchConfig(
                k=int(settings.get("k", 30)),
                max_mutations=int(settings.get("max_mutations", 5)),
                min_mutations=int(settings.get("min_mutations", 2)),
                n_restarts=int(settings.get("restarts", 8)),
                steps_per_restart=int(settings.get("steps", 1200)),
                seed=settings.get("seed"),
            ),
        )
        job.progress = 0.85

        job.status = "encoding"
        job.message = f"Reverse-translating and scrubbing restriction sites for {len(variants)} variants…"
        df = variants_to_dataframe(
            record.protein,
            variants,
            host=settings.get("host", "e_coli"),
            forbidden_sites=DEFAULT_FORBIDDEN_SITES,
        )
        # ---------------------------------------------------------------
        # Build a WT pseudo-row with the SAME codon-optimization and
        # restriction-site scrub applied to variants, so the user can
        # order the unmutated wild-type alongside the evolved variants.
        # Variant_ID 'WT' is special-cased on the client.
        # ---------------------------------------------------------------
        try:
            wt_host = settings.get("host", "e_coli")
            wt_raw_dna = reverse_translate(record.protein, host=wt_host, append_stop=True)
            wt_clean_dna, wt_report = scrub_restriction_sites(
                wt_raw_dna,
                record.protein + "*",
                host=wt_host,
                forbidden_sites=DEFAULT_FORBIDDEN_SITES,
            )
            wt_pcr = pcr_metrics(wt_clean_dna)
            wt_row = {
                "Variant_ID": "WT",
                "Mutations_AA": "",
                "Mutant_AA_Seq": record.protein,
                "Optimized_DNA_Seq": wt_clean_dna,
                "Predicted_Fitness_Score": 0.0,
                "Length_bp": wt_pcr.get("length_bp"),
                "GC_Percent": wt_pcr.get("gc_percent"),
                "Primer_Fwd": wt_pcr.get("primer_fwd"),
                "Primer_Fwd_Tm_C": wt_pcr.get("primer_fwd_tm_c"),
                "Primer_Fwd_GC_Percent": wt_pcr.get("primer_fwd_gc"),
                "Primer_Rev": wt_pcr.get("primer_rev"),
                "Primer_Rev_Tm_C": wt_pcr.get("primer_rev_tm_c"),
                "Primer_Rev_GC_Percent": wt_pcr.get("primer_rev_gc"),
                "Annealing_Temp_C": wt_pcr.get("annealing_temp_c"),
                "Restriction_Sites_Found": sum(wt_report.sites_found.values()),
                "Restriction_Sites_Unresolved": len(wt_report.unresolved),
            }
        except Exception as wt_exc:  # noqa: BLE001 — never fail the whole run for the WT row
            # Audit H5: previously this branch set wt_row = None and the WT
            # row silently vanished from the table. The user's reference
            # sample (the unmutated sequence they paid us to design around)
            # was gone with no signal. Now we emit a sentinel row with the
            # error message in the Mutations_AA column so the UI can render
            # an explicit "WT row couldn't be built — <reason>" indicator
            # instead of silently omitting it.
            logger.warning("Couldn't build WT pseudo-row: %s", wt_exc)
            wt_row = {
                "Variant_ID": "WT",
                "Mutations_AA": f"ERROR: {wt_exc}",
                "Mutant_AA_Seq": record.protein,
                "Optimized_DNA_Seq": "",
                "Predicted_Fitness_Score": 0.0,
                "Length_bp": 0,
                "GC_Percent": 0.0,
                "Primer_Fwd": "",
                "Primer_Fwd_Tm_C": None,
                "Primer_Fwd_GC_Percent": 0.0,
                "Primer_Rev": "",
                "Primer_Rev_Tm_C": None,
                "Primer_Rev_GC_Percent": 0.0,
                "Annealing_Temp_C": None,
                "Restriction_Sites_Found": 0,
                "Restriction_Sites_Unresolved": 0,
                # Sentinel flag the frontend can check to render the error
                # banner inline on the WT row instead of trying to display
                # an empty DNA sequence as if it were valid.
                "WT_Error": str(wt_exc),
            }
        job.progress = 0.95

        stem = Path(original_name).stem or "library"
        safe_id = "".join(c if c.isalnum() else "_" for c in record.identifier) or "wt"
        ts = time.strftime("%Y%m%d_%H%M%S")
        filename = f"{stem}__{safe_id}__{ts}_dee_library.csv"
        primary = OUTPUT_DIR / filename
        write_library_csv(df, str(primary))
        job.csv_path = str(primary)

        # Best-effort copy to Desktop. Requires the user to have granted the
        # .app Files & Folders → Desktop access (NSDesktopFolderUsageDescription
        # in Info.plist triggers the system prompt).
        desktop_dest = DESKTOP_DIR / filename
        try:
            desktop_dest.write_bytes(primary.read_bytes())
            job.desktop_path = str(desktop_dest)
        except (PermissionError, OSError) as exc:
            logger.warning("Could not copy to Desktop (%s); CSV stays in ~/.dee/output/.", exc)
            job.desktop_path = None

        variant_rows = df.to_dict(orient="records")
        # WT row first — UI sorts by Variant_ID so 'WT' sorts naturally last by
        # default; the client explicitly pins it to row 0.
        job.variants = ([wt_row] + variant_rows) if wt_row else variant_rows
        job.status = "done"
        job.progress = 1.0
        job.message = f"Done. {len(variants)} variants ready."
        job.finished_at = time.time()

        # Save the library to Supabase Storage so the user can access it
        # from their dashboard. Signed-in users only — anonymous runs no-op
        # inside save_library_async. Fire-and-forget; failures are logged
        # but don't propagate to the user.
        try:
            top_fitness = None
            if variant_rows:
                # Variants are sorted descending by fitness; the first one's
                # Predicted_Fitness_Score (if present) is the top score.
                top_fitness = variant_rows[0].get("Predicted_Fitness_Score")
                if isinstance(top_fitness, (int, float)):
                    top_fitness = float(top_fitness)
                else:
                    top_fitness = None
            # Library name: prefer the original input filename's stem; fall
            # back to the WT identifier. Truncated to keep dashboard rows tidy.
            library_name = (
                Path(original_name).stem
                or record.identifier
                or "library"
            )[:120]
            # Pre-assign the library id so the client gets it in the result and
            # can log wet-lab outcomes against it (the learning flywheel).
            job.library_id = uuid.uuid4().hex
            _auth.save_library_async(
                user_id=job.user_id,
                job_id=job.job_id,
                csv_path=job.csv_path,
                name=library_name,
                wt_identifier=record.identifier,
                wt_protein=record.protein,
                host_organism=settings.get("host", "e_coli"),
                n_variants=len(variants),
                top_fitness=top_fitness,
                library_id=job.library_id,
            )
        except Exception as exc:  # noqa: BLE001
            # save_library_async is itself fire-and-forget, but the kwargs
            # build above could in principle raise. Never block the user.
            logger.warning("save_library kickoff failed: %s", exc)
    except SequenceValidationError as exc:
        job.status = "error"
        job.error = f"Couldn't parse input: {exc}"
        job.message = job.error
        job.finished_at = time.time()
    except Exception as exc:  # noqa: BLE001
        logger.exception("Pipeline crashed.")
        job.status = "error"
        job.error = f"{type(exc).__name__}: {exc}"
        job.message = job.error
        job.finished_at = time.time()


# ============================================================== EDIT PIPELINE
# Re-derive every column of a variant row from a user-edited DNA string. The
# input is treated as authoritative — we do NOT scrub restriction sites or
# silently mutate the user's bases. We translate it, diff against WT to
# rebuild the mutation label, recompute PCR metrics, and report restriction
# sites as found (cleared count is always 0 — they wrote it, they keep it).
# Returns the new row dict in the same shape as variants_to_dataframe rows
# so it can drop into job.variants[i] directly. Raises ValueError on
# user-correctable issues (callers should turn that into HTTP 400).


def _diff_mutations_against_wt(wt_protein: str, mutant: str) -> str:
    """Build a 'A23V,K45R' label from the WT-vs-edited protein diff.

    Same convention used elsewhere in the codebase: 1-indexed AA positions,
    single-letter codes, '*' for stop. If lengths differ we still emit a
    label for the overlapping prefix and prefix the whole string with a
    length-change marker so the UI can render the warning prominently.
    """
    overlap = min(len(wt_protein), len(mutant))
    muts = []
    for i in range(overlap):
        if wt_protein[i] != mutant[i]:
            muts.append(f"{wt_protein[i]}{i + 1}{mutant[i]}")
    label = ",".join(muts)
    if len(wt_protein) != len(mutant):
        marker = f"length:WT={len(wt_protein)}aa,edited={len(mutant)}aa"
        return f"{marker}|{label}" if label else marker
    return label


def _scan_restriction_sites(
    dna: str,
    forbidden_sites: Optional[Dict[str, str]] = None,
) -> Dict[str, int]:
    """Scan both strands for forbidden recognition sites. Pure observation —
    no scrubbing. Returns {enzyme: count} for sites present in the user's
    edited DNA, summed across forward + reverse strands so a Type IIS site
    on either strand is counted once per occurrence."""
    forbidden = forbidden_sites or DEFAULT_FORBIDDEN_SITES
    from Bio.Seq import Seq
    rc = str(Seq(dna).reverse_complement())
    counts: Dict[str, int] = {}
    for enzyme, motif in forbidden.items():
        fwd = sum(1 for _ in re.finditer(f"(?={re.escape(motif)})", dna))
        rev = sum(1 for _ in re.finditer(f"(?={re.escape(motif)})", rc))
        counts[enzyme] = fwd + rev
    return counts


def _rederive_variant_row(
    *,
    variant_id: str,
    edited_dna: str,
    wt_protein: str,
    original_row: Dict[str, Any],
) -> Dict[str, Any]:
    """Recompute every derived column of a variant row from a new DNA string.

    The user's edit is treated as authoritative. We validate (ACGT only,
    length multiple of 3), translate (a premature stop is allowed — it
    truncates the product, e.g. an intentional nonsense/knockout mutation),
    diff against WT for the Mutations_AA label, recompute PCR metrics, and
    report restriction-site presence honestly.

    Raises ValueError with a user-readable message on validation failure —
    callers should turn that into HTTP 400 so the frontend can display it.
    """
    from Bio.Seq import Seq

    if not edited_dna:
        raise ValueError("Edited DNA is empty.")
    cleaned = edited_dna.upper()
    bad = set(cleaned) - set("ACGT")
    if bad:
        raise ValueError(
            f"Edited DNA contains non-ACGT character(s): {sorted(bad)!r}. "
            "Only A, C, G, T are allowed. RNA U should be converted to T "
            "and IUPAC ambiguity codes must be resolved before saving."
        )
    if len(cleaned) % 3 != 0:
        raise ValueError(
            f"Edited DNA length ({len(cleaned)} bp) is not a multiple of 3 — "
            "frame would be broken. Add or remove bases until the length "
            "is divisible by 3 before saving."
        )

    # Translate. Stop codons appear as '*'. A premature stop is a LEGITIMATE
    # edit — a nonsense / truncation mutation (e.g. an intentional knockout or
    # a single-base SNP that happens to create a stop). We don't block it:
    # synthesis vendors synthesize the DNA as-is, they don't reject internal
    # stops. The encoded protein simply ends at the first stop; the user's
    # client shows a non-blocking heads-up. (Previously this hard-rejected the
    # save with a false "vendors will reject this" claim — an audit finding.)
    raw_protein = str(Seq(cleaned).translate(table=1, to_stop=False))
    protein = raw_protein.split("*")[0]

    # Mutations label — diff against WT. For length-changing edits this
    # prefixes a 'length:...' marker so the frontend can warn loudly.
    is_wt_row = variant_id.upper() == "WT"
    mutations_label = "" if is_wt_row and protein == wt_protein else (
        _diff_mutations_against_wt(wt_protein, protein)
    )

    # PCR metrics + restriction-site count from the actual edited bytes.
    pcr = pcr_metrics(cleaned)
    re_counts = _scan_restriction_sites(cleaned)

    # Compose the row. Preserve fields we don't recompute (Variant_ID,
    # Predicted_Fitness_Score) from the original row so the variant keeps
    # its identity in the table.
    return {
        "Variant_ID": original_row.get("Variant_ID", variant_id),
        "Mutations_AA": mutations_label,
        "Mutant_AA_Seq": protein,
        "Optimized_DNA_Seq": cleaned,
        "Predicted_Fitness_Score": original_row.get(
            "Predicted_Fitness_Score", 0.0
        ),
        "Length_bp": pcr.get("length_bp"),
        "GC_Percent": pcr.get("gc_percent"),
        "Primer_Fwd": pcr.get("primer_fwd"),
        "Primer_Fwd_Tm_C": pcr.get("primer_fwd_tm_c"),
        "Primer_Fwd_GC_Percent": pcr.get("primer_fwd_gc"),
        "Primer_Rev": pcr.get("primer_rev"),
        "Primer_Rev_Tm_C": pcr.get("primer_rev_tm_c"),
        "Primer_Rev_GC_Percent": pcr.get("primer_rev_gc"),
        "Annealing_Temp_C": pcr.get("annealing_temp_c"),
        "Restriction_Sites_Found": sum(re_counts.values()),
        # We don't scrub edits, so 'Unresolved' equals 'Found' here. The
        # frontend treats anything > 0 as a hard warning before synthesis.
        "Restriction_Sites_Unresolved": sum(re_counts.values()),
        # Marker so exports + UI can show "edited" indicators without
        # second-guessing equality with original_row.
        "Edited": True,
    }


def _atomic_rewrite_csv(job: JobState) -> None:
    """Rewrite the job's library CSV from current job.variants atomically.

    Writes to a sibling .tmp file and renames into place so a concurrent
    /api/download never sees a half-written file. WT-row 'Edited' flag and
    other UI-only fields are dropped from the CSV — the on-disk shape stays
    identical to what variants_to_dataframe originally wrote.
    """
    import pandas as pd

    if not job.csv_path or not job.variants:
        return
    target = Path(job.csv_path)
    tmp = target.with_suffix(target.suffix + ".tmp")
    df_rows = []
    for v in job.variants:
        row = {k: val for k, val in v.items() if k != "Edited"}
        df_rows.append(row)
    pd.DataFrame(df_rows).to_csv(str(tmp), index=False)
    tmp.replace(target)


EXPORT_DISCLAIMER = (
    "RESEARCH USE ONLY — NOT FOR DIAGNOSTIC OR THERAPEUTIC USE. "
    "Sequences in this file are computational predictions generated by "
    "TuringDNA. Visually verify every sequence before ordering DNA from a "
    "synthesis vendor. The TuringDNA authors disclaim all warranties; "
    "you are responsible for validating outputs against your experimental "
    "requirements."
)


def _disclaimer_lines(prefix: str = "") -> List[str]:
    """Split the disclaimer into wrapped lines with an optional comment prefix.
    Used by formats whose native comment syntax is line-based (FASTA's ``;``,
    GenBank ``COMMENT`` blocks, shell-style ``#``)."""
    import textwrap
    wrapped = textwrap.wrap(EXPORT_DISCLAIMER, width=72)
    return [f"{prefix}{line}" for line in wrapped]


def _fasta_from_job(job: JobState, *, of: str = "protein") -> str:
    """Serialize a job's variants as FASTA. ``of`` selects which sequence to
    emit per record — protein or DNA. Protein is the more common ask (mutants
    aligned against WT); DNA is included for completeness.

    Prepends the export disclaimer as ``;``-comment lines (the standard
    FASTA comment syntax — every conforming parser skips lines starting
    with ``;``). The disclaimer is also embedded in every record's
    description so a downstream tool that extracts a single record still
    carries the "predicted output; verify before use" annotation.
    """
    if not job.variants:
        return ""
    lines: List[str] = []
    lines.extend(_disclaimer_lines("; "))
    lines.append(f"; Generated by TuringDNA · {time.strftime('%Y-%m-%d %H:%M:%S')}")
    lines.append(";")
    seq_key = "Mutant_AA_Seq" if of == "protein" else "Optimized_DNA_Seq"
    for v in job.variants:
        header = (
            f">{v.get('Variant_ID')} {v.get('Mutations_AA')} "
            f"fitness={v.get('Predicted_Fitness_Score')} "
            f"[PREDICTED · verify before synthesis]"
        )
        seq = v.get(seq_key, "")
        lines.append(header)
        for i in range(0, len(seq), 60):
            lines.append(seq[i : i + 60])
    return "\n".join(lines) + "\n"


def _genbank_from_job(job: JobState) -> str:
    """Build a multi-record GenBank file with one record per variant.

    Each record gets a CDS feature whose ``/translation`` is the mutant
    protein, plus a misc_feature per substitution so the mutation positions
    are visible when opened in SnapGene / Benchling.
    """
    from Bio.Seq import Seq
    from Bio.SeqFeature import FeatureLocation, SeqFeature
    from Bio.SeqRecord import SeqRecord
    from Bio import SeqIO

    records = []
    for v in job.variants or []:
        dna = v.get("Optimized_DNA_Seq", "")
        protein = v.get("Mutant_AA_Seq", "")
        muts = v.get("Mutations_AA", "")
        record = SeqRecord(
            Seq(dna),
            id=v.get("Variant_ID", "variant"),
            name=v.get("Variant_ID", "variant"),
            description=(
                f"TuringDNA predicted variant — RESEARCH USE ONLY · "
                f"verify before synthesis. mutations={muts}; "
                f"fitness={v.get('Predicted_Fitness_Score')}"
            ),
            annotations={
                "molecule_type": "DNA",
                "organism": "synthetic construct",
                # GenBank COMMENT block — SnapGene / Benchling render this
                # at the top of the entry when the file is opened.
                "comment": EXPORT_DISCLAIMER,
            },
        )
        # Whole-CDS feature with the translation in /translation.
        cds_qualifiers = {
            "gene": [job.wt_identifier or "designed_variant"],
            "product": ["designed variant"],
            "note": [f"mutations={muts}"],
        }
        if protein:
            cds_qualifiers["translation"] = [protein]
        record.features.append(
            SeqFeature(
                FeatureLocation(0, len(dna)),
                type="CDS",
                qualifiers=cds_qualifiers,
            )
        )
        # One misc_feature per substitution at the nucleotide it touches.
        # Audit H6: the previous parser did
        #   pos_aa = int("".join(c for c in mut[1:-1] if c.isdigit()))
        # which would happily turn a malformed label like "A1V2K3R" into the
        # position string "123" and place a feature at nt 367 — completely
        # wrong. It would also silently truncate at the first non-digit
        # character. Use the same strict regex the frontend's detail panel
        # uses (^[A-Z](\d+)[A-Z*]$) so labels that don't match the format
        # are skipped rather than parsed into garbage positions. The
        # length-marker prefix from manual edits ("length:WT=8aa,...|G3V")
        # is handled by taking only the post-"|" portion if present.
        _MUT_RE = re.compile(r"^([A-Z])(\d+)([A-Z*])$")
        mut_payload = muts.split("|", 1)[-1] if "|" in muts else muts
        for mut in mut_payload.split(","):
            mut = mut.strip()
            m = _MUT_RE.match(mut)
            if not m:
                continue
            pos_aa = int(m.group(2))
            if pos_aa < 1:
                continue
            nt_start = (pos_aa - 1) * 3
            nt_end = nt_start + 3
            if nt_end > len(dna):
                continue
            record.features.append(
                SeqFeature(
                    FeatureLocation(nt_start, nt_end),
                    type="misc_feature",
                    qualifiers={"label": [mut], "note": [f"Substitution {mut}"]},
                )
            )
        records.append(record)

    buf = io.StringIO()
    SeqIO.write(records, buf, "genbank")
    return buf.getvalue()


def _xlsx_from_job(job: JobState) -> bytes:
    """Write the variant table to a production-quality .xlsx workbook.

    Two sheets:
      * "Variants" — the table itself, with bold-colored header row, frozen
        top row, auto-filter, column widths sized per content type, number
        formatting per column (3 decimals for fitness, 1 for GC/Tm, integer
        for bp), and horizontally-clamped sequence columns so the long
        Mutant_AA_Seq / Optimized_DNA_Seq cells don't visually drown out
        everything else.
      * "Run info" — key-value pairs of every parameter the engine used,
        plus the auto-generated methods paragraph for copy-pasting into a
        Materials & Methods section.

    Requires ``openpyxl``. Returns raw bytes for the Flask handler to stream.
    """
    import openpyxl
    from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
    from openpyxl.utils import get_column_letter

    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Variants"

    variants = job.variants or []
    if not variants:
        wb.remove(ws)
        ws = wb.create_sheet("Variants")
        ws["A1"] = "No variants in this run."
        buf = io.BytesIO()
        wb.save(buf)
        buf.seek(0)
        return buf.getvalue()

    headers = list(variants[0].keys())

    # Header row — bold white on deep brand background, all caps, slightly
    # taller so it reads as a real header band.
    header_fill = PatternFill("solid", fgColor="0A5F77")
    header_font = Font(name="Inter", size=11, bold=True, color="FFFFFF")
    header_align = Alignment(horizontal="left", vertical="center", wrap_text=False)
    body_font = Font(name="Inter", size=10)
    body_align = Alignment(horizontal="left", vertical="top", wrap_text=False)
    num_align = Alignment(horizontal="right", vertical="top")
    mono_font = Font(name="JetBrains Mono", size=9)
    band_fill = PatternFill("solid", fgColor="F4F6F9")  # alternating row color

    thin = Side(style="thin", color="E0E5EC")
    border = Border(left=thin, right=thin, top=thin, bottom=thin)

    # Column geometry — width sized to typical content per column type.
    # Number formats keyed to specific column names (rest = text).
    COL_WIDTH = {
        "Variant_ID": 11,
        "Mutations_AA": 28,
        "Mutant_AA_Seq": 52,
        "Optimized_DNA_Seq": 70,
        "Predicted_Fitness_Score": 14,
        "Length_bp": 9,
        "GC_Percent": 10,
        "Primer_Fwd": 32,
        "Primer_Fwd_Tm_C": 12,
        "Primer_Fwd_GC_Percent": 14,
        "Primer_Rev": 32,
        "Primer_Rev_Tm_C": 12,
        "Primer_Rev_GC_Percent": 14,
        "Annealing_Temp_C": 14,
        "Restriction_Sites_Found": 14,
        "Restriction_Sites_Unresolved": 16,
    }
    NUM_FORMAT = {
        "Predicted_Fitness_Score": "0.000",
        "GC_Percent": "0.0",
        "Primer_Fwd_Tm_C": "0.0",
        "Primer_Fwd_GC_Percent": "0.0",
        "Primer_Rev_Tm_C": "0.0",
        "Primer_Rev_GC_Percent": "0.0",
        "Annealing_Temp_C": "0.0",
        "Length_bp": "0",
        "Restriction_Sites_Found": "0",
        "Restriction_Sites_Unresolved": "0",
    }
    MONO_COLS = {"Mutations_AA", "Mutant_AA_Seq", "Optimized_DNA_Seq",
                 "Primer_Fwd", "Primer_Rev", "Variant_ID"}
    NUM_COLS = set(NUM_FORMAT.keys())

    # Disclaimer banner row at the very top. Merged across all data
    # columns, amber background, bold red text — meant to be the first
    # thing the user sees when they open the workbook. Drops the actual
    # header row to row 2 and data to row 3 onwards.
    disclaimer_fill = PatternFill("solid", fgColor="FEF3C7")
    disclaimer_font = Font(name="Inter", size=10, bold=True, color="7F1D1D")
    disclaimer_align = Alignment(horizontal="left", vertical="center", wrap_text=True)
    ws.cell(row=1, column=1, value=EXPORT_DISCLAIMER)
    ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=max(1, len(headers)))
    banner = ws.cell(row=1, column=1)
    banner.fill = disclaimer_fill
    banner.font = disclaimer_font
    banner.alignment = disclaimer_align
    ws.row_dimensions[1].height = 48

    # Write header row.
    for col_idx, col in enumerate(headers, start=1):
        cell = ws.cell(row=2, column=col_idx, value=col)
        cell.fill = header_fill
        cell.font = header_font
        cell.alignment = header_align
        cell.border = border
    ws.row_dimensions[2].height = 22

    # Write data rows with alternating band fill + column-specific formatting.
    # Data now starts at row 3 because of the banner + header rows above.
    for row_idx, variant in enumerate(variants, start=3):
        is_band = (row_idx % 2 == 0)
        for col_idx, col in enumerate(headers, start=1):
            val = variant.get(col)
            cell = ws.cell(row=row_idx, column=col_idx, value=val)
            cell.border = border
            if is_band:
                cell.fill = band_fill
            if col in NUM_COLS:
                cell.alignment = num_align
                cell.number_format = NUM_FORMAT[col]
                cell.font = body_font
            elif col in MONO_COLS:
                cell.alignment = body_align
                cell.font = mono_font
            else:
                cell.alignment = body_align
                cell.font = body_font

    # Column widths.
    for col_idx, col in enumerate(headers, start=1):
        width = COL_WIDTH.get(col, 14)
        ws.column_dimensions[get_column_letter(col_idx)].width = width

    # Freeze the header row + first two columns so Variant_ID + Mutations stay
    # in view while horizontally scrolling through primer + sequence columns.
    # Now C3 because the banner + header rows live above.
    ws.freeze_panes = "C3"

    # Auto-filter the data range only (skips the banner row).
    from openpyxl.utils import get_column_letter as _gcl
    last_col_letter = _gcl(len(headers))
    last_row = 2 + len(variants)
    ws.auto_filter.ref = f"A2:{last_col_letter}{last_row}"

    # ---- Sheet 2: Run info ------------------------------------------------
    info = wb.create_sheet("Run info")
    label_font = Font(name="Inter", size=11, bold=True, color="0A5F77")
    value_font = Font(name="Inter", size=11)
    methods_font = Font(name="Inter", size=10)

    # Disclaimer banner at the top of Run info too. Mirrors the Variants
    # sheet so a user who jumps straight to Run info still sees the
    # research-use-only framing.
    info.cell(row=1, column=1, value=EXPORT_DISCLAIMER)
    info.merge_cells(start_row=1, start_column=1, end_row=1, end_column=4)
    info_banner = info.cell(row=1, column=1)
    info_banner.fill = disclaimer_fill
    info_banner.font = disclaimer_font
    info_banner.alignment = disclaimer_align
    info.row_dimensions[1].height = 48
    INFO_ROW_OFFSET = 2  # data starts at row 3 (banner row 1, blank row 2)

    s = job.settings_used or {}
    model_label = {
        "small": "ESM-2 35M (facebook/esm2_t12_35M_UR50D)",
        "medium": "ESM-2 650M (facebook/esm2_t33_650M_UR50D)",
        "large": "ESM-2 3B (facebook/esm2_t36_3B_UR50D)",
    }.get(s.get("model"), s.get("model", ""))
    host_label = {
        "e_coli": "Escherichia coli",
        "yeast": "Saccharomyces cerevisiae",
        "human": "Homo sapiens",
    }.get(s.get("host"), s.get("host", ""))

    rows = [
        ("Wild-type identifier", job.wt_identifier),
        ("Wild-type length", f"{len(job.wt_protein)} aa"),
        ("Model", model_label),
        ("Percentile cutoff",
         f"≥ p{s.get('percentile')} (top {100 - float(s.get('percentile', 85)):.0f}%)"),
        ("K variants returned", s.get("k")),
        ("Min mutations / variant", s.get("min_mutations")),
        ("Max mutations / variant", s.get("max_mutations")),
        ("SA restarts", s.get("restarts")),
        ("SA steps / restart", s.get("steps_per_restart")),
        ("Expression host", host_label),
        ("Compute device", s.get("device")),
        ("Random seed", s.get("seed") if s.get("seed") is not None else "(random)"),
        ("CDS feature picked", s.get("cds_feature") or "(none / single CDS)"),
        ("Run started (epoch s)", job.started_at),
        ("Wall time (s)", job.elapsed()),
    ]
    for i, (k, v) in enumerate(rows, start=1 + INFO_ROW_OFFSET):
        info.cell(row=i, column=1, value=k).font = label_font
        info.cell(row=i, column=2, value=v).font = value_font

    # Methods paragraph. Offset accounts for the disclaimer banner block.
    info.cell(row=len(rows) + 2 + INFO_ROW_OFFSET, column=1, value="Materials & methods (copy-paste)").font = label_font
    methods = (
        f"Variants of {job.wt_identifier} ({len(job.wt_protein)} aa) were designed "
        f"in silico with {model_label} (Lin et al., Science 2022) using the "
        f"wild-type marginal log-likelihood scoring scheme of Meier et al. "
        f"(Adv. Neural Inf. Process. Syst. 2021). Single-point substitutions "
        f"in the top {100 - float(s.get('percentile', 85)):.0f}% by ΔLL were "
        f"retained as the combinatorial search space. {s.get('k')} multi-mutant "
        f"variants with {s.get('min_mutations')}–{s.get('max_mutations')} "
        f"simultaneous substitutions were generated by simulated annealing "
        f"({s.get('restarts')} restarts × {s.get('steps_per_restart')} steps, "
        f"geometric cooling) maximizing cumulative ΔLL with stop-codon and "
        f"duplicate-position penalties. Optimized DNA was reverse-translated "
        f"using {host_label} codon-usage frequencies and synonymously cleaned "
        f"of BsaI, BsmBI, and NotI recognition sites for Golden Gate "
        f"compatibility."
    )
    methods_row = len(rows) + 3 + INFO_ROW_OFFSET
    mcell = info.cell(row=methods_row, column=1, value=methods)
    mcell.font = methods_font
    mcell.alignment = Alignment(wrap_text=True, vertical="top")
    info.merge_cells(start_row=methods_row, start_column=1, end_row=methods_row, end_column=4)
    info.row_dimensions[methods_row].height = 140

    info.column_dimensions["A"].width = 32
    info.column_dimensions["B"].width = 48
    info.column_dimensions["C"].width = 16
    info.column_dimensions["D"].width = 16

    buf = io.BytesIO()
    wb.save(buf)
    buf.seek(0)
    return buf.getvalue()


def _json_from_job(job: JobState) -> bytes:
    """Compact, programmer-friendly JSON dump of the run.

    Includes ``_disclaimer`` and ``_generated_at`` fields at the top of
    the payload so any downstream consumer sees the "predicted; verify
    before use" annotation alongside the data.
    """
    payload = {
        "_disclaimer": EXPORT_DISCLAIMER,
        "_generated_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
        "_generator": "TuringDNA",
        "wt_identifier": job.wt_identifier,
        "wt_protein": job.wt_protein,
        "wt_protein_length": len(job.wt_protein),
        "variants": job.variants or [],
    }
    return json.dumps(payload, indent=2).encode("utf-8")


def _tsv_from_job(job: JobState) -> bytes:
    """Tab-separated equivalent of the CSV — friendlier for some analysis
    pipelines (R, awk, Perl) that hate quoted commas. The disclaimer is
    prepended as ``#``-prefixed comment lines; pandas / R / awk users
    pass ``comment='#'`` (or equivalent) to skip them, while a vendor
    eyeballing the file in a text editor still sees the disclaimer first.
    """
    import pandas as pd

    df = pd.DataFrame(job.variants or [])
    body = df.to_csv(sep="\t", index=False)
    header = "\n".join(_disclaimer_lines("# ")) + "\n"
    header += f"# Generated by TuringDNA · {time.strftime('%Y-%m-%d %H:%M:%S')}\n"
    return (header + body).encode("utf-8")


# Format registry — keyed by the value of ``?format=``. Each entry produces
# (payload, mimetype, file-extension). New formats are a one-line addition.
def _render_download(job: JobState, fmt: str):
    if fmt == "csv":
        # Excel in many European locales (incl. the user's Georgian Excel)
        # treats CSV with ',' delimiter as a single column unless told
        # otherwise. We prepend Excel's "sep=," hint line and a UTF-8 BOM so
        # double-clicking the file opens it with proper columns everywhere.
        #
        # Disclaimer placement: appended as a final row after all variant
        # data. Putting it BEFORE the sep=, hint breaks Excel's auto-
        # detection; putting it ABOVE the header row breaks pandas /
        # csv.DictReader. A final row with the disclaimer in column A and
        # blanks elsewhere is the format-neutral compromise — every tool
        # reads it as one extra row, and a vendor opening the file in
        # Excel sees the disclaimer plainly at the bottom of the data.
        #
        # Audit M6: the previous implementation did
        #   raw = read_bytes(); decoded = raw.decode('utf-8','replace'); …; decoded.encode('utf-8')
        # which is a needless round-trip — and silently corrupted any
        # byte that wasn't valid UTF-8 (the 'replace' arg). Now we read
        # bytes and work in bytes throughout; the only decoding is the
        # first-line column count, done on a bounded prefix.
        with open(job.csv_path, "rb") as f:
            raw = f.read()
        # Read the first line in bytes to count columns without decoding
        # the whole file. Sequence columns are pure ASCII so split('\n')
        # on bytes is safe here.
        first_line_bytes = raw.split(b"\n", 1)[0] if raw else b""
        n_cols = max(1, first_line_bytes.count(b",") + 1) if first_line_bytes else 1
        # The disclaimer row is pure ASCII (EXPORT_DISCLAIMER above is
        # constructed from ASCII chars only), so encoding once is safe.
        disclaimer_row = (
            '"' + EXPORT_DISCLAIMER.replace('"', '""') + '"'
            + ("," * (n_cols - 1))
            + "\r\n"
        ).encode("utf-8")
        bom = b"\xef\xbb\xbf"
        return bom + b"sep=,\r\n" + raw + disclaimer_row, "text/csv", "csv"
    if fmt == "tsv":
        return _tsv_from_job(job), "text/tab-separated-values", "tsv"
    if fmt == "fasta":
        return _fasta_from_job(job, of="protein").encode("utf-8"), "text/x-fasta", "fasta"
    if fmt == "fasta-dna":
        return _fasta_from_job(job, of="dna").encode("utf-8"), "text/x-fasta", "fna"
    if fmt in ("gb", "genbank"):
        return _genbank_from_job(job).encode("utf-8"), "text/x-genbank", "gb"
    if fmt in ("xlsx", "excel"):
        return (
            _xlsx_from_job(job),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "xlsx",
        )
    if fmt == "json":
        return _json_from_job(job), "application/json", "json"
    raise ValueError(
        "format must be one of: csv, tsv, fasta, fasta-dna, gb, xlsx, json"
    )


# ----------------------------------------------------------------- CLI entry


def serve(host: Optional[str] = None, port: Optional[int] = None) -> None:
    """Run the Flask server.

    Honors ``HOST`` and ``PORT`` env vars first (so the same image runs under
    Hugging Face Spaces' fixed ``PORT=7860`` contract, Fly.io's ``8080``,
    Render's ``10000``, etc.) before falling back to local-dev defaults
    (``127.0.0.1:4789``).
    """
    env_host = os.environ.get("HOST")
    env_port = os.environ.get("PORT")
    host = host or env_host or "127.0.0.1"
    port = port or (int(env_port) if env_port else 4789)
    app = build_app()
    logger.info("Digital Evolution Engine listening on http://%s:%s", host, port)
    print(f"DEE_READY http://{host}:{port}", flush=True)
    app.run(host=host, port=port, debug=False, use_reloader=False, threaded=True)


def build_app() -> Flask:
    """Construct the app + run one-time startup side-effects (logging config +
    off-target prewarm). This is the WSGI entry point used in production by
    gunicorn (``dee.server:build_app()``); ``serve()`` reuses it for local dev so
    both paths get identical startup behaviour.

    Prewarms the CRISPR off-target kmer indexes in daemon threads so user
    requests don't pay the 60-300 s cold-build cost (ecoli ~3-5 s; human/mouse
    60-180 s). A Design click before the build finishes returns empty + a
    "building" flag rather than blocking the request past the ~120 s cap.
    """
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(name)s: %(message)s",
    )
    app = create_app()
    try:
        from dee.core import offtarget as _ot
        for _org in ("ecoli", "human", "mouse"):
            if _ot.is_organism_ready(_org):
                logger.info("Prewarming kmer index for %s in background", _org)
                _ot.kick_off_build(_org)
    except Exception as exc:  # noqa: BLE001
        logger.warning("Off-target prewarm failed (will still build on demand): %s", exc)
    return app


if __name__ == "__main__":
    serve()