File size: 227,969 Bytes
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
9e15897
 
e88a3a3
81a8217
 
 
e88a3a3
9a6cb9a
e88a3a3
 
 
 
 
 
e13472e
e88a3a3
 
 
f5696cb
9e15897
 
e91167d
81a8217
9e15897
 
e88a3a3
9e15897
81a8217
e91167d
f5696cb
9a6cb9a
e91167d
9e15897
e91167d
f5696cb
e88a3a3
9a6cb9a
e88a3a3
 
 
 
 
 
 
f5696cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07bca1c
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
f5696cb
 
 
 
 
 
 
 
9e15897
07bca1c
 
b2aa446
07bca1c
9a6cb9a
 
 
 
 
85f794d
 
ff9703a
 
81a8217
 
 
 
 
 
b2aa446
 
 
81a8217
 
9a6cb9a
 
 
 
 
 
9e15897
 
 
 
 
 
b2aa446
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07bca1c
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07bca1c
 
 
 
 
 
 
81a8217
 
 
 
 
07bca1c
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
b2aa446
9a6cb9a
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
f5696cb
e88a3a3
 
 
 
 
f5696cb
e88a3a3
 
 
9a6cb9a
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
 
e88a3a3
dcd43e2
e88a3a3
 
 
 
 
9a6cb9a
aa1490a
9a6cb9a
07bca1c
 
e88a3a3
 
 
 
 
f5696cb
e88a3a3
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
 
9a6cb9a
e88a3a3
07bca1c
 
f5696cb
e88a3a3
 
 
 
 
cf09724
 
e88a3a3
cf09724
bb71a16
 
 
 
 
9a6cb9a
e88a3a3
f5696cb
e88a3a3
9a6cb9a
 
 
 
bb71a16
 
9a6cb9a
 
 
 
 
bb71a16
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5981db
9a6cb9a
 
 
 
 
bb71a16
 
3e19b1e
 
 
 
 
9a6cb9a
 
 
b2aa446
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5981db
9a6cb9a
 
 
 
 
 
 
 
a5981db
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
a5981db
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5981db
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9703a
 
 
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
85f794d
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9a6cb9a
b2aa446
 
9a6cb9a
b2aa446
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
9a6cb9a
 
 
 
 
81a8217
9a6cb9a
 
 
 
 
 
a5981db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dbbea8
a5981db
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
f5696cb
e88a3a3
f5696cb
e88a3a3
 
 
81a8217
85f794d
81a8217
85f794d
 
 
81a8217
85f794d
 
81a8217
85f794d
 
 
 
 
 
 
 
81a8217
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
992a41f
 
 
 
 
81a8217
992a41f
 
 
 
 
 
 
dcd43e2
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
81a8217
 
 
 
992a41f
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
ff9703a
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
9e15897
 
 
 
81a8217
 
b2aa446
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
aa1490a
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
f5696cb
9e15897
f5696cb
9e15897
f5696cb
9e15897
 
f5696cb
9e15897
 
f5696cb
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
 
 
85f794d
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
992a41f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
992a41f
 
 
81a8217
 
 
992a41f
 
 
 
 
 
 
9e15897
 
f5696cb
9e15897
 
 
 
 
 
 
 
 
f5696cb
 
9e15897
 
 
 
f5696cb
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
07bca1c
f5696cb
9e15897
 
 
 
 
f5696cb
 
 
 
9e15897
 
f5696cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07bca1c
9e15897
 
 
 
 
 
 
 
07bca1c
 
 
 
 
 
 
 
9e15897
07bca1c
 
 
9a6cb9a
 
9e15897
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
9a6cb9a
 
9e15897
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
9a6cb9a
9e15897
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
ff9703a
 
 
 
b2aa446
 
bce4cf7
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
81a8217
 
9e15897
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
bce4cf7
 
 
 
 
 
b2aa446
 
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
81a8217
b2aa446
 
 
9a6cb9a
 
ff9703a
 
85f794d
 
 
 
ff9703a
 
 
85f794d
 
 
ff9703a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
ff9703a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
ff9703a
 
 
85f794d
ff9703a
85f794d
ff9703a
 
 
85f794d
 
9a6cb9a
 
 
81a8217
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
 
22987e4
a93637f
22987e4
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb71a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
992a41f
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
e88a3a3
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
81a8217
 
 
 
 
 
 
 
 
 
 
9e15897
81a8217
 
9e15897
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
81a8217
 
 
85f794d
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
81a8217
 
 
 
 
 
 
 
 
 
 
e88a3a3
07bca1c
e88a3a3
 
 
 
 
 
 
 
992a41f
9e15897
 
f5696cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
f5696cb
9e15897
85f794d
 
 
f5696cb
 
9e15897
e88a3a3
f5696cb
 
 
 
 
 
 
 
 
07bca1c
f5696cb
 
07bca1c
f5696cb
81a8217
 
 
ff9703a
 
 
 
f5696cb
 
 
 
 
07bca1c
 
9e15897
07bca1c
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07bca1c
 
 
 
 
 
 
992a41f
9e15897
07bca1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
07bca1c
 
9e15897
07bca1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
07bca1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
07bca1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
b2aa446
9e15897
b2aa446
9e15897
 
 
 
 
 
b2aa446
 
 
9e15897
 
 
 
 
 
b2aa446
 
9e15897
 
b2aa446
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
81a8217
 
b2aa446
81a8217
 
 
b2aa446
81a8217
 
 
b2aa446
81a8217
b2aa446
81a8217
 
 
 
 
 
b2aa446
81a8217
 
 
b2aa446
81a8217
 
 
 
 
 
 
b2aa446
81a8217
 
 
 
 
 
 
 
 
9e15897
81a8217
 
 
 
 
 
 
b2aa446
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
9e15897
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
81a8217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
81a8217
 
b2aa446
81a8217
 
 
 
 
 
 
 
 
 
 
07bca1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
07bca1c
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
07bca1c
 
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
992a41f
9e15897
aa1490a
 
9a6cb9a
 
992a41f
f5696cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
f5696cb
9e15897
f5696cb
 
9e15897
e88a3a3
f5696cb
9a6cb9a
 
 
 
f5696cb
9a6cb9a
f5696cb
 
 
 
 
 
 
 
 
 
9a6cb9a
 
 
f5696cb
9a6cb9a
f5696cb
 
 
 
 
 
 
 
 
 
9e15897
 
07bca1c
 
9e15897
07bca1c
e88a3a3
 
 
 
 
 
 
 
b2aa446
e88a3a3
 
 
 
 
 
 
 
 
 
 
992a41f
 
b2aa446
 
 
 
 
e88a3a3
 
 
 
 
f5696cb
 
aa1490a
f5696cb
 
 
 
 
 
e88a3a3
 
9e15897
 
 
85f794d
9e15897
 
 
e88a3a3
 
9e15897
e88a3a3
 
 
 
 
9a6cb9a
 
 
 
9e15897
9a6cb9a
 
85f794d
 
 
 
aa1490a
 
9a6cb9a
 
 
 
 
a5981db
 
9a6cb9a
 
b2aa446
 
9a6cb9a
 
 
 
 
 
9e15897
9a6cb9a
 
 
 
 
aa1490a
 
 
85f794d
aa1490a
 
b2aa446
 
e88a3a3
 
 
 
 
 
aa1490a
e88a3a3
9e15897
e88a3a3
 
85f794d
 
 
 
 
 
 
 
e88a3a3
a5981db
9a6cb9a
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
dcd43e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e91167d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
 
992a41f
 
e88a3a3
 
e91167d
e88a3a3
 
e91167d
 
 
 
 
e88a3a3
e91167d
 
e88a3a3
e91167d
 
9a6cb9a
 
 
 
 
 
e88a3a3
 
 
 
 
 
9a6cb9a
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""amazon_client.py — the SP-API transport, in the DATA LAYER where the loaders can reach it.

⛔⛔ **WHY THIS FILE MOVED DOWN OUT OF `aios-web/api/`, AND THE GATE THAT MADE IT.** The transport
started life inside `connectors_amazon.py`, and `harness/amazon_store.py` reached UP to import it.
`verify_meta`'s architecture leg caught it in one line -- `amazon_store.py -> connectors_amazon` --
and it was right: layers point ONE way (`modules -> core`, `api -> modules`), and nothing under
`platform/core` or `platform/harness` may import an API-layer module. That check exists because the
same shortcut was taken once before, with `sys.path.insert` plus an import from inside `core`.

⭐ **THE ALTERNATIVE WAS WORSE, WHICH IS WHY THIS AND NOT A SECOND READER.** `meta_store` avoids the
inversion by bringing its own reader, and Graph is simple enough that a second one costs little.
SP-API is not: the LWA token exchange, the read-only guard, the report request-poll-download loop
and the rate-limit reporting would all have existed twice, and "which stored credential serves this
connector" having two answers is a defect class this codebase already names. So the TRANSPORT lives
here, in the layer both callers can see, and `connectors_amazon.py` stays the API-layer face that
registers the liveness probe.

⭐ **WHY THIS FILE IS SMALL, AND THE STALE ASSUMPTION IT KILLS.** Since 2 October 2023 SP-API
disregards AWS SigV4 entirely and authorizes on the LWA access token alone: a plain
`Authorization: Bearer` header. Any library, blog post or memory that has us minting IAM users and
signing requests is describing a dead API.
· https://developer-docs.amazon.com/sp-api/changelog/sp-api-will-no-longer-require-aws-iam-or-aws-signature-version-4

⛔ **SELLER DATA IS READ-ONLY.** `_request` refuses any method but
GET before it builds a request. The separate `send_named_write` door admits C3's exact approved
inbound and removal batches. Sync and plain read routes cannot opt out of `_request`'s guard.

The approved POST wrappers read reports, pricing, fees, replenishment and Data Kiosk results.
`_notifications_post` creates only an EventBridge destination or one approved subscription.
These fixed paths cannot alter seller records or send buyer messages.

⛔ **REPORTS AND DATA KIOSK ARE THE BULK PATHS; FINANCES FOLLOWS EVERY PAGE.** SP-API is token-bucket rate limited per
operation per selling-partner/application pair, and Amazon treats throttling as evidence of a wrong
call pattern rather than a wrong ceiling. Standing rule 1 forbids a silent cap on a connector's
records, and its second half is what applies: a limit that genuinely cannot be removed must be
REPORTED with cause and a recommended fix. `REPORT_TYPES` below is that fix, written down.
· https://developer-docs.amazon.com/sp-api/docs/usage-plans-and-rate-limits

Ideation record, with every owner ruling: `AutoWiki/research/ideation/amazon-connector.md`
"""
from __future__ import annotations

import contextvars
from contextlib import contextmanager
import csv
import gzip
import hashlib
import importlib
import io
import json
import logging
import math
import os
import random
import re
import shutil
import sys
import tempfile
import threading
import time
from datetime import date, datetime, timezone, timedelta
import urllib.error
import urllib.parse
import urllib.request

KEY = "amazon_sp"
LABEL = "Amazon"

#: W57-T38/C13: five total attempts, including the first, bound one throttled operation.
RETRY_MAX_ATTEMPTS = 5
#: W57-T38/C13: exponential backoff starts at one second after the first 429.
RETRY_BASE_SECONDS = 1.0
#: W57-T38/C13: no individual retry sleep exceeds one minute, including Retry-After/jitter.
RETRY_MAX_SECONDS = 60.0
#: W57-T38/C13: randomize each wait by up to half its value to separate competing clients.
RETRY_JITTER = 0.5
#: W57-T38/C13: separate consecutive table report creations by at least five seconds.
REPORT_STAGGER_SECONDS = 5.0
#: Amazon createReport usage plan: 15 initial tokens, shared by callers in this process.
#: https://developer-docs.amazon.com/sp-api/reference/createreport
REPORT_BURST = 15
#: Amazon createReport usage plan: 0.0167 requests/second, approximately one token/minute.
#: https://developer-docs.amazon.com/sp-api/reference/createreport
REPORT_SUSTAINED_SECONDS = 60.0

#: Product Pricing v2022-05-01 `getCompetitiveSummary`, official default usage plan.
#: https://developer-docs.amazon.com/sp-api/reference/getcompetitivesummary
COMPETITIVE_SUMMARY_RATE = 0.033
COMPETITIVE_SUMMARY_INTERVAL = 1.0 / COMPETITIVE_SUMMARY_RATE
COMPETITIVE_SUMMARY_BATCH_SIZE = 20

#: AWD v2024-05-09 `listInventory`, official default usage plan and maximum page size.
#: https://developer-docs.amazon.com/sp-api/reference/listinventory
AWD_INVENTORY_RATE = 2.0
AWD_INVENTORY_INTERVAL = 1.0 / AWD_INVENTORY_RATE
AWD_INVENTORY_PAGE_SIZE = 200

# Unscoped callers retain the legacy bucket. Transport calls use credential-scoped state.
# The contextual wait belongs to the current report_document logger.
_report_pacer = {
    "tokens": float(REPORT_BURST),
    "updated": None,
    "last_create": None,
    "lock": threading.Lock(),
    "waited": contextvars.ContextVar("amazon_report_create_waited", default=0.0),
}

# Unscoped pacer defaults remain available to callers without an access token.
_entity_pacers = {
    "competitive_summary": {"last": None, "lock": threading.Lock()},
    "getItemOffersBatch": {"last": None, "lock": threading.Lock()},
    "awd_inventory": {"last": None, "lock": threading.Lock()},
    "transactions": {"last": None, "lock": threading.Lock()},
    "getOrderMetrics": {"last": None, "lock": threading.Lock()},
    "getInventorySummaries": {"last": None, "lock": threading.Lock()},
    "searchListingsItems": {"last": None, "lock": threading.Lock()},
    "searchCatalogItems": {"last": None, "lock": threading.Lock()},
    "getItemReviewTopics": {"last": None, "lock": threading.Lock()},
    "getItemReviewTrends": {"last": None, "lock": threading.Lock()},
    "getItemBrowseNode": {"last": None, "lock": threading.Lock()},
    "getBrowseNodeReviewTopics": {"last": None, "lock": threading.Lock()},
    "getMyFeesEstimates": {"last": None, "lock": threading.Lock()},
    "listAllFulfillmentOrders": {"last": None, "lock": threading.Lock()},
    "getFulfillmentOrder": {"last": None, "lock": threading.Lock()},
    "listInboundPlans": {"last": None, "lock": threading.Lock()},
    "getInboundPlan": {"last": None, "lock": threading.Lock()},
    "listShipmentItems": {"last": None, "lock": threading.Lock()},
    "getShipment": {"last": None, "lock": threading.Lock()},
    "getShipmentItemsByShipmentId": {"last": None, "lock": threading.Lock()},
    "getShipmentItems": {"last": None, "lock": threading.Lock()},
    "getSellingPartnerMetrics": {"last": None, "lock": threading.Lock()},
    "listOfferMetrics": {"last": None, "lock": threading.Lock()},
}

# Data Kiosk has its own quota, independent of createReport.
QUERY_BURST = 15
QUERY_SUSTAINED_SECONDS = 60.0
_query_pacer = {"tokens": float(QUERY_BURST), "updated": None, "lock": threading.Lock()}
_rate_lock = threading.Lock()
_rate_states = {}
_token_scopes = {}
_client_scope = contextvars.ContextVar("amazon_client_scope", default=None)
_tenant_scope = contextvars.ContextVar("amazon_tenant_scope", default="")
_reservation = contextvars.ContextVar("amazon_operation_reservation", default=None)
#: S82-T14: documents the first-load job already downloaded, keyed by `prefetch_key`. `None` outside a job write.
_prefetch = contextvars.ContextVar("amazon_report_prefetch", default=None)
#: S82-T14: the store's per-seller createReport ledger. A callable taking `fields`; it raises AmazonThrottled to defer.
_report_ledger = contextvars.ContextVar("amazon_report_ledger", default=None)
_QUERIES_CREATE_PATH = "dataKiosk/2023-11-15/queries"
_TRANSACTIONS_PATH = "finances/2024-06-19/transactions"
TRANSACTIONS_INTERVAL = 2.0

# Selection pinned to Amazon's published analytics_economics_2024_03_15.graphql,
# read 2026-09-25. RANGE avoids MONTH's automatic rounding of partial months.
# Only dates, a validated marketplace ID and one of two fixed grains are substituted.
_ECONOMICS_QUERY = '''query {
  analytics_economics_2024_03_15 {
    economics(startDate: "__START__", endDate: "__END__",
      marketplaceIds: ["__MARKETPLACE__"], aggregateBy: {date: __DATE__, productId: __PRODUCT__}) {
      startDate endDate marketplaceId msku fnsku childAsin parentAsin
      sales {
        orderedProductSales { amount currencyCode } unitsOrdered
        refundedProductSales { amount currencyCode } unitsRefunded
        netProductSales { amount currencyCode } netUnitsSold
        averageSellingPrice { amount currencyCode }
      }
      fees { feeTypeName charges { startDate endDate identifier aggregatedDetail {
        amount { amount currencyCode } totalAmount { amount currencyCode }
        amountPerUnit { amount currencyCode } amountPerUnitDelta { amount currencyCode }
        promotionAmount { amount currencyCode } taxAmount { amount currencyCode } quantity
      } } }
      ads { adTypeName charge {
        amount { amount currencyCode } totalAmount { amount currencyCode }
        amountPerUnit { amount currencyCode } promotionAmount { amount currencyCode }
        taxAmount { amount currencyCode } quantity
      } }
      netProceeds { total { amount currencyCode } perUnit { amount currencyCode } }
      cost {
        costOfGoodsSold { amount currencyCode } miscellaneousCost { amount currencyCode }
        fbaCost { shippingToAmazonCost { amount currencyCode } }
        mfnCost { fulfillmentCost { amount currencyCode } storageCost { amount currencyCode } }
      }
    }
  }
}'''
_ECONOMICS_TEMPLATES = {
    False: _ECONOMICS_QUERY.replace("__DATE__", "DAY").replace("__PRODUCT__", "MSKU"),
    # S66-T40 (lead, measured live 2026-09-25, window 2026-09-20..24): RANGE x MSKU equals the
    # sum of our DAY x MSKU rows to the cent (fees 38,009.94, net 38,474.335), while ANY
    # PARENT_ASIN grain carries 37.75 of fees Amazon attributes to no MSKU. The reconciliation
    # checks OUR date roll-up at the SAME product grain; comparing across grains refused a
    # correct transform.
    True: _ECONOMICS_QUERY.replace("__DATE__", "RANGE").replace("__PRODUCT__", "MSKU"),
}

#: ⚠ MUST MATCH `core.keychain.ENTRY_TYPES` OR `add_entry` 400s with a message about our data
#: structure on a screen about their Amazon account. That was the wave-31 Meta defect and the
#: comments in `keychain.py` warn about it in as many words.
ENTRY_TYPE = "amazon_sp"

#: Login With Amazon: the ONLY place a refresh token is exchanged. Not a regional endpoint.
LWA_TOKEN_URL = "https://api.amazon.com/auth/o2/token"

#: Regional SP-API hosts. Royal Imports is US, so North America is the default.
ENDPOINTS = {
    "na": "https://sellingpartnerapi-na.amazon.com",
    "eu": "https://sellingpartnerapi-eu.amazon.com",
    "fe": "https://sellingpartnerapi-fe.amazon.com",
}

#: ⭐ THE SANDBOX HOSTS, so the `Loopable Sandbox` app that ALREADY EXISTS is usable today.
#:
#: Owner ruling R9 created that app precisely so the connector could be built and proven while
#: identity verification is pending. Without these hosts its credentials would be sent to the
#: PRODUCTION endpoint and fail with an authorization error that looks like a bad credential rather
#: than a wrong host -- the most expensive kind of wrong answer.
#:
#: ⛔⛔ A SANDBOX CREDENTIAL IS FENCED OUT OF `sync`, AND THAT FENCE IS THE POINT. The sandbox
#: returns STATIC MOCK responses. Standing rule 8 forbids an unverifiable aggregate on a screen and
#: R3 requires reconciliation to Amazon's own summary; a mock figure satisfies neither, and mock
#: rows written into `ut_amzn_*` would be indistinguishable from real ones once they are in a grid.
#: So sandbox is allowed for the LIVENESS PROBE and for `--check`, and `amazon_store.sync` REFUSES
#: it by name. That is what makes the sandbox app useful without making it dangerous.
SANDBOX_ENDPOINTS = {
    "na": "https://sandbox.sellingpartnerapi-na.amazon.com",
    "eu": "https://sandbox.sellingpartnerapi-eu.amazon.com",
    "fe": "https://sandbox.sellingpartnerapi-fe.amazon.com",
}
DEFAULT_REGION = "na"

#: These paths are constants, not caller input. The outer Product Pricing request is POST, but
#: every request inside its batch is a fixed GET to the read-only item URI.
_COMPETITIVE_SUMMARY_BATCH_PATH = (
    "batches/products/pricing/2022-05-01/items/competitiveSummary")
_COMPETITIVE_SUMMARY_ITEM_URI = "/products/pricing/2022-05-01/items/competitiveSummary"
_COMPETITIVE_SUMMARY_INCLUDED = ("featuredBuyingOptions", "referencePrices")
_AWD_INVENTORY_PATH = "awd/2024-05-09/inventory"
_REPLENISHMENT_PATHS = {
    "getSellingPartnerMetrics": "replenishment/2022-11-07/sellingPartners/metrics/search",
    "listOfferMetrics": "replenishment/2022-11-07/offers/metrics/search",
}
REPLENISHMENT_EMPTY = "Amazon reports no Subscribe and Save offers for this seller"


def is_sandbox(fields):
    """Does this stored credential belong to a SANDBOX app? -> bool.

    ⚠ ONE READING, IN ONE PLACE. The probe, the request builder and the loader's refusal all ask
    this function rather than each testing the field themselves, because three spellings of
    "is this sandbox" is three chances for one of them to answer differently -- and the one that
    matters is the refusal.
    """
    v = (fields or {}).get("sandbox")
    return str(v).strip().lower() in ("1", "true", "yes", "on") if v is not None else False


def base_for(fields, region=None):
    """The SP-API host this credential should talk to. Sandbox or production, never a guess."""
    r = str(region or (fields or {}).get("region") or DEFAULT_REGION).lower()
    table = SANDBOX_ENDPOINTS if is_sandbox(fields) else ENDPOINTS
    return table.get(r)

#: US marketplace. Stored per credential; this is only the fallback for a probe.
US_MARKETPLACE_ID = "ATVPDKIKX0DER"

#: The five values an admin pastes. `refresh_token` is the secret; the other four are identifiers.
#: ⚠ `refresh_token` MUST also join `keychain._PREVIEW_FIELDS`, or the entry stores correctly and
#: renders a BLANK preview: nothing raises, and the only symptom is an empty cell on the screen the
#: feature exists for. Exactly the wave-31 `access_token` defect.
CREDENTIAL_FIELDS = ("client_id", "client_secret", "refresh_token", "seller_id", "marketplace_id")

#: ⚠ OPTIONAL, AND NOT ONE OF THE FIVE. `sandbox` is a DECLARATION about which app minted the
#: credential, not a secret and not something an admin must supply. Absent means production, which
#: is the safe default: a sandbox credential mistakenly left undeclared fails loudly against the
#: production host, whereas a production credential wrongly marked sandbox would quietly read mocks.
OPTIONAL_FIELDS = ("sandbox", "region")

SQP_ASIN_OPTION_MAX_CHARS = 200
SQP_PERIOD = ("MONTH", "WEEK")

#: ⭐ THE SCHEMA SPINE (owner rulings R4 + R14: seven tables, and NOTHING ELSE). Each row names
#: the table, the bulk report
#: type that fills it, and the summary aggregate its `validate()` reconciles against.
#:
#: ⭐⭐ R3 — `validate()` RECONCILES TO AMAZON'S OWN SUMMARY, not to Odoo. Standing rule 8 says a
#: number that does not tie to Odoo does not ship; settlements, FBA inventory and Brand Analytics
#: have no Odoo counterpart at all. The owner ruled the reconciliation is source-internal
#: (summary vs detail), because the bug class rule 8 exists to catch is OUR transformation, not
#: Amazon's arithmetic. That answer governs every API-only connector, not just this one.
#:
#: ⛔⛔ R12 — THESE ARE STANDALONE DATABASES. Owner, verbatim: *"We're not building a cross
#: source integration. Its all different. Assume that its a whole new databases which they
#: are."* So NOTHING here joins to Odoo: `listings` is not a bridge to `product_data`'s
#: `default_code`, no seller-SKU mapping table is built, and the hand-maintained ASIN
#: mastersheet is NOT retired by this connector. Amazon numbers are read, reconciled and
#: presented on Amazon's own terms.
#: ⭐ The consequence worth stating: this REMOVES the whole class of defect that
#: [[amazon-conversion-k-is-inverted]] describes, because no unit conversion between an Odoo
#: unit and an Amazon unit is ever performed.
#:
#: ⛔⛔ R14 — NO DASHBOARD, AND NO MODULE. Owner: *"this is just database from Amazon, all
#: its fields mapped into our app so it can be seen under Data module and later be pulled
#: into Sheet. All database connector has this exact flow."* We ship the data, not the
#: conclusion. ⭐ `sheet/BindingEditor.tsx:61` binds on `database.startsWith("ut_")`, so
#: `ut_amzn_*` is Sheet-bindable the moment it exists; that path needs no work.
#:
#: ⚠ `report` is `None` where no bulk report flavor is confirmed. That is O5 of the ideation
#: record and it is NOT a licence to page an entity endpoint quietly: an unconfirmed row must
#: either find its report or REPORT the limit with cause, per standing rule 1.
#:
#: `history` is Amazon's own history floor for a dated table, one of:
#:   {"rolling_days": N, "edge": "start"|"end", "evidence": str}: Amazon refuses a window whose
#:     start (or end) is older than now minus N days. The floor moves with the clock.
#:   {"from": "YYYY-MM-DD", "evidence": str}: Amazon serves nothing older than this date.
#:   {"seller_floor": False, "evidence": str}: brand-level data; the seller's first month does not
#:     bound it, so history walks back until Amazon refuses an older period.
#: A `from` rule also replaces the seller month, even when older. A rolling rule is max(seller, rule).
#: No `history` key: Amazon serves back to the seller's first data (`amazon_store.history_floor`).
REPORT_TYPES = {
    # ⭐⭐ R13 — BOTH ORDER REPORTS, BY ROLE. `report` seeds the one-time historical
    # backfill because BY_ORDER_DATE is stable and pages cleanly by period; `report_incremental`
    # drives every sync after, because BY_LAST_UPDATE is the ONLY one that returns orders whose
    # status changed after they were placed. ⛔ Refunds, cancellations and settlement
    # restatements all arrive as updates to OLD orders, so an order-date-only sync drifts away
    # from Amazon in the direction that flatters us, and standing rule 8 would only catch it later
    # against the settlement summary.
    "orders": {
        "report": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
        "report_incremental": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL",
        "validates_against": "order report totals vs our order rows",
        "role": "Inventory and Order Tracking",
    },
    "order_items": {
        "report": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL",
        "report_incremental": "GET_FLAT_FILE_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL",
        "validates_against": "order report line totals vs our item rows",
        "role": "Inventory and Order Tracking",
    },
    "listings": {
        "report": "GET_MERCHANT_LISTINGS_ALL_DATA",
        "snapshot": True,
        "validates_against": "listing report row count vs our listing rows",
        "role": "Product Listing",
    },
    # ⛔⛔ THE REPORT THIS ROW ORIGINALLY NAMED IS BEING **REMOVED ON 2026-11-11**.
    # `GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE` and `GET_V2_SETTLEMENT_REPORT_DATA_XML` are both
    # deprecated and deleted on that date; Amazon's named replacement is
    # `GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2`, which "offers the same information in fewer
    # columns and streamlined formatting" and is available NOW.
    # ⭐ CAUGHT BEFORE THE FIRST SYNC, WHICH IS THE ONLY REASON IT COST NOTHING: had we shipped on
    # the deprecated report, settlements would have worked, been reconciled, been trusted, and then
    # gone dark in November with no code change on our side to explain it.
    # ⚠ FEWER COLUMNS MEANS A DIFFERENT HEADER. This table is `measured_at_sync`, so the parser
    # reads whatever V2 actually sends and nothing here needs to know the column list -- which is
    # exactly the property that makes swapping the report type a one-line change.
    # · https://developer-docs.amazon.com/sp-api/docs/report-type-values-settlement
    # Amazon creates settlements on its own schedule and refuses createReport for them.
    # This type is a getReports discovery filter, never a requestable report flavor.
    "settlements": {
        "report_discover": "GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2",
        "validates_against": "settlement summary vs settlement lines",
        "role": "Finance and Accounting",
    },
    "inventory": {
        "report": "GET_LEDGER_SUMMARY_VIEW_DATA",
        "snapshot": True,
        "dated_snapshot": True,
        "options": {"aggregateByTimePeriod": "DAILY", "aggregateByLocation": "COUNTRY"},
        "entity_read": "AWD v2024-05-09 listInventory (all 200-row pages)",
        "validates_against": "FBA ledger summary vs detail and AWD API items vs stored AWD rows",
        "role": "Amazon Fulfillment / Amazon Warehousing and Distribution",
    },
    # ⛔⛔ O5 IS CLOSED AND THE ANSWER IS NO (researched 2026-09-04). All 101 report types were
    # enumerated and ZERO contain BUYBOX, PRICING, PRICE or COMPETITIVE. So this table SPLITS:
    #   Buy Box SHARE  -> GET_SALES_AND_TRAFFIC_REPORT.salesAndTrafficByAsin.buyBoxPercentage,
    #                     which IS bulk. ⚠ needs the Brand Analytics role, the same one R5 marks
    #                     UNPROVEN, so this row inherits that risk.
    #   Buy Box PRICE  -> Product Pricing entity endpoints ONLY. No bulk path exists.
    # ⛔ STANDING RULE 1'S SECOND HALF: the ceiling is Amazon's and cannot be removed, so it is
    # REPORTED here with its cause and its fix. Best path is Product Pricing v2022-05-01
    # `getCompetitiveSummary` (featured buying options + competitive price threshold): batch 20,
    # rate 0.033/sec, burst 1 — about 40 ASINs per minute.
    # ⭐ So the ticket ships SHARE from the bulk report as this table's spine, and PRICE as an
    # explicitly rate-limited enrichment that names its own ceiling on screen. A silent per-ASIN
    # page loop over a full catalogue is precisely what rule 1 forbids.
    "pricing": {
        "report": "GET_SALES_AND_TRAFFIC_REPORT",
        "history": {"rolling_days": 730, "edge": "start",
                    "evidence": "CANCELLED, Amazon's no data answer, for 2021-09, 2023-01 and 2024-11 (start 743 days "
                                "back, 17,584 orders that month); DONE with rows 2024-12 (start 713 days back), 2025-05, "
                                "2025-11 (2026-11-14)"},
        "json_root": "salesAndTrafficByAsin",
        "report_covers": "buy box SHARE only; PRICE has no bulk path",
        "price_path": "Product Pricing v2022-05-01 getCompetitiveSummary (batch 20, 0.033/sec)",
        "validates_against": "sales and traffic report totals and competitive ASIN responses",
        "role": "Pricing + Brand Analytics",
    },
    "brand_analytics": {
        # ⚠ Returns data only for Brand Registry brand owners (owner ruling R5). Carried as the
        # wave's one UNPROVEN ticket with its exit condition written in advance: returns >0 rows
        # for any registered brand, else demote to a declared-but-unsynced stub.
        # R18 (SDLC 78): one completed Sunday to Saturday WEEK per window. A first load takes the
        # latest week only; older weeks keep watched terms only (amazon_store.write_week).
        "report": "GET_BRAND_ANALYTICS_SEARCH_TERMS_REPORT",
        "weekly": True, "period": "WEEK",
        "history": {"from": "2025-08-10",
                    "evidence": "Weekly FATAL, the period may fall outside the available data range, for the weeks "
                                "of 2021-09-05, 2023-11-05, 2024-11-03, 2025-03-30, 2025-06-29 and 2025-08-03; DONE with "
                                "rows 2025-10-05, 2026-04-05 and 2026-07-05 (2026-11-14). The weeks between stop at "
                                "Amazon's first refusal. Search terms cover the marketplace, not the seller"},
        "json_root": "dataByDepartmentAndSearchTerm",
        "validates_against": "report period totals vs our search-term rows",
        "role": "Brand Analytics",
    },
    "economics": {
        "api": "createQuery",
        "validates_against": "DAY x MSKU sales, fees and net proceeds vs Amazon RANGE x MSKU totals per currency",
        "role": "Selling Partner Insights",
        "history": {"rolling_days": 730, "edge": "start",
                    "evidence": "Data Kiosk FATAL: Start date must be no more than two years ago (2026-11-14)"},
    },
    "transactions": {
        "api": "listTransactions",
        "validates_against": "Amazon transaction count and totalAmount per currency vs stored items, and breakdowns vs transaction totals",
        "role": "Finance and Accounting",
        "history": {"rolling_days": 730, "edge": "start",
                    "evidence": "listTransactions 400: Start date cannot be before 2 years from now (2026-11-14)"},
    },
    # snapshot forbids dataStartTime/dataEndTime; min_interval_s is a successful
    # refresh floor (also enforced on manual sync). Monthly history is separate.
    "fba_fee_estimates": {
        "report": "GET_FBA_ESTIMATED_FBA_FEES_TXT_DATA", "snapshot": True,
        "min_interval_s": 86400,
        "validates_against": "Amazon document data-row count vs stored rows for its latest snapshot date",
        "role": "Amazon Fulfillment",
    },
    "referral_fees": {
        "report": "GET_REFERRAL_FEE_PREVIEW_REPORT", "snapshot": True,
        "min_interval_s": 86400,
        "validates_against": "Amazon document data-row count vs stored rows for its latest snapshot date",
        "role": "Finance and Accounting",
    },
    "storage_fees": {
        "report": "GET_FBA_STORAGE_FEE_CHARGES_DATA", "monthly": True,
        "min_interval_s": 86400,
        "validates_against": "Amazon document data-row count vs stored rows for its latest calendar month",
        "role": "Amazon Fulfillment",
    },
    "search_query_performance": {
        "report": "GET_BRAND_ANALYTICS_SEARCH_QUERY_PERFORMANCE_REPORT",
        "history": {"from": "2025-04-01",
                    "evidence": "Monthly FATAL, the period may fall outside the available data range, for 2021-09, "
                                "2024-10, 2024-11, 2025-01 and 2025-03; 2025-04 onward landed (2026-11-14)",
                    "periods": {"WEEK": {"from": "2025-07-13", "provisional": True,
                                         "evidence": "2026-11-14 probe refused 2025-07-06 and served 2025-10-05. "
                                                     "The intervening twelve weeks are unasked. 2025-07-13 is the "
                                                     "first unasked Sunday, not a proved earliest served floor"}}},
        "role": "Brand Analytics",
        "validates_against": "Amazon dataByAsin row count and ASIN purchases per batch vs stored rows for the latest month",
        "json_root": "dataByAsin", "monthly": True,
        "period": "MONTH", "periods": SQP_PERIOD,
        "asin_option_max_chars": SQP_ASIN_OPTION_MAX_CHARS,
    },
}

# S66-T42: inventory sections 2.2 and 2.3. Fields are measured at sync, including
# JSON documents. Row roots were read from amzn/selling-partner-api-models/schemas/reports
# on 2026-09-25 at commit 713565ff394d136629a342120872e65cb073d162.
# json_schema names the public source, without changing the pinned proto.
GROUP_A_TABLES = {
    "long_term_storage_fees": {
        "label": "Amazon long term storage fees",
        "report": "GET_FBA_FULFILLMENT_LONGTERM_STORAGE_FEE_CHARGES_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Complete calendar months; refresh no sooner than 14400 seconds.",
        "monthly": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "storage_overage_fees": {
        "label": "Amazon storage overage fees",
        "report": "GET_FBA_OVERAGE_FEE_CHARGES_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Complete calendar months; refresh no sooner than 14400 seconds.",
        "monthly": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "reimbursements": {
        "label": "Amazon reimbursements",
        "report": "GET_FBA_REIMBURSEMENTS_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "restatement_keys": ("reimbursement_id",),
        "cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "fba_customer_returns": {
        "label": "Amazon FBA customer returns",
        "report": "GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "restatement_keys": ("order_id", "sku", "fnsku", "asin", "return_date"),
        "cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "replacements": {
        "label": "Amazon replacements",
        "report": "GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_REPLACEMENT_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "fba_shipped_sales": {
        "label": "Amazon FBA shipped sales",
        "report": "GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_SALES_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "fba_shipment_promotions": {
        "label": "Amazon FBA shipment promotions",
        "report": "GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_PROMOTION_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "inventory_ledger_detail": {
        "label": "Amazon inventory ledger detail",
        "report": "GET_LEDGER_DETAIL_VIEW_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "inventory_planning": {
        "label": "Amazon inventory planning",
        "report": "GET_FBA_INVENTORY_PLANNING_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "manage_inventory": {
        "label": "Amazon manage inventory",
        "report": "GET_FBA_MYI_UNSUPPRESSED_INVENTORY_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "reserved_inventory": {
        "label": "Amazon reserved inventory",
        "report": "GET_RESERVED_INVENTORY_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "restock_recommendations": {
        "label": "Amazon restock recommendations",
        "report": "GET_RESTOCK_INVENTORY_RECOMMENDATIONS_REPORT",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "stranded_inventory": {
        "label": "Amazon stranded inventory",
        "report": "GET_STRANDED_INVENTORY_UI_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "inbound_noncompliance": {
        "label": "Amazon inbound noncompliance",
        "report": "GET_FBA_FULFILLMENT_INBOUND_NONCOMPLIANCE_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "inventory_expiration_dates": {
        "label": "Amazon inventory expiration dates",
        "report": "GET_FBA_FULFILLMENT_INVENTORY_EXPIRATION_DATE_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "recommended_removals": {
        "label": "Amazon recommended removals",
        "report": "GET_FBA_RECOMMENDED_REMOVAL_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "removal_orders": {
        "label": "Amazon removal orders",
        "report": "GET_FBA_FULFILLMENT_REMOVAL_ORDER_DETAIL_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "removal_shipments": {
        "label": "Amazon removal shipments",
        "report": "GET_FBA_FULFILLMENT_REMOVAL_SHIPMENT_DETAIL_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "subscribe_save_forecast": {
        "label": "Amazon Subscribe and Save forecast",
        "report": "GET_FBA_SNS_FORECAST_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "subscribe_save_performance": {
        "label": "Amazon Subscribe and Save performance",
        "report": "GET_FBA_SNS_PERFORMANCE_DATA",
        "role": "Amazon Fulfillment",
        "min_interval_s": 14400,
        "cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "remote_fulfillment_eligibility": {
        "label": "Amazon remote fulfillment eligibility",
        "report": "GET_REMOTE_FULFILLMENT_ELIGIBILITY",
        "role": "Amazon Fulfillment",
        "min_interval_s": 86400,
        "cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "search_catalog_performance": {
        "label": "Amazon search catalog performance",
        "report": "GET_BRAND_ANALYTICS_SEARCH_CATALOG_PERFORMANCE_REPORT",
        "role": "Brand Analytics",
        "history": {"rolling_days": 730, "edge": "end",
                    "evidence": "FATAL, the period may fall outside the available data range, for 2024-10 (end 744 "
                                "days back) and every month probed back to 2021-09; DONE with rows 2024-11 (end 714 days "
                                "back), 2025-03, 2025-04 (2026-11-14)"},
        "min_interval_s": 86400,
        "cadence_note": "Complete calendar months; refresh no sooner than 86400 seconds.",
        "monthly": True,
        "json_root": "dataByAsin",
        "json_schema": "sellingPartnerSearchCatalogPerformanceReport.json",
        "period": "MONTH",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "market_basket": {
        "label": "Amazon market basket",
        "report": "GET_BRAND_ANALYTICS_MARKET_BASKET_REPORT",
        "role": "Brand Analytics",
        "history": {"from": "2019-08-01",
                    "evidence": "DONE with rows 2020-01, 2020-07 and 2021-07 (before the seller's first order "
                                "2021-08); DONE empty 2019-07 (2026-11-14)"},
        "min_interval_s": 86400,
        "cadence_note": "Complete calendar months; refresh no sooner than 86400 seconds.",
        "monthly": True,
        "json_root": "dataByAsin",
        "json_schema": "sellingPartnerMarketBasketAnalysisReport.json",
        "period": "MONTH",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "repeat_purchase": {
        "label": "Amazon repeat purchase",
        "report": "GET_BRAND_ANALYTICS_REPEAT_PURCHASE_REPORT",
        "role": "Brand Analytics",
        "history": {"from": "2023-02-01",
                    "evidence": "FATAL, the period may fall outside the available data range, for 2021-09 and 2023-01; "
                                "DONE with rows 2024-10, 2024-11, 2025-03, 2025-04 (2026-11-14). The months between "
                                "stop at Amazon's first refusal"},
        "min_interval_s": 86400,
        "cadence_note": "Complete calendar months; refresh no sooner than 86400 seconds.",
        "monthly": True,
        "json_root": "dataByAsin",
        "json_schema": "sellingPartnerRepeatPurchaseReport.json",
        "period": "MONTH",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "promotion_performance": {
        "label": "Amazon promotion performance",
        "report": "GET_PROMOTION_PERFORMANCE_REPORT",
        "role": "Selling Partner Insights",
        "history": {"rolling_days": 730, "edge": "start",
                    "evidence": "FATAL: Requests with a promotionStartDateFrom of more than two years ago are not "
                                "supported (2021-09 window, 2026-11-14)"},
        "min_interval_s": 86400,
        "cadence_note": "Date windows; refresh no sooner than 86400 seconds.",
        "json_root": "promotions",
        "json_schema": "promotionReport.json",
        "date_options": ["promotionStartDateFrom","promotionStartDateTo"],
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "coupon_performance": {
        "label": "Amazon coupon performance",
        "report": "GET_COUPON_PERFORMANCE_REPORT",
        "role": "Brand Analytics",
        "history": {"rolling_days": 730, "edge": "start",
                    "evidence": "FATAL: Requests with a couponStartDateFrom of more than two years ago are not "
                                "supported (2021-09 window, 2026-11-14)"},
        "min_interval_s": 86400,
        "cadence_note": "Date windows; refresh no sooner than 86400 seconds.",
        "json_root": "coupons",
        "json_schema": "sellerCouponReport.json",
        "date_options": ["couponStartDateFrom","couponStartDateTo"],
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "account_health": {
        "label": "Amazon account health",
        "report": "GET_V2_SELLER_PERFORMANCE_REPORT",
        "role": "Selling Partner Insights",
        "min_interval_s": 43200,
        "cadence_note": "Current snapshot; refresh no sooner than 43200 seconds.",
        "snapshot": True,
        "json_root": "performanceMetrics",
        "json_schema": "accountHealthReport-2020-11-18.json",
        "json_extra_roots": ["accountStatuses"],
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "inactive_listings": {
        "label": "Amazon inactive listings",
        "report": "GET_MERCHANT_LISTINGS_INACTIVE_DATA",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "cancelled_listings": {
        "label": "Amazon cancelled listings",
        "report": "GET_MERCHANT_CANCELLED_LISTINGS_DATA",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "suppressed_listings": {
        "label": "Amazon suppressed listings",
        "report": "GET_MERCHANTS_LISTINGS_FYP_REPORT",
        "role": "Product Listing",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "listing_defects": {
        "label": "Amazon listing defects",
        "report": "GET_MERCHANT_LISTINGS_DEFECT_DATA",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "sold_listings": {
        "label": "Amazon sold listings",
        "report": "GET_CONVERGED_FLAT_FILE_SOLD_LISTINGS_DATA",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "mfn_returns": {
        "label": "Amazon MFN returns",
        "report": "GET_FLAT_FILE_RETURNS_DATA_BY_RETURN_DATE",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 14400,
        "restatement_keys": ("order_id", "sku", "return_request_date"),
        "cadence_note": "Date windows; refresh no sooner than 14400 seconds.",
        "max_window_days": 60,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "b2b_recommended": {
        "label": "Amazon B2B product opportunities",
        "report": "GET_B2B_PRODUCT_OPPORTUNITIES_RECOMMENDED_FOR_YOU",
        "role": "Product Listing",
        "min_interval_s": 604800,
        "cadence_note": "Current snapshot; refresh no sooner than 604800 seconds.",
        "snapshot": True,
        "json_root": "recommendations",
        "json_schema": "b2bProductOpportunitiesRecommendedForYouReport-2020-11-19.json",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "b2b_not_yet_on_amazon": {
        "label": "Amazon B2B products not yet on Amazon",
        "report": "GET_B2B_PRODUCT_OPPORTUNITIES_NOT_YET_ON_AMAZON",
        "role": "Product Listing",
        "min_interval_s": 604800,
        "cadence_note": "Current snapshot; refresh no sooner than 604800 seconds.",
        "snapshot": True,
        "json_root": "recommendations",
        "json_schema": "b2bProductOpportunitiesNotYetOnAmazonReport-2020-11-19.json",
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "geo_opportunities": {
        "label": "Amazon geo opportunities",
        "report": "GET_FLAT_FILE_GEO_OPPORTUNITIES",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 86400,
        "cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "out_of_stock_mfn": {
        "label": "Amazon out of stock MFN listings",
        "report": "GET_OUT_OF_STOCK_MFN_INFORMATION",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 14400,
        "cadence_note": "Current snapshot; refresh no sooner than 14400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "b2b_quotes": {
        "label": "Amazon B2B quantity discounts",
        "report": "RFQD_BULK_DOWNLOAD",
        "role": "Product Listing",
        "min_interval_s": 86400,
        "cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "fee_discounts": {
        "label": "Amazon fee discounts",
        "report": "FEE_DISCOUNTS_REPORT",
        "role": "Product Listing",
        "min_interval_s": 86400,
        "cadence_note": "Current snapshot; refresh no sooner than 86400 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "order_metrics": {
        "label": "Amazon order metrics",
        "api": "getOrderMetrics",
        "role": "Inventory and Order Tracking",
        "min_interval_s": 1800,
        "cadence_note": "Date windows; refresh no sooner than 1800 seconds.",
        "validates_against": "Amazon daily order, unit and sales totals vs stored metrics; order counts independently reconcile orders",
    },
    "fba_inventory": {
        "label": "Amazon FBA inventory summaries",
        "api": "getInventorySummaries",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "listing_items": {
        "label": "Amazon listing status and issues",
        "api": "searchListingsItems",
        "role": "Product Listing",
        "min_interval_s": 1800,
        "cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "catalog_items": {
        "label": "Amazon catalog attributes",
        "api": "searchCatalogItems",
        "role": "Product Listing",
        "min_interval_s": 1800,
        "cadence_note": "Current snapshot; refresh no sooner than 1800 seconds.",
        "snapshot": True,
        "validates_against": "Amazon document or API data-row count vs stored rows for the latest period",
    },
    "fee_estimates_api": {
        "label": "Amazon per-price fee estimates",
        "api": "getMyFeesEstimates",
        "role": "Pricing",
        "min_interval_s": 1800,
        "cadence_note": "Per-price snapshot; batches of 20 at 0.5 requests per second with a burst of one.",
        "snapshot": True,
        "validates_against": "Amazon returned estimate count vs stored distinct estimates for the latest batch",
    },
    "outbound_fulfillment": {
        "label": "Amazon outbound fulfillment orders",
        "api": "listAllFulfillmentOrders",
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Current multi-channel order snapshot; every page and order's items are read at two requests per second.",
        "snapshot": True,
        "validates_against": "Amazon returned order item count and quantities vs stored outbound fulfillment items",
    },
    "inbound_shipments": {
        "label": "Amazon inbound shipments",
        "api": "listInboundPlans",
        "operations": ("listInboundPlans", "getInboundPlan", "listShipmentItems"),
        "role": "Amazon Fulfillment",
        "min_interval_s": 1800,
        "cadence_note": "Current FBA shipment item snapshot; every plan and item page at two requests per second per operation.",
        "snapshot": True,
        "validates_against": "Independently counted Amazon shipment items and quantities vs stored items for every latest plan and shipment",
    },
    "replenishment": {
        "label": "Amazon replenishment metrics",
        "api": "getSellingPartnerMetrics",
        "operations": ("getSellingPartnerMetrics", "listOfferMetrics"),
        "role": "Brand Analytics",
        "min_interval_s": 86400,
        "cadence_note": "Latest complete month snapshot; every offer page at one request per second per operation.",
        "snapshot": True,
        "validates_against": "Amazon raw seller metric count and total offer metrics vs stored replenishment rows",
    },
    "review_topics": {
        "label": "Amazon review topics",
        "api": "getItemReviewTopics",
        "role": "Brand Analytics / Selling Partner Insights",
        "role_match": "any",
        "min_interval_s": 7 * 86400,
        "cadence_note": "Amazon refreshes English review topics weekly in US, UK, France, Italy, Germany, Spain and Japan. Every listing ASIN is requested.",
        "snapshot": True,
        "validates_against": "Amazon returned positive and negative topic counts per ASIN vs stored topics for the same pass",
    },
    "review_trends": {
        "label": "Amazon review trends",
        "api": "getItemReviewTrends",
        "role": "Brand Analytics / Selling Partner Insights",
        "role_match": "any",
        "min_interval_s": 7 * 86400,
        "cadence_note": "Amazon refreshes six months of English review trends weekly in US, UK, France, Italy, Germany, Spain and Japan. Every listing ASIN is requested.",
        "snapshot": True,
        "validates_against": "Amazon raw trend point counts and occurrence percentages per ASIN, sentiment, topic and month vs stored rows for the same pass",
    },
    "browse_node_review_topics": {
        "label": "Amazon category review topics",
        "api": "getBrowseNodeReviewTopics",
        "role": "Brand Analytics / Selling Partner Insights",
        "role_match": "any",
        "min_interval_s": 7 * 86400,
        "cadence_note": "Amazon refreshes the top 10 positive and negative category topics weekly. Every browse node of every active child ASIN is requested, sorted by mentions and by star rating impact.",
        "snapshot": True,
        "validates_against": "Amazon raw positive and negative topic counts and metrics per browse node and sort vs stored topics for the same pass",
    },
}
REPORT_TYPES.update(GROUP_A_TABLES)

# These are visible declarations, never enablement keys or request allow-list entries.
DECLARED_DATASETS = {
    "browse_node_return_topics": {
        "label": "Amazon browse node return topics",
        "operations": ["getBrowseNodeReturnTopics", "getBrowseNodeReturnTrends"],
        "role": "Brand Analytics / Selling Partner Insights",
        "role_match": "any",
        "cadence_note": "Not requested by this connector.",
        "reason": "Browse node return topics and trends describe category returns, not item review trends. Their readers are not built in this release.",
    },
    "manage_inventory_variants": {
        "label": "Amazon manage inventory alternatives",
        "report_types": ["GET_FBA_MYI_ALL_INVENTORY_DATA","GET_AFN_INVENTORY_DATA"],
        "role": "Amazon Fulfillment",
        "cadence_note": "Not requested by this connector.",
        "reason": "The connector uses the unsuppressed manage inventory report for this dataset.",
    },
    "stranded_inventory_loader": {
        "label": "Amazon stranded inventory loader",
        "report_types": ["GET_STRANDED_INVENTORY_LOADER_DATA"],
        "role": "Amazon Fulfillment",
        "cadence_note": "Not requested by this connector.",
        "reason": "The connector uses the stranded inventory UI report for this dataset.",
    },
    "listing_variants": {
        "label": "Amazon listing report variants",
        "report_types": ["GET_MERCHANT_LISTINGS_DATA","GET_MERCHANT_LISTINGS_DATA_BACK_COMPAT","GET_MERCHANT_LISTINGS_DATA_LITE","GET_MERCHANT_LISTINGS_DATA_LITER","GET_FLAT_FILE_OPEN_LISTINGS_DATA"],
        "role": "Product Listing",
        "cadence_note": "Not requested by this connector.",
        "reason": "These listing variants overlap Amazon listings, which reads the all listings report.",
    },
    "pending_orders": {
        "label": "Amazon pending order reports",
        "report_types": ["GET_FLAT_FILE_PENDING_ORDERS_DATA","GET_PENDING_ORDERS_DATA","GET_CONVERGED_FLAT_FILE_PENDING_ORDERS_DATA"],
        "role": "Inventory and Order Tracking",
        "cadence_note": "Not requested by this connector.",
        "reason": "Pending orders are covered by Amazon orders.",
    },
    "archived_orders": {
        "label": "Amazon archived orders",
        "report_types": ["GET_FLAT_FILE_ARCHIVED_ORDERS_DATA_BY_ORDER_DATE"],
        "role": "Inventory and Order Tracking",
        "cadence_note": "Not requested by this connector.",
        "reason": "Archived orders before the normal history window are not built in this release.",
    },
    "xml_orders": {
        "label": "Amazon XML order reports",
        "report_types": ["GET_XML_ALL_ORDERS_DATA_BY_ORDER_DATE_GENERAL","GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_GENERAL"],
        "role": "Inventory and Order Tracking",
        "cadence_note": "Not requested by this connector.",
        "reason": "The XML order reports duplicate the flat file reports used by Amazon orders.",
    },
    "mfn_return_variants": {
        "label": "Amazon MFN return report variants",
        "report_types": ["GET_CSV_MFN_PRIME_RETURNS_REPORT","GET_XML_MFN_PRIME_RETURNS_REPORT","GET_FLAT_FILE_MFN_SKU_RETURN_ATTRIBUTES_REPORT","GET_XML_MFN_SKU_RETURN_ATTRIBUTES_REPORT"],
        "role": "Inventory and Order Tracking",
        "cadence_note": "Not requested by this connector.",
        "reason": "Prime return, return attribute and attribute feed record variants are not built; Amazon MFN returns reads returns by return date.",
    },
    "browse_tree": {
        "label": "Amazon browse tree",
        "report_types": ["GET_XML_BROWSE_TREE_DATA"],
        "role": "Product Listing",
        "cadence_note": "Not requested by this connector.",
        "reason": "The XML browse tree is category reference data and is not built in this release.",
    },
    "sales_traffic_kiosk": {
        "label": "Amazon sales and traffic query",
        "operations": ["analytics_salesAndTraffic_2024_04_24"],
        "role": "Brand Analytics",
        "cadence_note": "Not requested by this connector.",
        "reason": "Same rows as Amazon pricing and Buy Box, which reads the report twin.",
    },
    "financial_events": {
        "label": "Amazon legacy financial events",
        "operations": ["listFinancialEvents","listFinancialEventGroups"],
        "role": "Finance and Accounting",
        "cadence_note": "Not requested by this connector.",
        "reason": "Superseded by Amazon financial transactions.",
    },
    "payouts": {
        "label": "Amazon payouts",
        "operations": ["listPayouts","listExpectedPayouts"],
        "role": "Finance and Accounting",
        "cadence_note": "Not requested by this connector.",
        "reason": "Payout timing from the Transfers API is not built in this release.",
    },
    # C7: the daily rival job reads offers outside the sync pass, so the sync requests nothing here.
    "offer_prices": {
        "label": "Amazon offer prices",
        "operations": ["getItemOffersBatch"],
        "role": "Pricing",
        "cadence_note": "Read once a day by the rival job, outside the sync pass.",
        "reason": "The daily rival job reads offer prices through getItemOffersBatch. The sync does not request them.",
    },
    "promotions": {
        "label": "Amazon promotion calendar",
        "operations": ["searchPromotions","getPromotion"],
        "role": "Pricing",
        "cadence_note": "Not requested by this connector.",
        "reason": "The Promotions API calendar is not built in this release; promotion results are in Amazon promotion performance.",
    },
    "aplus_content": {
        "label": "Amazon A plus content",
        "operations": ["searchContentDocuments"],
        "role": "Brand Analytics",
        "cadence_note": "Not requested by this connector.",
        "reason": "A plus content reference data is not built in this release.",
    },
    "listing_restrictions": {
        "label": "Amazon listing restrictions",
        "operations": ["getListingsRestrictions"],
        "role": "Product Listing",
        "cadence_note": "Not requested by this connector.",
        "reason": "Listing restriction reference data is not built in this release.",
    },
    "product_types": {
        "label": "Amazon product type definitions",
        "operations": ["searchDefinitionsProductTypes","getDefinitionsProductType"],
        "role": "Product Listing",
        "cadence_note": "Not requested by this connector.",
        "reason": "Product type definition reference data is not built in this release.",
    },
    "supply_sources": {
        "label": "Amazon supply sources",
        "operations": ["getSupplySources"],
        "role": "Selling Partner Insights",
        "cadence_note": "Not requested by this connector.",
        "reason": "Supply source reference data is not built in this release.",
    },
}

# Include the existing seven base tables and T40/T41 datasets in the same inventory.
GROUP_A = {
    key: {"key": key, "label": spec.get("label") or "Amazon " + key.replace("_", " "),
          "report_types": tuple(spec[k] for k in ("report", "report_incremental", "report_discover") if spec.get(k)),
          "operation": spec.get("api"), "role": spec["role"],
          **({"operations": tuple(spec["operations"])} if spec.get("operations") else {}),
          "cadence_note": spec.get("cadence_note") or "Uses the existing connector cadence."}
    for key, spec in REPORT_TYPES.items()
}
GROUP_A.update({key: {"key": key, **spec} for key, spec in DECLARED_DATASETS.items()})


# Source: AutoWiki/research/datadoe-sync-cadence.md. Unlisted tables keep the daily default.
CADENCE = {
    table: {"perDay": 1, "lookbackDays": 1, "intradayLookbackDays": 1, "period": "day"}
    for table in GROUP_A
}
for _table, _spec in REPORT_TYPES.items():
    if _spec.get("monthly") or _spec.get("period") == "MONTH":
        CADENCE[_table].update(period="month", lookbackDays=60, intradayLookbackDays=60)
    elif _spec.get("weekly") or _spec.get("min_interval_s", 0) >= 7 * 86400:
        CADENCE[_table].update(period="week", lookbackDays=14, intradayLookbackDays=14)
for _tables, _passes, _daily, _intraday in (
    (("orders", "order_items"), 6, 8, 1),
    (("settlements", "transactions"), 3, 8, 2),
    (("listings", "inventory_planning"), 4, 1, 1),
    (("account_health", "manage_inventory", "restock_recommendations"), 2, 1, 1),
    (("pricing", "fba_fee_estimates", "referral_fees"), 1, 4, 4),
    (("reimbursements", "long_term_storage_fees"), 1, 30, 30),
    (("fba_customer_returns", "mfn_returns"), 1, 60, 60),
    (("storage_fees",), 1, 1, 1),
):
    for _table in _tables:
        CADENCE[_table].update(perDay=_passes, lookbackDays=_daily,
                               intradayLookbackDays=_intraday, period="day")

# Ads uses namespaced mirror marker names, so its tables cannot collide with SP-API tables.
from harness import amazon_ads_schema as _ads_schema

CADENCE.update({
    "ads_" + table: {"perDay": 4, "lookbackDays": 60, "intradayLookbackDays": 5, "period": "day"}
    for table in _ads_schema.TABLE_SPECS
})
del _table, _tables, _spec, _passes, _daily, _intraday, _ads_schema


# Inventory section 2.5: immutable refusal even if a future report roster admits one.
EXCLUDED_REPORT_TYPES = frozenset({
    "GET_ORDER_REPORT_DATA_SHIPPING", "GET_ORDER_REPORT_DATA_TAX", "GET_ORDER_REPORT_DATA_ALL",
    "GET_FLAT_FILE_ORDER_REPORT_DATA_SHIPPING", "GET_FLAT_FILE_ORDER_REPORT_DATA_TAX",
    "GET_FLAT_FILE_ORDERS_RECONCILIATION_DATA_SHIPPING", "GET_FLAT_FILE_ORDERS_RECONCILIATION_DATA_TAX",
    "GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_SHIPPING", "GET_ORDERS_DATA",
    "GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_ALL", "GET_AMAZON_FULFILLED_SHIPMENTS_DATA_TAX",
    "GET_FLAT_FILE_SALES_TAX_DATA", "GET_FLAT_FILE_VAT_INVOICE_DATA_REPORT",
    "GET_XML_VAT_INVOICE_DATA_REPORT", "GET_VAT_TRANSACTION_DATA",
    "GET_GST_MTR_B2B_CUSTOM", "GET_GST_MTR_B2C_CUSTOM", "GET_EASYSHIP_DOCUMENTS",
    "GET_EASYSHIP_DOCUMENTS_PICKEDUP", "GET_EASYSHIP_DOCUMENTS_WAITING_FOR_PICKUP",
    "GET_MONTHLY_WARRANTIES", "WARRANTY_BASE_ITEM_INFO",
    "GET_AMAZON_FULFILLED_SHIPMENTS_DATA_GENERAL", "GET_SELLER_FEEDBACK_DATA",
})

#: Eight of the ten roles Amazon approved on 2026-07-22. Buyer Communication and Buyer Solicitation
#: are REFUSED (owner ruling R7): both are write-shaped and PII-bearing, and it is precisely those
#: restricted roles that trigger Phase 1 verification, a Phase 2 data-security assessment and an
#: architecture review over screen share at developer registration.
#: · https://developer-docs.amazon.com/sp-api/docs/register-as-a-public-developer
ROLES_TAKEN = (
    "Inventory and Order Tracking", "Amazon Fulfillment",
    "Amazon Warehousing and Distribution", "Finance and Accounting",
    "Pricing", "Product Listing", "Brand Analytics", "Selling Partner Insights",
)
ROLES_REFUSED = ("Buyer Communication", "Buyer Solicitation")

NOTIFICATIONS_SCOPE = "sellingpartnerapi::notifications"
# Destination support: https://developer-docs.amazon.com/sp-api/docs/notification-type-values
NOTIFICATION_TYPES = {
    # The report example uses 2020-09-04 despite the page's schema prose saying 1.0.
    "REPORT_PROCESSING_FINISHED": {
        "roles": ROLES_TAKEN, "payload_version": "2020-09-04", "destinations": ("SQS",)},
    "FBA_INVENTORY_AVAILABILITY_CHANGES": {
        "roles": ("Amazon Fulfillment",), "payload_version": "1.0", "table": "inventory",
        "destinations": ("SQS",)},
    "LISTINGS_ITEM_STATUS_CHANGE": {
        "roles": ("Product Listing",), "payload_version": "1.0", "table": "listings",
        "destinations": ("EventBridge",)},
    "BRANDED_ITEM_CONTENT_CHANGE": {
        "roles": ("Product Listing",), "payload_version": "1.0", "table": "listings",
        "destinations": ("EventBridge",), "requires_brand_owner": True},
    "ANY_OFFER_CHANGED": {
        "roles": ("Pricing",), "payload_version": "1.0", "table": "pricing",
        "destinations": ("SQS",)},
}
_NOTIFICATION_DESTINATIONS_PATH = "notifications/v1/destinations"
_NOTIFICATION_SUBSCRIPTIONS_PATH = "notifications/v1/subscriptions"

#: W59-T39: the connector's approved operation scope, not Amazon's entire role catalogue.
#: Join the report roster rather than maintaining another copy of its role labels. A compound
#: label describes TWO data legs: inventory uses Fulfillment for its report and AWD for its
#: entity read; pricing uses Brand Analytics for its report and Pricing for its entity read.
#: Keep those source labels intact and expose both roles, without granting either entity role
#: the other role's report access.
REPORT_ROLES = {
    table: tuple(spec["role"].replace(" / ", " + ").split(" + "))
    for table, spec in REPORT_TYPES.items()
}
_REPORT_ROLE_INDEX = {"inventory": 0, "pricing": 1}
_BULK_REPORT_ROLES = tuple(dict.fromkeys(
    roles[_REPORT_ROLE_INDEX.get(table, 0)] for table, roles in REPORT_ROLES.items()
    if REPORT_TYPES[table].get("report") or REPORT_TYPES[table].get("report_discover")))
_APPROVED_REPORT_TYPES = tuple(dict.fromkeys(
    spec[key] for spec in REPORT_TYPES.values() for key in ("report", "report_incremental")
    if spec.get(key)))

#: Exact method/path pairs. Braced ids match ONE opaque path segment, never a suffix, query,
#: escaped slash or traversal. POSTs generate reports, queries or fees, or wrap fixed read-only GETs.
#: LWA, presigned documents and the schema module's public GitHub refresh are not SP-API
#: operations. The gate enumerates those transports separately; they confer no operation scope.
OPERATIONS = {
    "createReport": {
        "name": "createReport", "roles": _BULK_REPORT_ROLES, "method": "POST",
        "path": "reports/2021-06-30/reports", "report_types": _APPROVED_REPORT_TYPES,
    },
    # Discovery is approved only for Amazon-issued settlements and their finance role.
    # Sharing the Reports path grants neither the other bulk types nor their roles.
    "getReports": {
        "name": "getReports", "roles": ("Finance and Accounting",), "method": "GET",
        "path": "reports/2021-06-30/reports",
        "report_types": (REPORT_TYPES["settlements"]["report_discover"],),
    },
    "getReport": {
        "name": "getReport", "roles": _BULK_REPORT_ROLES, "method": "GET",
        "path": "reports/2021-06-30/reports/{reportId}",
    },
    "getReportDocument": {
        "name": "getReportDocument", "roles": _BULK_REPORT_ROLES, "method": "GET",
        "path": "reports/2021-06-30/documents/{documentId}",
    },
    "getMarketplaceParticipations": {
        "name": "getMarketplaceParticipations", "roles": ("Selling Partner Insights",),
        "method": "GET", "path": "sellers/v1/marketplaceParticipations",
    },
    "getCompetitiveSummary": {
        "name": "getCompetitiveSummary", "roles": ("Pricing",), "method": "POST",
        "path": "batches/products/pricing/2022-05-01/items/competitiveSummary",
    },
    "getItemOffersBatch": {
        "name": "getItemOffersBatch", "roles": ("Pricing",), "method": "POST",
        "path": "batches/products/pricing/v0/itemOffers",
    },
    "getMyFeesEstimates": {
        "name": "getMyFeesEstimates", "roles": ("Pricing",), "method": "POST",
        "path": "products/fees/v0/feesEstimate",
    },
    "listInventory": {
        "name": "listInventory", "roles": ("Amazon Warehousing and Distribution",),
        "method": "GET", "path": "awd/2024-05-09/inventory",
    },
    "createQuery": {"name": "createQuery", "roles": ("Selling Partner Insights",),
                    "method": "POST", "path": _QUERIES_CREATE_PATH},
    "getQuery": {"name": "getQuery", "roles": ("Selling Partner Insights",),
                 "method": "GET", "path": "dataKiosk/2023-11-15/queries/{queryId}"},
    "getDocument": {"name": "getDocument", "roles": ("Selling Partner Insights",),
                    "method": "GET", "path": "dataKiosk/2023-11-15/documents/{documentId}"},
    "listTransactions": {"name": "listTransactions", "roles": ("Finance and Accounting",),
                         "method": "GET", "path": _TRANSACTIONS_PATH},
    "getOrderMetrics": {"name": "getOrderMetrics", "roles": ("Inventory and Order Tracking",),
                        "method": "GET", "path": "sales/v1/orderMetrics"},
    "getInventorySummaries": {"name": "getInventorySummaries", "roles": ("Amazon Fulfillment",),
                             "method": "GET", "path": "fba/inventory/v1/summaries"},
    "searchListingsItems": {"name": "searchListingsItems", "roles": ("Product Listing",),
                            "method": "GET", "path": "listings/2021-08-01/items/{sellerId}"},
    "searchCatalogItems": {"name": "searchCatalogItems", "roles": ("Product Listing",),
                           "method": "GET", "path": "catalog/2022-04-01/items"},
    "getItemReviewTopics": {"name": "getItemReviewTopics",
                            "roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
                            "method": "GET", "path": "customerFeedback/2024-06-01/items/{asin}/reviews/topics"},
    "getItemReviewTrends": {"name": "getItemReviewTrends",
                            "roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
                            "method": "GET", "path": "customerFeedback/2024-06-01/items/{asin}/reviews/trends"},
    "getItemBrowseNode": {"name": "getItemBrowseNode",
                          "roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
                          "method": "GET", "path": "customerFeedback/2024-06-01/items/{asin}/browseNode"},
    "getBrowseNodeReviewTopics": {"name": "getBrowseNodeReviewTopics",
                                  "roles": ("Brand Analytics", "Selling Partner Insights"), "role_match": "any",
                                  "method": "GET",
                                  "path": "customerFeedback/2024-06-01/browseNodes/{browseNodeId}/reviews/topics"},
    "listAllFulfillmentOrders": {"name": "listAllFulfillmentOrders", "roles": ("Amazon Fulfillment",),
                                 "method": "GET", "path": "fulfillmentOutbound/2020-07-01/fulfillmentOrders"},
    "getFulfillmentOrder": {"name": "getFulfillmentOrder", "roles": ("Amazon Fulfillment",),
                            "method": "GET", "path": "fulfillmentOutbound/2020-07-01/fulfillmentOrders/{sellerFulfillmentOrderId}"},
    "listInboundPlans": {"name": "listInboundPlans", "roles": ("Amazon Fulfillment",),
                         "method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans"},
    "getInboundPlan": {"name": "getInboundPlan", "roles": ("Amazon Fulfillment",),
                       "method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}"},
    "listPrepDetails": {"name": "listPrepDetails", "roles": ("Amazon Fulfillment",),
                        "method": "GET", "path": "inbound/fba/2024-03-20/items/prepDetails"},
    "getInboundOperationStatus": {"name": "getInboundOperationStatus", "roles": ("Amazon Fulfillment",),
                                  "method": "GET", "path": "inbound/fba/2024-03-20/operations/{operationId}"},
    "listShipmentItems": {"name": "listShipmentItems", "roles": ("Amazon Fulfillment",),
                          "method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}/shipments/{shipmentId}/items"},
    # The 2024 Item carries no received units: the legacy v0 item read joins them by confirmation ID and SKU.
    "getShipment": {"name": "getShipment", "roles": ("Amazon Fulfillment",),
                    "method": "GET", "path": "inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}/shipments/{shipmentId}"},
    "getShipmentItemsByShipmentId": {"name": "getShipmentItemsByShipmentId", "roles": ("Amazon Fulfillment",),
                                     "method": "GET", "path": "fba/inbound/v0/shipments/{shipmentId}/items"},
    "getShipmentItems": {"name": "getShipmentItems", "roles": ("Amazon Fulfillment",),
                         "method": "GET", "path": "fba/inbound/v0/shipmentItems"},
    "getSellingPartnerMetrics": {"name": "getSellingPartnerMetrics", "roles": ("Brand Analytics",),
                                "method": "POST", "path": "replenishment/2022-11-07/sellingPartners/metrics/search"},
    "listOfferMetrics": {"name": "listOfferMetrics", "roles": ("Brand Analytics",),
                         "method": "POST", "path": "replenishment/2022-11-07/offers/metrics/search"},
    "createDestination": {"name": "createDestination", "roles": (), "method": "POST",
                          "path": _NOTIFICATION_DESTINATIONS_PATH, "scope": NOTIFICATIONS_SCOPE},
    "getDestinations": {"name": "getDestinations", "roles": (), "method": "GET",
                        "path": _NOTIFICATION_DESTINATIONS_PATH, "scope": NOTIFICATIONS_SCOPE},
    "createSubscription": {"name": "createSubscription", "roles": ROLES_TAKEN, "method": "POST",
                           "path": "notifications/v1/subscriptions/{notificationType}"},
    "getSubscription": {"name": "getSubscription", "roles": ROLES_TAKEN, "method": "GET",
                        "path": "notifications/v1/subscriptions/{notificationType}"},
}

#: Answer "what does this approved role let this connector read?" directly from data.
#: The report-side roles above are derived from REPORT_TYPES, including its compound labels.
ROLE_OPERATIONS = {
    role: tuple(name for name, operation in OPERATIONS.items() if role in operation["roles"])
    for role in ROLES_TAKEN
}

# Containment record for the Amazon approval-control series, measured 2026-09-13.
# Git ancestry is not the record here: a packed wave container carries no source
# history. The laptop ancestry check lives in intake finding F23 in
# AutoWiki/research/ideation/wave59-intake.md.
# Each entry claims what exists, never that the control is correct. `contained`
# records full containment; False preserves a documented partial contribution.
# `checkable` means the module can be imported from platform/ without reaching up.
# False is an honest ownership boundary, not a gap to paper over: platform must
# not import the web API, and a Dockerfile is not an importable Python module.
# This is data only; resolving symbols belongs to the checker (W59-T39).
APPROVAL_CONTROLS = {
    "f1d803d": {
        "carries": "shared persistent login-attempt lockout",
        "module": "platform/core/users.py",
        "symbol": "LOGIN_LOCKOUT_BUCKET",
        "contained": True,
        "checkable": True,
    },
    "be68048": {
        "carries": "password minimum age in the password policy",
        "module": "platform/core/users.py",
        "symbol": "PASSWORD_MIN_AGE_DAYS",
        "contained": True,
        "checkable": True,
    },
    "83bfed7": {
        "carries": "the audited lockfile is the dependency boundary",
        "module": "aios-web/Dockerfile",
        "symbol": None,
        "contained": False,
        "checkable": False,
        "note": (
            "The lockfile COPY at aios-web/Dockerfile:37 stands; the npm ci half "
            "does not: :38 is npm install --no-audit --no-fund --ignore-scripts. "
            "The cause is a Windows-resolved lockfile, booked as HARNESS W-170. "
            "Dockerfile and the lockfile belong to lane F in Wave 59. "
            "This web build control cannot be resolved here because Dockerfile "
            "is not an importable Python module."
        ),
    },
    "849067e": {
        "carries": "Pricing and AWD read operations, and the eight approved roles",
        "module": "platform/harness/amazon_client.py",
        "symbol": "ROLES_TAKEN",
        "contained": True,
        "checkable": True,
    },
    "7e556f8": {
        "carries": "exact-tenant raw-mirror purge",
        "module": "platform/harness/amazon_store.py",
        "symbol": "purge",
        "contained": True,
        "checkable": True,
    },
    "9c9454b": {
        "carries": "origin attribution on materialised Amazon tables",
        "module": "aios-web/api/amazon_relational.py",
        "symbol": "source_attribution",
        "contained": True,
        "checkable": False,
        "note": (
            "Owned by the web API layer, which platform may not import; "
            "source_attribution cannot be resolved from this layer."
        ),
    },
    "df1252b": {
        "carries": "origin attribution on Sheet workbooks and the scope cache",
        "module": "platform/core/sheets.py",
        "symbol": "AMAZON_DATA_ORIGIN_NAME",
        "contained": True,
        "checkable": True,
    },
}

_UA = "AIOS-Loopable/1.0 (+read-only)"
_TIMEOUT = 20


class AmazonError(RuntimeError):
    """Any refusal from LWA or SP-API, already stripped of anything secret."""


class AmazonReportError(AmazonError):
    """Vendor report refusal, with its complete reason available to the batch coordinator."""

    def __init__(self, message, reason, status):
        self.vendor_reason = str(reason).replace("\u2014", "; ").replace("\u2013", " to ")
        self.status = status
        super().__init__(f"{message}: {self.vendor_reason}")


class AmazonReportPending(AmazonError):
    """A bounded poll ended before the report, which must be resumed by ID."""

    def __init__(self, report_id, status):
        self.report_id, self.status = str(report_id), str(status or "pending")
        super().__init__(f"Report {self.report_id} is still {self.status}; resume its saved ID next pass")


def sqp_refused_asins(error, asins):
    """Only Amazon's named brand refusals permit removing an ASIN from one retry."""
    if not isinstance(error, AmazonReportError) or error.status not in (400, "FATAL"):
        return []
    reason = error.vendor_reason
    if not re.search(r"not\s+(?:part|associated|owned|eligible|authorized|belong|registered)|invalid\s+asin|outside.*brand", reason, re.I):
        return []
    named = set(re.findall(r"\b[A-Z0-9]{10}\b", reason.upper()))
    return [asin for asin in asins if asin in named]


class AmazonOperationRefused(AmazonError):
    """A local scope refusal, never a throttle and never eligible for throttling retries."""

    def __init__(self, operation):
        super().__init__(
            f"Refused {_safe(operation)}: this connector is limited to the approved read-only set")


class AmazonThrottled(AmazonError):
    """An operation deferred until resume_at, with metadata safe for a pass summary."""

    def __init__(self, message, retry_after=None, *, operation=None, resume_at=None, report_id=None):
        super().__init__(message)
        self.operation = operation if operation in OPERATIONS else None
        self.report_id = report_id
        try:
            delay = float(retry_after)
            self.retry_after = max(0.0, delay) if math.isfinite(delay) else None
        except (TypeError, ValueError):
            try:
                # Retry-After also admits an IMF-fixdate, always expressed in GMT.
                stamp = datetime.strptime(str(retry_after).strip(), "%a, %d %b %Y %H:%M:%S GMT").replace(tzinfo=timezone.utc)
                self.retry_after = max(0.0, (stamp - datetime.now(timezone.utc)).total_seconds())
            except (TypeError, ValueError, OverflowError):
                self.retry_after = None
        try:
            deadline = (datetime.now(timezone.utc) + timedelta(seconds=self.retry_after or 0.0)).isoformat()
        except OverflowError:
            deadline = datetime.max.replace(tzinfo=timezone.utc).isoformat()
        self.resume_at = resume_at or deadline

    def as_resume(self):
        """Return the continuation contract consumed by amazon_store without failing a pass."""
        row = {"state": "throttled", "operation": self.operation,
               "retry_after": self.retry_after, "resume_at": self.resume_at}
        if self.report_id is not None:
            row["report_id"] = str(self.report_id)
        return row


def seller_key(fields):
    """The createReport quota's owner: one seller and region, never a secret."""
    fields = fields or {}
    ident = [str(fields.get("seller_id") or fields.get("client_id") or ""),
             str(fields.get("region") or DEFAULT_REGION).lower(), bool(is_sandbox(fields))]
    return hashlib.sha256(json.dumps(ident).encode()).hexdigest()[:16]


def prefetch_key(fields, report_type, start=None, end=None, options=None):
    """One report request's identity: seller, type, window and options. Two tables sharing one report share it."""
    return json.dumps([seller_key(fields), str(report_type), start, end, dict(options) if options else None],
                      sort_keys=True)


@contextmanager
def prefetch_scope(documents, *, only=True):
    """S82-T14: serve `{prefetch_key: (text, meta)}` without a vendor call. `only` defers any other report.

    Yields the set of keys served, so the job marks only the windows a write consumed.
    """
    served = set()
    token = _prefetch.set({"documents": dict(documents), "only": bool(only), "served": served})
    try:
        yield served
    finally:
        _prefetch.reset(token)


@contextmanager
def report_ledger_scope(take):
    """S82-T14: every new createReport in this context first draws from `take(fields)`."""
    token = _report_ledger.set(take)
    try:
        yield
    finally:
        _report_ledger.reset(token)


def prefetch_active():
    """True inside a first-load job's write, where the job owns report pacing."""
    return _prefetch.get() is not None


def _prefetched(fields, report_type, start, end, options):
    held = _prefetch.get()
    if held is None:
        return None
    key = prefetch_key(fields, report_type, start, end, options)
    if key in held["documents"]:
        held["served"].add(key)
        return held["documents"][key]
    if held["only"]:
        # The job polls its own reports together; a write it runs never starts another.
        raise AmazonThrottled(f"The first-load job requests the {report_type} report for this window itself. "
                              "It resumes in a later generation.", retry_after=0, operation="createReport")
    return None


def _draw_report_token(fields):
    take = _report_ledger.get()
    if take is not None:
        take(fields)


@contextmanager
def rate_limit_scope(tenant, client="amazon_sp"):
    """Isolate one tenant and connection's operation quotas, including refreshed access tokens."""
    tenant_token = _tenant_scope.set((str(tenant), str(client)))
    client_token = _client_scope.set(None)
    reserved = _reservation.set(None)
    try:
        yield
    finally:
        _reservation.reset(reserved)
        _client_scope.reset(client_token)
        _tenant_scope.reset(tenant_token)


def _scope_for(token, region, sandbox):
    digest = hashlib.sha256(str(token).encode()).hexdigest()
    with _rate_lock:
        client = _token_scopes.get((_tenant_scope.get(), digest), digest)
    return (_tenant_scope.get(), client, str(region or DEFAULT_REGION).lower(), bool(sandbox))


def _remember_token(fields, token):
    client = hashlib.sha256(json.dumps(
        [_tenant_scope.get(), str(fields.get("tenant") or ""), str(fields.get("client_id") or ""),
         str(fields.get("seller_id") or ""), str(fields.get("refresh_token") or "")],
        separators=(",", ":")).encode()).hexdigest()
    with _rate_lock:
        _token_scopes[(_tenant_scope.get(), hashlib.sha256(token.encode()).hexdigest())] = client
    _client_scope.set(_scope_for(token, fields.get("region"), is_sandbox(fields)))


@contextmanager
def _pacing_scope(scope):
    previous = _client_scope.set(scope)
    try:
        yield
    finally:
        _client_scope.reset(previous)


def _rate_state(operation, scope):
    with _rate_lock:
        return _rate_states.setdefault((scope, operation),
            {"last": None, "interval": None, "until": 0.0, "lock": threading.Lock()})


def _default_interval(operation):
    return {"createReport": REPORT_SUSTAINED_SECONDS, "createQuery": QUERY_SUSTAINED_SECONDS,
            "getReport": 0.5, "getReports": 1 / 0.0222, "getReportDocument": 1 / 0.0167,
            "getQuery": 0.5, "getDocument": 0.5, "getQueries": 0.5,
            "getCompetitiveSummary": COMPETITIVE_SUMMARY_INTERVAL,
            "getItemOffersBatch": ITEM_OFFERS_INTERVAL, "listPrepDetails": 1.0,
            "getInboundOperationStatus": 0.5,
            "listInventory": AWD_INVENTORY_INTERVAL, "listTransactions": TRANSACTIONS_INTERVAL,
            "listAllFulfillmentOrders": 0.5, "getFulfillmentOrder": 0.5,
            "getSellingPartnerMetrics": 1.0, "listOfferMetrics": 1.0,
            **ENTITY_INTERVALS, **INBOUND_INTERVALS, **FEEDBACK_INTERVALS}.get(operation, 1.0)


def _observe_rate(operation, scope, headers):
    try:
        rate = float(next((v for k, v in (headers or {}).items()
                           if str(k).lower() == "x-amzn-ratelimit-limit"), 0))
    except (ValueError, TypeError, AttributeError):
        return
    if math.isfinite(rate) and rate > 0 and math.isfinite(1 / rate):
        state = _rate_state(operation, scope)
        with state["lock"]:
            state["interval"] = 1 / rate


def _pace_operation(operation, scope, interval, *, sleep, now):
    state = _rate_state(operation, scope)
    with state["lock"]:
        stamp, last = now(), state["last"]
        gap = state["interval"] if state["interval"] is not None else interval
        wait = max(0.0, state["until"] - stamp,
                   last + gap - stamp if last is not None else 0.0)
        if wait > RETRY_MAX_SECONDS:
            raise AmazonThrottled(f"Amazon throttled (429). Operation: {operation}. "
                                  "Resume next pass after the operation's rate limit delay.",
                                  retry_after=wait, operation=operation)
        if wait:
            sleep(wait)
        state["last"] = max(stamp + wait, now())
        return wait


def _safe(url):
    """A URL fit to appear in an error message: query string dropped entirely.

    Same idiom as `connectors_meta._safe`. SP-API puts marketplace ids, seller ids and date
    windows in query parameters, and an error string is the one place a caller reliably copies
    into a ticket or a screenshot.
    """
    try:
        p = urllib.parse.urlsplit(str(url))
        return urllib.parse.urlunsplit((p.scheme, p.netloc, p.path, "", ""))
    except Exception:                                                  # noqa: BLE001
        return "<url>"


def operation_for(method, path):
    """Resolve an exact approved operation, or None. Query parameters belong in **params."""
    parts = str(path).lstrip("/").split("/")
    for operation in OPERATIONS.values():
        template = operation["path"].split("/")
        if str(method).upper() != operation["method"] or len(parts) != len(template):
            continue
        if all(
            (bool(part) and part not in (".", "..")
             and all(c in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."
                     for c in part))
            if segment.startswith("{") and segment.endswith("}") else part == segment
            for part, segment in zip(parts, template)
        ):
            return operation
    return None


def require_operation(method, path, *, report_type=None):
    """Fail closed before constructing any URL or touching a transport."""
    if report_type in EXCLUDED_REPORT_TYPES:
        raise AmazonOperationRefused(f"excluded report {report_type}")
    operation = operation_for(method, path)
    if operation is None:
        raise AmazonOperationRefused(f"{str(method).upper()} {_safe(path)}")
    if (operation["name"] in ("getSubscription", "createSubscription")
            and str(path).rsplit("/", 1)[-1] not in NOTIFICATION_TYPES):
        raise AmazonOperationRefused("Notifications type")
    # A Reports URL alone is insufficient: restricted report families use this same POST.
    # Admit only the bulk flavors joined from the seven declared tables, including incrementals.
    if report_type is not None and str(report_type) not in operation.get("report_types", ()):
        raise AmazonOperationRefused(f"{operation['name']} report {report_type}")
    return operation


def _retry(attempt_fn, what, *, sleep=time.sleep, rand=random.random, exhausted_fix=None,
           operation=None, scope=None, now=time.monotonic):
    """Retry only SP-API throttling; return successes and propagate other refusals unchanged."""
    reserved = _reservation.get()
    _reservation.set(None)
    prepaid = bool(scope is not None and reserved and reserved[0] == operation
                   and reserved[1] in (None, scope))
    if prepaid:
        sleep, now = reserved[2:4]
        state = _rate_state(operation, scope)
        with state["lock"]:
            state["last"] = reserved[4]
    for n in range(1, RETRY_MAX_ATTEMPTS + 1):
        try:
            if scope is not None and not (n == 1 and prepaid):
                wait = _pace_operation(operation, scope, _default_interval(operation), sleep=sleep, now=now)
                if operation == "createReport":
                    _report_pacer["waited"].set(wait)
            return attempt_fn()
        except AmazonThrottled as e:
            operation = operation or e.operation or (what if what in OPERATIONS else None)
            floor = e.retry_after or 0.0
            wait = max(floor, min(RETRY_MAX_SECONDS, RETRY_BASE_SECONDS * 2 ** (n - 1)))
            wait = max(floor, min(RETRY_MAX_SECONDS,
                                 wait * (1 - RETRY_JITTER + RETRY_JITTER * rand() * 2)))
            if scope is not None:
                state = _rate_state(operation, scope)
                with state["lock"]:
                    state["until"] = max(state["until"], now() + wait)
                    interval = state["interval"]
                    if interval is not None and state["last"] is not None:
                        wait = max(wait, state["last"] + interval - now())
            if n == RETRY_MAX_ATTEMPTS or wait > RETRY_MAX_SECONDS:
                fix = exhausted_fix or "sync fewer tables at once and widen the report window"
                raise AmazonThrottled(
                    f"Amazon throttled (429). Operation: {operation or 'unknown'}. Cause: SP-API quota. "
                    f"Fix: resume next pass after retry delay. {n - 1} retries spent. {fix}. "
                    f"Endpoint: {_safe(what)}", retry_after=wait, operation=operation) from None
            if scope is None:
                sleep(wait)


def _pace_report_create(*, sleep=time.sleep, now=time.monotonic):
    """Reserve one report creation under the burst, refill rate and minimum gap; return its wait."""
    if _client_scope.get() is not None:
        return _pace_entity("createReport", REPORT_SUSTAINED_SECONDS, sleep=sleep, now=now)
    with _report_pacer["lock"]:
        stamp = now()
        updated = _report_pacer["updated"]
        elapsed = max(0.0, stamp - updated) if updated is not None else 0.0
        tokens = min(REPORT_BURST, _report_pacer["tokens"] + elapsed / REPORT_SUSTAINED_SECONDS)
        last = _report_pacer["last_create"]
        gap = last + REPORT_STAGGER_SECONDS - stamp if last is not None else 0.0
        wait = max(0.0, gap, (1.0 - tokens) * REPORT_SUSTAINED_SECONDS)
        if wait:
            sleep(wait)
        # ⭐ Count refill during the wait too. A late wake may refill up to the burst, never more.
        issued = max(stamp + wait, now())
        _report_pacer.update(
            tokens=min(REPORT_BURST, tokens + (issued - stamp) / REPORT_SUSTAINED_SECONDS) - 1.0,
            updated=issued, last_create=issued)
        return wait


def _pace_entity(name, interval, *, sleep=time.sleep, now=time.monotonic):
    """Reserve one operation using its observed rate within the active client scope."""
    operation = {"competitive_summary": "getCompetitiveSummary", "awd_inventory": "listInventory",
                 "transactions": "listTransactions"}.get(name, name)
    scope = _client_scope.get()
    if scope is not None:
        wait = _pace_operation(operation, scope, interval, sleep=sleep, now=now)
        _reservation.set((operation, scope, sleep, now, now()))
        return wait
    pacer = _entity_pacers[name]
    with pacer["lock"]:
        stamp = now()
        last = pacer["last"]
        wait = max(0.0, last + interval - stamp) if last is not None else 0.0
        if wait:
            sleep(wait)
        pacer["last"] = max(stamp + wait, now())
        _reservation.set((operation, None, sleep, now, pacer["last"]))
        return wait


def _pace_query_create(*, sleep=time.sleep, now=time.monotonic):
    """Reserve from Data Kiosk's independent burst-15, one-per-minute bucket."""
    if _client_scope.get() is not None:
        return _pace_entity("createQuery", QUERY_SUSTAINED_SECONDS, sleep=sleep, now=now)
    with _query_pacer["lock"]:
        stamp = now()
        updated = _query_pacer["updated"]
        elapsed = max(0.0, stamp - updated) if updated is not None else 0.0
        tokens = min(QUERY_BURST, _query_pacer["tokens"] + elapsed / QUERY_SUSTAINED_SECONDS)
        wait = max(0.0, (1.0 - tokens) * QUERY_SUSTAINED_SECONDS)
        if wait:
            sleep(wait)
        issued = max(stamp + wait, now())
        _query_pacer.update(tokens=min(QUERY_BURST, tokens +
                            (issued - stamp) / QUERY_SUSTAINED_SECONDS) - 1.0, updated=issued)
        return wait


def economics_query(start, end, marketplace_id, *, summary=False):
    """Build only the pinned economics query; never accept caller GraphQL."""
    for value in (start, end):
        if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
            raise AmazonError("Economics dates must be YYYY-MM-DD")
        try:
            date.fromisoformat(value)
        except ValueError:
            raise AmazonError("Economics dates must be valid YYYY-MM-DD dates") from None
    if start > end or type(summary) is not bool:
        raise AmazonError("Economics needs an ordered date range and a boolean summary selection")
    if not isinstance(marketplace_id, str) or not re.fullmatch(r"[A-Z0-9]+", marketplace_id):
        raise AmazonError("Economics needs an alphanumeric marketplace ID")
    return (_ECONOMICS_TEMPLATES[summary].replace("__START__", start)
            .replace("__END__", end).replace("__MARKETPLACE__", marketplace_id))


def _create_query(token, start, end, marketplace_id, *, summary=False,
                  region=DEFAULT_REGION, timeout=_TIMEOUT, sandbox=False):
    """The third declared POST wrapper, fixed to a read-only economics query."""
    require_operation("POST", _QUERIES_CREATE_PATH)
    operation, scope = "createQuery", _scope_for(token, region, sandbox)
    body = {"query": economics_query(start, end, marketplace_id, summary=summary)}

    def attempt():
        base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region).lower())
        if not base:
            raise AmazonError(f"unknown region `{region}`")
        url = f"{base}/{_QUERIES_CREATE_PATH}"
        req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), method="POST")
        req.add_header("x-amz-access-token", token)
        req.add_header("Content-Type", "application/json")
        req.add_header("User-Agent", _UA)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as response:
                _observe_rate(operation, scope, getattr(response, "headers", None))
                got = json.loads(response.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as exc:
            _observe_rate(operation, scope, exc.headers)
            if exc.code == 429:
                raise AmazonThrottled("createQuery throttled (429); Data Kiosk permits a burst of "
                                      "15, then one query per 60 seconds",
                                      retry_after=(exc.headers or {}).get("Retry-After")) from None
            if exc.code == 403:
                raise AmazonError("createQuery answered 403: needs the Selling Partner Insights role") from None
            raise AmazonError(f"createQuery answered {exc.code}") from None
        except Exception as exc:
            raise AmazonError(f"createQuery unreachable: {type(exc).__name__}") from None
        if not got.get("queryId"):
            raise AmazonError("createQuery returned no queryId")
        return str(got["queryId"])

    with _pacing_scope(scope):
        _pace_query_create()
    return _retry(attempt, _QUERIES_CREATE_PATH,
                  operation=operation, scope=scope,
                  exhausted_fix="reduce Data Kiosk query frequency and retry the window")


def _kiosk_document(token, document_id, *, region, sandbox, timeout):
    meta = _request(f"dataKiosk/2023-11-15/documents/{document_id}", token,
                    region=region, sandbox=sandbox, timeout=timeout)
    url = str(meta.get("documentUrl") or "")
    if not url:
        raise AmazonError("Data Kiosk document returned no documentUrl")
    text = _download_document(url, str(meta.get("compressionAlgorithm") or ""))
    return text


def economics_document(fields, start, end, *, summary=False, max_wait=900,
                       poll_seconds=15, timeout=_TIMEOUT, sleep=time.sleep):
    """Request, poll and download JSONL, including the vendor error document on failure."""
    marketplace = str(fields.get("marketplace_id") or US_MARKETPLACE_ID)
    economics_query(start, end, marketplace, summary=summary)  # Validate before LWA.
    token = access_token(fields, timeout=timeout)
    region, sandbox = str(fields.get("region") or DEFAULT_REGION), is_sandbox(fields)
    query_id = _create_query(token, start, end, marketplace, summary=summary,
                             region=region, sandbox=sandbox, timeout=timeout)
    waited = 0
    while waited <= max_wait:
        got = _request(f"dataKiosk/2023-11-15/queries/{query_id}", token,
                       region=region, sandbox=sandbox, timeout=timeout)
        state = got.get("processingStatus")
        if got.get("errorDocumentId"):
            detail = _kiosk_document(token, got["errorDocumentId"], region=region,
                                     sandbox=sandbox, timeout=timeout)
            detail = detail.replace("\u2014", "; ").replace("\u2013", " to ")
            raise AmazonError(f"Economics query {query_id} {state}: {detail[:1200]}")
        if state == "DONE":
            doc_id = got.get("dataDocumentId")
            if not doc_id:
                raise AmazonError(f"Economics query {query_id} returned no dataDocumentId")
            return (_kiosk_document(token, doc_id, region=region, sandbox=sandbox, timeout=timeout),
                    {"queryId": query_id, "reportDocumentId": doc_id})
        if state in ("FATAL", "CANCELLED"):
            raise AmazonError(f"Economics query {query_id} ended as {state}")
        sleep(poll_seconds)
        waited += poll_seconds
        if waited and waited % 1800 == 0:
            token = access_token(fields, timeout=timeout)
    raise AmazonError(f"Economics query {query_id} still pending after {max_wait}s; "
                      "increase the query wait before retrying the window")


def transactions(fields, start, end, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """Follow every Finances page at 0.5/s, including empty pages carrying a nextToken."""
    token, issued = access_token(fields, timeout=timeout), now()
    following, seen, rows = None, set(), []
    while True:
        _pace_entity("transactions", TRANSACTIONS_INTERVAL, sleep=sleep, now=now)
        if now() - issued >= 3000:
            token, issued = access_token(fields, timeout=timeout), now()
        got = _request(_TRANSACTIONS_PATH, token,
                       region=str(fields.get("region") or DEFAULT_REGION),
                       sandbox=is_sandbox(fields), timeout=timeout,
                       postedAfter=start, postedBefore=end,
                       marketplaceId=fields.get("marketplace_id") or US_MARKETPLACE_ID,
                       nextToken=following,
                       throttle_fix="resume the same Finances window at its 0.5 requests/second rate")
        payload = got.get("payload") or {}
        page = payload.get("transactions")
        if not isinstance(page, list):
            raise AmazonError("listTransactions returned no transactions list")
        rows.extend(page)
        following = payload.get("nextToken")
        if not following:
            return rows
        if following in seen:
            raise AmazonError("listTransactions repeated a nextToken; cannot prove complete pagination; "
                              "retry the window after Amazon corrects the cursor")
        seen.add(following)


ENTITY_INTERVALS = {"getOrderMetrics": 2.0, "getInventorySummaries": 0.5,
                    "searchListingsItems": 0.2, "searchCatalogItems": 0.5,
                    "getMyFeesEstimates": 2.0}
FEEDBACK_INTERVALS = {"getItemReviewTopics": 1.0, "getItemReviewTrends": 1.0,
                      "getItemBrowseNode": 1.0, "getBrowseNodeReviewTopics": 1.0}
#: getItemReviewTopics and getBrowseNodeReviewTopics accept exactly these sortBy values.
FEEDBACK_SORTS = ("MENTIONS", "STAR_RATING_IMPACT")
INBOUND_INTERVALS = {"listInboundPlans": 0.5, "getInboundPlan": 0.5, "listShipmentItems": 0.5,
                     "getShipment": 0.5, "getShipmentItemsByShipmentId": 0.5, "getShipmentItems": 0.5}
#: Amazon's 400 text for an Amazon Warehousing and Distribution plan in the FBA inbound list.
AWD_PLAN_REFUSAL = "not supported for Amazon Warehousing and Distribution inbound plans"
#: Amazon's 400 text for a V0 shipment converted to a Send-to-Amazon plan: getInboundPlan never serves it.
CONVERTED_PLAN_REFUSAL = ("not supported for Fulfillment Inbound API V0 shipments that have been converted "
                          "to Send-to-Amazon inbound plans")


class InboundRecords(list):
    """Inbound shipment records, plus `skipped_plans`: each plan Amazon refused alone, with its reason."""

    def __init__(self, records=(), skipped_plans=()):
        super().__init__(records)
        self.skipped_plans = list(skipped_plans)


def _inbound_plan_refusal(exc):
    """Name a 400 that refuses one plan, or return None when the refusal must drop the snapshot."""
    text = str(exc)
    # A throttle or a local scope refusal is never one plan's answer.
    if isinstance(exc, (AmazonThrottled, AmazonOperationRefused)):
        return None
    if CONVERTED_PLAN_REFUSAL in text:
        return {"refusal": "converted", "reason": "Amazon converted this V0 shipment to a Send-to-Amazon plan "
                                                  "and does not serve it through getInboundPlan."}
    status = re.search(r"(?:\banswered|\bHTTP) 400\b:?\s*", text)
    if status is None:
        return None
    detail = text[status.end():].replace("\u2014", ". ").replace("\u2013", " to ").strip()
    return {"refusal": "unknown", "reason": "Amazon refused this plan with a 400: " + (detail or "no reason given.")}


def _require_replenishment_roles():
    """Admit both fixed metric searches before credentials or transport access."""
    for operation, path in _REPLENISHMENT_PATHS.items():
        admitted = require_operation("POST", path)
        if (admitted["name"] != operation or admitted["roles"] != ("Brand Analytics",)
                or "Brand Analytics" not in ROLES_TAKEN):
            raise AmazonOperationRefused(operation + " requires the Brand Analytics role")


def _replenishment_request(token, operation, marketplace, start, end, *, offset=0,
                           region=DEFAULT_REGION, sandbox=False, timeout=_TIMEOUT,
                           sleep=time.sleep, now=time.monotonic):
    """Search only Subscribe and Save performance metrics through fixed read-only POST bodies."""
    require_operation("POST", _REPLENISHMENT_PATHS.get(operation, ""))
    scope = _scope_for(token, region, sandbox)
    _require_replenishment_roles()
    if not isinstance(marketplace, str) or not re.fullmatch(r"[A-Z0-9]+", marketplace):
        raise AmazonError("Replenishment metrics need an alphanumeric marketplace ID")
    try:
        lower, upper = (datetime.fromisoformat(value.replace("Z", "+00:00")) for value in (start, end))
        valid = (lower.tzinfo is not None and upper.tzinfo is not None and lower <= upper
                 and (lower.year, lower.month) == (upper.year, upper.month))
    except (ValueError, TypeError, AttributeError):
        valid = False
    if not valid:
        raise AmazonError("Replenishment metrics need one calendar month with UTC date-time bounds")
    if type(offset) is not int or not 0 <= offset <= 9000 or (operation == "getSellingPartnerMetrics" and offset):
        raise AmazonOperationRefused("noncanonical replenishment pagination")
    filters = {"aggregationFrequency": "MONTH", "timeInterval": {"startDate": start, "endDate": end},
               "timePeriodType": "PERFORMANCE", "marketplaceId": marketplace,
               "programTypes": ["SUBSCRIBE_AND_SAVE"]}
    body = (filters if operation == "getSellingPartnerMetrics" else
            {"filters": filters, "pagination": {"limit": 500, "offset": offset},
             "sort": {"order": "ASC", "key": "TOTAL_SUBSCRIPTIONS_REVENUE"}})

    def attempt():
        base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region).lower())
        if not base:
            raise AmazonError(f"unknown region `{region}`")
        req = urllib.request.Request(f"{base}/{_REPLENISHMENT_PATHS[operation]}",
                                     data=json.dumps(body).encode("utf-8"), method="POST")
        req.add_header("x-amz-access-token", token)
        req.add_header("Content-Type", "application/json")
        req.add_header("User-Agent", _UA)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as response:
                _observe_rate(operation, scope, getattr(response, "headers", None))
                got = json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            _observe_rate(operation, scope, exc.headers)
            try:
                errors = json.loads(exc.read().decode("utf-8")).get("errors") or []
                reason = "; ".join(str(row.get("message") or row.get("code") or "Amazon gave no reason") for row in errors)
            except (ValueError, AttributeError, TypeError):
                reason = "Amazon gave no reason"
            if exc.code == 429:
                raise AmazonThrottled(f"{operation} throttled (429); use one request per second with a burst of one",
                                      retry_after=(exc.headers or {}).get("Retry-After")) from None
            raise AmazonReportError(f"{operation} refused ({exc.code}). Amazon reason",
                                    reason or "Amazon gave no reason", exc.code) from None
        except (OSError, ValueError) as exc:
            raise AmazonError(f"{operation} could not read Amazon's response: {type(exc).__name__}") from None
        if not isinstance(got, dict):
            raise AmazonError(operation + " returned no metric response object")
        return got

    with _pacing_scope(scope):
        _pace_entity(operation, 1.0, sleep=sleep, now=now)
    return _retry(attempt, operation, sleep=sleep, now=now, operation=operation, scope=scope,
                  exhausted_fix="resume replenishment metric searches at one request per second")


def replenishment_metrics(fields, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """Read the complete seller summary and every offer page for the last complete month."""
    _require_replenishment_roles()
    end = datetime.now(timezone.utc).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    last = end - timedelta(seconds=1)
    start = last.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    first, final = (value.strftime("%Y-%m-%dT%H:%M:%SZ") for value in (start, last))
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    token, issued = access_token(fields, timeout=timeout), now()

    def read(operation, offset=0):
        nonlocal token, issued
        if now() - issued >= 3000:
            token, issued = access_token(fields, timeout=timeout), now()
        return _replenishment_request(token, operation, marketplace, first, final, offset=offset,
            region=str(fields.get("region") or DEFAULT_REGION), sandbox=is_sandbox(fields),
            timeout=timeout, sleep=sleep, now=now)

    seller = read("getSellingPartnerMetrics").get("metrics")
    if not isinstance(seller, list) or any(not isinstance(row, dict) for row in seller):
        raise AmazonError("getSellingPartnerMetrics returned no valid metrics list")
    offers, expected, identities = [], None, set()
    while True:
        offset = len(offers)
        if offset > 9000:
            raise AmazonError("Amazon listOfferMetrics limits offsets to 9000. No partial snapshot was stored. "
                              "Ask Amazon for a higher pagination limit or a bulk replenishment export.")
        got = read("listOfferMetrics", offset)
        page = got.get("offers")
        pagination = got.get("pagination")
        count = pagination.get("totalResults") if isinstance(pagination, dict) else None
        if (not isinstance(page, list) or any(not isinstance(row, dict) for row in page)
                or type(count) is not int or count < 0 or len(page) > 500):
            raise AmazonError("listOfferMetrics returned incomplete offers or totalResults; no partial snapshot was stored")
        if expected is not None and count != expected:
            raise AmazonError("listOfferMetrics changed totalResults during pagination; retry the complete snapshot")
        expected = count
        for row in page:
            identity = (row.get("asin"), row.get("sku"), row.get("fulfillmentChannelType"),
                        json.dumps(row.get("timeInterval"), sort_keys=True))
            if identity in identities:
                raise AmazonError("listOfferMetrics repeated an offer across pages; no partial snapshot was stored")
            identities.add(identity)
        offers.extend(page)
        if len(offers) == expected:
            break
        if not page or len(offers) > expected:
            raise AmazonError("listOfferMetrics ended before its totalResults matched; no partial snapshot was stored")
    return {"sellingPartnerMetrics": seller, "offerMetrics": offers, "offerCount": expected,
            "marketplaceId": marketplace, "start": first, "end": final}


def outbound_fulfillment_orders(fields, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """Read every multi-channel order and its items through the two fixed Fulfillment GET operations."""
    path = "fulfillmentOutbound/2020-07-01/fulfillmentOrders"
    for operation, target in (("listAllFulfillmentOrders", path),
                              ("getFulfillmentOrder", path + "/fixture-order")):
        admitted = require_operation("GET", target)
        if (admitted["name"] != operation or admitted["roles"] != ("Amazon Fulfillment",)
                or "Amazon Fulfillment" not in ROLES_TAKEN):
            raise AmazonOperationRefused(operation + " requires the Amazon Fulfillment role")
    token, issued = access_token(fields, timeout=timeout), now()
    params = {"queryStartDateTime": "1970-01-01T00:00:00Z"}
    seen, orders = set(), {}

    def read(target, operation, query):
        nonlocal token, issued
        _pace_entity(operation, 0.5, sleep=sleep, now=now)
        if now() - issued >= 3000:
            token, issued = access_token(fields, timeout=timeout), now()
        got = _request(target, token, region=str(fields.get("region") or DEFAULT_REGION),
                       sandbox=is_sandbox(fields), timeout=timeout, **query,
                       throttle_fix="continue all outbound fulfillment pages and items at two requests per second")
        payload = got.get("payload")
        if not isinstance(payload, dict):
            raise AmazonError(operation + " returned no valid payload; no partial outbound snapshot was stored")
        return payload

    while True:
        payload = read(path, "listAllFulfillmentOrders", params)
        page = payload.get("fulfillmentOrders")
        if not isinstance(page, list) or any(not isinstance(order, dict) for order in page):
            raise AmazonError("Amazon outbound fulfillment returned no valid order list")
        for order in page:
            identity = order.get("sellerFulfillmentOrderId")
            if not isinstance(identity, str) or operation_for("GET", path + "/" + identity) is None:
                raise AmazonError("Amazon outbound fulfillment omitted a supported order ID; no partial snapshot was stored")
            orders[identity] = None
        following = payload.get("nextToken")
        if not following:
            break
        if not isinstance(following, str) or following in seen:
            raise AmazonError("Amazon outbound fulfillment repeated or returned an invalid nextToken; no partial snapshot was stored")
        seen.add(following)
        params = {"nextToken": following}
    records = []
    for identity in orders:
        payload = read(path + "/" + identity, "getFulfillmentOrder", {})
        order, items = payload.get("fulfillmentOrder"), payload.get("fulfillmentOrderItems")
        if (not isinstance(order, dict) or order.get("sellerFulfillmentOrderId") != identity
                or not isinstance(items, list) or any(not isinstance(item, dict) for item in items)):
            raise AmazonError("Amazon outbound fulfillment returned incomplete order items; no partial snapshot was stored")
        records.append({"fulfillmentOrder": order, "fulfillmentOrderItems": items})
    return records


def inbound_shipment_items(fields, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """Read every FBA plan, its shipment summaries and every shipment-item page."""
    path = "inbound/fba/2024-03-20/inboundPlans"
    targets = (("listInboundPlans", path), ("getInboundPlan", path + "/fixture-plan"),
               ("listShipmentItems", path + "/fixture-plan/shipments/fixture-shipment/items"),
               ("getShipment", path + "/fixture-plan/shipments/fixture-shipment"),
               ("getShipmentItemsByShipmentId", "fba/inbound/v0/shipments/fixture-shipment/items"),
               ("getShipmentItems", "fba/inbound/v0/shipmentItems"))
    for operation, target in targets:
        admitted = require_operation("GET", target)
        if (admitted["name"] != operation or admitted["roles"] != ("Amazon Fulfillment",)
                or "Amazon Fulfillment" not in ROLES_TAKEN):
            raise AmazonOperationRefused(operation + " requires the Amazon Fulfillment role")
    token, issued = access_token(fields, timeout=timeout), now()

    def read(target, operation, query):
        nonlocal token, issued
        _pace_entity(operation, INBOUND_INTERVALS[operation], sleep=sleep, now=now)
        if now() - issued >= 3000:
            token, issued = access_token(fields, timeout=timeout), now()
        body = _request(target, token, region=str(fields.get("region") or DEFAULT_REGION),
                        sandbox=is_sandbox(fields), timeout=timeout, **query,
                        throttle_fix="continue every FBA inbound plan and item page at two requests per second per operation")
        if not isinstance(body, dict):
            raise AmazonError(operation + " returned no valid response; no partial inbound snapshot was stored")
        return body

    def pages(target, operation, root, size):
        query, seen = {"pageSize": size}, set()
        while True:
            body = read(target, operation, query)
            page = body.get(root)
            if not isinstance(page, list) or any(not isinstance(row, dict) for row in page):
                raise AmazonError(operation + " returned no valid " + root + " list; no partial inbound snapshot was stored")
            yield page
            pagination = body.get("pagination", {})
            if not isinstance(pagination, dict):
                raise AmazonError(operation + " returned invalid pagination; no partial inbound snapshot was stored")
            following = pagination.get("nextToken")
            if following is None:
                return
            if not isinstance(following, str) or not following or following in seen:
                raise AmazonError(operation + " repeated or returned an invalid nextToken; no partial inbound snapshot was stored")
            seen.add(following)
            query = {"pageSize": size, "paginationToken": following}

    def identifier(value):
        if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9-]{38}", value):
            raise AmazonError("Amazon FBA inbound omitted a supported ID; no partial snapshot was stored")
        return value

    marketplace = str(fields.get("marketplace_id") or US_MARKETPLACE_ID)

    def receipt_refused(exc):
        # A 4xx leaves this shipment's receipt unknown. A throttle, a 5xx or an unreachable call refuses the snapshot.
        return not isinstance(exc, AmazonThrottled) and re.search(r"\banswered 4\d\d\b", str(exc)) is not None

    def receipts(plan_id, shipment_id):
        """Return the legacy confirmation ID and received units per SKU. Unknown receipts stay out."""
        try:
            shipment = read(path + "/" + plan_id + "/shipments/" + shipment_id, "getShipment", {})
        except AmazonError as exc:
            if receipt_refused(exc):
                return None, {}
            raise
        confirmation = shipment.get("shipmentConfirmationId")
        if (shipment.get("shipmentId") not in (None, shipment_id) or not isinstance(confirmation, str)
                or not re.fullmatch(r"[A-Za-z0-9]{1,40}", confirmation)):
            return None, {}
        legacy, seen = [], set()
        target, operation, query = ("fba/inbound/v0/shipments/" + confirmation + "/items",
                                    "getShipmentItemsByShipmentId", {"MarketplaceId": marketplace})
        try:
            while True:
                payload = read(target, operation, query).get("payload")
                rows = payload.get("ItemData") if isinstance(payload, dict) else None
                if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
                    return confirmation, {}
                legacy.extend(rows)
                following = payload.get("NextToken")
                if not following:
                    break
                if not isinstance(following, str) or following in seen:
                    return confirmation, {}
                seen.add(following)
                target, operation = "fba/inbound/v0/shipmentItems", "getShipmentItems"
                query = {"QueryType": "NEXT_TOKEN", "NextToken": following, "MarketplaceId": marketplace}
        except AmazonError as exc:
            if receipt_refused(exc):
                return confirmation, {}
            raise
        received, repeated = {}, set()
        for row in legacy:
            sku, units = row.get("SellerSKU"), row.get("QuantityReceived")
            if row.get("ShipmentId") not in (None, confirmation) or not isinstance(sku, str):
                continue
            if sku in received:
                repeated.add(sku)
            received[sku] = units if type(units) is int and units >= 0 else None
        return confirmation, {sku: units for sku, units in received.items() if sku not in repeated}

    plans, records, skipped = {}, [], []
    for page in pages(path, "listInboundPlans", "inboundPlans", 30):
        for plan in page:
            plans[identifier(plan.get("inboundPlanId"))] = None
    for plan_id in plans:
        target = path + "/" + plan_id
        try:
            plan = read(target, "getInboundPlan", {})
        except AmazonError as exc:
            # Amazon lists AWD plans here but answers 400 to getInboundPlan for them: they are not FBA plans.
            if AWD_PLAN_REFUSAL in str(exc):
                continue
            # One plan's 400 skips that plan and names it. A throttle or a 5xx still refuses the snapshot.
            refusal = _inbound_plan_refusal(exc)
            if refusal is None:
                raise
            skipped.append({"inboundPlanId": plan_id, **refusal})
            continue
        if plan.get("inboundPlanId") != plan_id or not isinstance(plan.get("status"), str) or not plan["status"]:
            raise AmazonError("getInboundPlan returned an incomplete or mismatched plan; no partial inbound snapshot was stored")
        # Unconfirmed plans may omit shipments until a placement option is confirmed.
        shipments = plan.get("shipments", [])
        if not isinstance(shipments, list) or any(not isinstance(shipment, dict) for shipment in shipments):
            raise AmazonError("getInboundPlan returned invalid shipments; no partial inbound snapshot was stored")
        seen = set()
        for shipment in shipments:
            shipment_id = identifier(shipment.get("shipmentId"))
            if shipment_id in seen or not isinstance(shipment.get("status"), str) or not shipment["status"]:
                raise AmazonError("getInboundPlan repeated or omitted a shipment status; no partial inbound snapshot was stored")
            seen.add(shipment_id)
            items = []
            for page in pages(target + "/shipments/" + shipment_id + "/items", "listShipmentItems", "items", 1000):
                items.extend(page)
            confirmation, received = receipts(plan_id, shipment_id) if items else (None, {})
            lines = {}
            for item in items:
                lines[item.get("msku")] = lines.get(item.get("msku"), 0) + 1
            for item in items:
                # Receipt is Amazon's explicit QuantityReceived, never a CLOSED status. A split SKU line keeps None.
                item["QuantityReceived"] = received.get(item.get("msku")) if lines[item.get("msku")] == 1 else None
            records.append({"inboundPlanId": plan_id, "planStatus": plan["status"],
                            "shipmentId": shipment_id, "status": shipment["status"],
                            "shipmentConfirmationId": confirmation, "items": items})
    return InboundRecords(records, skipped)


def _feedback_admitted(operation):
    """Refuse an unapproved Customer Feedback operation or a missing role before any transport."""
    if operation not in FEEDBACK_INTERVALS:
        raise AmazonOperationRefused("unapproved Customer Feedback reader")
    if not set(OPERATIONS[operation]["roles"]).intersection(ROLES_TAKEN):
        raise AmazonOperationRefused("Customer Feedback needs Brand Analytics or Selling Partner Insights")


def _feedback_child_asins(asins):
    identifiers = sorted(set(asins))
    if any(not isinstance(asin, str) or not re.fullmatch(r"[A-Z0-9]{10}", asin) for asin in identifiers):
        raise AmazonError("Customer Feedback contains an invalid child ASIN. Correct the listings catalogue and retry.")
    return identifiers


def _feedback_sort(sort_by):
    if sort_by not in FEEDBACK_SORTS:
        raise AmazonError("Customer Feedback sortBy must be MENTIONS or STAR_RATING_IMPACT")
    return sort_by


def _feedback_reads(fields, keys, reads, *, subject, timeout, sleep, now):
    """Yield `(key, label, body, reason)` per key and read, interleaved so each operation paces its own bucket.

    A 204, 400 or 404 answers one key: body None and a reason. A 403, an exhausted 429 or any other refusal raises.
    """
    token, issued = access_token(fields, timeout=timeout), now()
    for key in keys:
        for label, operation, path, params in reads(key):
            _pace_entity(operation, FEEDBACK_INTERVALS[operation], sleep=sleep, now=now)
            if now() - issued >= 3000:
                token, issued = access_token(fields, timeout=timeout), now()
            try:
                body = _request(path, token, region=str(fields.get("region") or DEFAULT_REGION),
                                sandbox=is_sandbox(fields), timeout=timeout,
                                throttle_fix="continue every child ASIN at the Customer Feedback rate limit",
                                **params)
            except AmazonError as exc:
                status = getattr(exc, "status", None)
                if isinstance(exc, (AmazonThrottled, AmazonOperationRefused)) or status not in (400, 404):
                    raise
                detail = str(getattr(exc, "vendor_message", "") or "").replace("\u2014", ". ").replace("\u2013", " to ")
                detail = re.sub(r"[.\s]+$", "", detail.strip())
                yield key, label, None, (f"Amazon {operation} answered {status} for this {subject} and marketplace: "
                                         + (detail or "no reason given") + ".")
                continue
            if body is None:
                yield key, label, None, f"Amazon {operation} returned 204 No Content for this {subject} and marketplace."
                continue
            yield key, label, body, None


def _feedback_record(operation, asin, marketplace, body, reason):
    """One validated item response, or its absence record."""
    if reason is not None:
        return {"asin": asin, "marketplaceId": marketplace, "_no_feedback_reason": reason}
    root = "topics" if operation == "getItemReviewTopics" else "reviewTrends"
    if (not isinstance(body, dict) or body.get("asin") != asin or body.get("marketplaceId") != marketplace
            or not isinstance(body.get(root), dict)):
        raise AmazonError(f"Amazon {operation} returned an invalid response for the requested child ASIN and marketplace. Retry after Amazon restores its response.")
    for key in ("positiveTopics", "negativeTopics"):
        topics = body[root].get(key)
        if topics is not None and (not isinstance(topics, list) or any(not isinstance(t, dict) for t in topics)):
            raise AmazonError(f"Amazon {operation} returned invalid {key}. No partial snapshot was stored.")
    return body


def _browse_node_record(body, reason):
    """`{"browse_node_id", "browse_node_name"}` from getItemBrowseNode, or its absence."""
    if reason is not None:
        return {"_no_feedback_reason": reason}
    node, name = (body.get(k) if isinstance(body, dict) else None for k in ("browseNodeId", "displayName"))
    if not isinstance(node, str) or not re.fullmatch(r"\d{1,20}", node) or (name is not None and not isinstance(name, str)):
        raise AmazonError("Amazon getItemBrowseNode returned no valid browse node. No partial snapshot was stored.")
    return {"browse_node_id": node, "browse_node_name": name}


def item_review_feedback(fields, asins, *, operation="getItemReviewTopics", sort_by="MENTIONS", timeout=_TIMEOUT,
                         sleep=time.sleep, now=time.monotonic):
    """Read every child ASIN, retaining known absences separately from invalid responses."""
    if operation not in ("getItemReviewTopics", "getItemReviewTrends"):
        raise AmazonOperationRefused("unapproved Customer Feedback reader")
    _feedback_admitted(operation)
    params = {"sortBy": _feedback_sort(sort_by)} if operation == "getItemReviewTopics" else {}
    identifiers = _feedback_child_asins(asins)
    if not identifiers:
        return []
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    path = OPERATIONS[operation]["path"]
    reads = lambda asin: [(None, operation, path.replace("{asin}", asin), {"marketplaceId": marketplace, **params})]
    return [_feedback_record(operation, asin, marketplace, body, reason) for asin, _label, body, reason in
            _feedback_reads(fields, identifiers, reads, subject="ASIN", timeout=timeout, sleep=sleep, now=now)]


def item_browse_nodes(fields, asins, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """`{asin: {"browse_node_id", "browse_node_name"}}` for every child ASIN; an absence carries `_no_feedback_reason`."""
    _feedback_admitted("getItemBrowseNode")
    identifiers = _feedback_child_asins(asins)
    if not identifiers:
        return {}
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    path = OPERATIONS["getItemBrowseNode"]["path"]
    reads = lambda asin: [(None, "getItemBrowseNode", path.replace("{asin}", asin), {"marketplaceId": marketplace})]
    return {asin: _browse_node_record(body, reason) for asin, _label, body, reason in
            _feedback_reads(fields, identifiers, reads, subject="ASIN", timeout=timeout, sleep=sleep, now=now)}


def item_review_topics(fields, asins, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """Per child ASIN: its browse node and its topics by both sorts, interleaved on one token.

    Returns `{"MENTIONS": [record], "STAR_RATING_IMPACT": [record], "browse_nodes": {asin: node}}`.
    """
    for operation in ("getItemBrowseNode", "getItemReviewTopics"):
        _feedback_admitted(operation)
    identifiers = _feedback_child_asins(asins)
    out = {**{sort: [] for sort in FEEDBACK_SORTS}, "browse_nodes": {}}
    if not identifiers:
        return out
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    node_path, topic_path = (OPERATIONS[name]["path"] for name in ("getItemBrowseNode", "getItemReviewTopics"))

    def reads(asin):
        return [("browse_node", "getItemBrowseNode", node_path.replace("{asin}", asin), {"marketplaceId": marketplace}),
                *((sort, "getItemReviewTopics", topic_path.replace("{asin}", asin),
                   {"marketplaceId": marketplace, "sortBy": sort}) for sort in FEEDBACK_SORTS)]
    for asin, label, body, reason in _feedback_reads(fields, identifiers, reads, subject="ASIN",
                                                     timeout=timeout, sleep=sleep, now=now):
        if label == "browse_node":
            out["browse_nodes"][asin] = _browse_node_record(body, reason)
        else:
            out[label].append(_feedback_record("getItemReviewTopics", asin, marketplace, body, reason))
    return out


def browse_node_review_topics(fields, node_ids, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """Each browse node's top category topics by both sorts: `{sort: [record]}`; an absence carries `_no_feedback_reason`."""
    _feedback_admitted("getBrowseNodeReviewTopics")
    nodes = sorted(set(node_ids))
    # The id becomes a path segment, so only a numeric browse node id is admitted.
    if any(not isinstance(node, str) or not re.fullmatch(r"\d{1,20}", node) for node in nodes):
        raise AmazonError("Customer Feedback contains an invalid browse node ID. Retry after Amazon returns a numeric browse node.")
    out = {sort: [] for sort in FEEDBACK_SORTS}
    if not nodes:
        return out
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    path = OPERATIONS["getBrowseNodeReviewTopics"]["path"]
    reads = lambda node: [(sort, "getBrowseNodeReviewTopics", path.replace("{browseNodeId}", node),
                           {"marketplaceId": marketplace, "sortBy": sort}) for sort in FEEDBACK_SORTS]
    for node, sort, body, reason in _feedback_reads(fields, nodes, reads, subject="browse node",
                                                    timeout=timeout, sleep=sleep, now=now):
        if reason is not None:
            out[sort].append({"browseNodeId": node, "marketplaceId": marketplace, "_no_feedback_reason": reason})
            continue
        if (not isinstance(body, dict) or str(body.get("browseNodeId")) != node
                or body.get("marketplaceId") != marketplace or not isinstance(body.get("topics"), dict)):
            raise AmazonError("Amazon getBrowseNodeReviewTopics returned an invalid response for the requested browse node and marketplace. Retry after Amazon restores its response.")
        for key in ("positiveTopics", "negativeTopics"):
            topics = body["topics"].get(key)
            if topics is not None and (not isinstance(topics, list) or any(not isinstance(t, dict) for t in topics)):
                raise AmazonError(f"Amazon getBrowseNodeReviewTopics returned invalid {key}. No partial snapshot was stored.")
        out[sort].append(body)
    return out


def group_a_records(fields, operation, *, start=None, end=None, asins=(),
                    timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """Fixed GET readers, every page and every own-ASIN batch; no record ceiling."""
    if operation not in ENTITY_INTERVALS or operation == "getMyFeesEstimates":
        raise AmazonOperationRefused("unapproved group (a) reader")
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    path = OPERATIONS[operation]["path"]
    params = {"marketplaceIds": marketplace}
    if operation == "getOrderMetrics":
        params.update(interval=f"{start}--{end}", granularity="Day", granularityTimeZone="UTC")
        root, payload_key, next_key = None, "payload", None
    elif operation == "getInventorySummaries":
        params.update(details="true", granularityType="Marketplace", granularityId=marketplace)
        root, payload_key, next_key = "inventorySummaries", "payload", "nextToken"
    elif operation == "searchListingsItems":
        seller = str(fields.get("seller_id") or "")
        if not re.fullmatch(r"[A-Za-z0-9]+", seller):
            raise AmazonError("Listing status needs the seller ID saved with the connection")
        path = path.replace("{sellerId}", seller)
        params.update(includedData="summaries,issues,offers,fulfillmentAvailability,attributes", pageSize=20)
        root, payload_key, next_key = "items", None, "pageToken"
    else:
        # `relationships` (S67-T29, O23): same Catalog Items endpoint and Product Listing role;
        # it carries VARIATION parentAsins so the mirror can map every own ASIN to its parent.
        # `images` names each ASIN's listing pictures; `amazon_pictures` stores the MAIN one.
        params.update(identifiersType="ASIN",
                      includedData="summaries,salesRanks,dimensions,attributes,relationships,images",
                      pageSize=20)
        root, payload_key, next_key = "items", None, "pageToken"
    batches = [None]
    if operation == "searchCatalogItems":
        identifiers = sorted(set(asins))
        if any(not re.fullmatch(r"[A-Z0-9]{10}", str(a)) for a in identifiers):
            raise AmazonError("Catalog contains an invalid ASIN; correct the listings or pricing mirror and retry")
        batches = [identifiers[i:i + 20] for i in range(0, len(identifiers), 20)]
        if not batches:
            raise AmazonError("Catalog attributes are waiting for our ASINs; sync Amazon listings first")
    token, issued = access_token(fields, timeout=timeout), now()
    rows = []
    listing_end = datetime.now(timezone.utc)
    # Date partitions bypass Listings search's 1,000-item pagination ceiling.
    # Inclusive boundaries are deduplicated by SKU after every partition has finished.
    if operation == "searchListingsItems":
        batches = [(datetime(1970, 1, 1, tzinfo=timezone.utc), listing_end)]
    for batch in batches:
        query, seen = dict(params), set()
        if operation == "searchListingsItems":
            lower, upper = batch
            query.update(createdAfter=lower.isoformat(), createdBefore=upper.isoformat())
        elif batch is not None:
            query["identifiers"] = ",".join(batch)
        page_rows, expected = [], None
        while True:
            _pace_entity(operation, ENTITY_INTERVALS[operation], sleep=sleep, now=now)
            if now() - issued >= 3000:
                token, issued = access_token(fields, timeout=timeout), now()
            got = _request(path, token, region=str(fields.get("region") or DEFAULT_REGION),
                           sandbox=is_sandbox(fields), timeout=timeout, **query,
                           throttle_fix=f"continue every page at Amazon's {1 / ENTITY_INTERVALS[operation]:g} requests per second")
            body = got.get(payload_key) if payload_key else got
            if operation == "searchListingsItems" and isinstance(body, dict):
                count = body.get("numberOfResults")
                if isinstance(count, int) and count > 1000:
                    midpoint = lower + (upper - lower) / 2
                    if (upper - lower) <= timedelta(milliseconds=1):
                        raise AmazonError("Amazon Listings search exceeds its 1,000 SKU limit within one millisecond. "
                                          "No partial snapshot was stored. Ask Amazon to raise this search limit or use a SKU-filtered export.")
                    batches.extend(((lower, midpoint), (midpoint, upper)))
                    page_rows = []
                    break
            page = body.get(root) if root and isinstance(body, dict) else body
            if not isinstance(page, list) or any(not isinstance(row, dict) for row in page):
                raise AmazonError(f"{operation} returned no valid row list; retry after Amazon restores its response")
            page_rows.extend(page)
            if isinstance(body, dict) and type(body.get("numberOfResults")) is int:
                expected = max(expected or 0, body["numberOfResults"])
            following = (got.get("pagination") or {}).get("nextToken")
            if isinstance(body, dict):
                following = following or (body.get("pagination") or {}).get("nextToken") or body.get("nextToken")
            if not following:
                if expected is not None and len(page_rows) != expected:
                    raise AmazonError(f"{operation} reported {expected} rows but returned {len(page_rows)}. "
                                      "No partial snapshot was stored; retry after Amazon restores complete pagination.")
                break
            if not next_key or following in seen:
                raise AmazonError(f"{operation} repeated or cannot follow its nextToken; retry after Amazon fixes pagination")
            seen.add(following)
            query[next_key] = following
        rows.extend(page_rows)
    if operation == "searchListingsItems":
        unique = {}
        for row in rows:
            if not row.get("sku"):
                raise AmazonError("Amazon listing search omitted a SKU; cannot reconcile date partition boundaries")
            unique[row["sku"]] = row
        rows = list(unique.values())
    return rows


#: getOrderMetrics refuses a Month interval over about two years ("2130D exceeded limit"); 731 days answers.
ORDER_MONTHS_MAX = 24


def _parse_utc(value):
    """A datetime or ISO string as an aware UTC datetime; a bare date reads as UTC midnight."""
    if isinstance(value, str):
        value = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if value.tzinfo is None:
        value = value.replace(tzinfo=timezone.utc)
    return value.astimezone(timezone.utc)


def order_months(fields, start, end, *, timeout=_TIMEOUT, sleep=time.sleep, now=time.monotonic):
    """[(month_start "YYYY-MM-01", orderCount)] for [start, end) from getOrderMetrics granularity Month."""
    lower = _parse_utc(start).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    upper = _parse_utc(end).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
    months = (upper.year - lower.year) * 12 + upper.month - lower.month
    if months <= 0:
        return []
    if months > ORDER_MONTHS_MAX:
        raise AmazonError(f"getOrderMetrics answers at most {ORDER_MONTHS_MAX} months per Month interval")
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    operation = "getOrderMetrics"
    token = access_token(fields, timeout=timeout)
    _pace_entity(operation, ENTITY_INTERVALS[operation], sleep=sleep, now=now)
    got = _request(OPERATIONS[operation]["path"], token, region=str(fields.get("region") or DEFAULT_REGION),
                   sandbox=is_sandbox(fields), timeout=timeout, marketplaceIds=marketplace,
                   interval=f"{lower.strftime('%Y-%m-%dT%H:%M:%SZ')}--{upper.strftime('%Y-%m-%dT%H:%M:%SZ')}",
                   granularity="Month", granularityTimeZone="UTC",
                   throttle_fix=f"continue at Amazon's {1 / ENTITY_INTERVALS[operation]:g} requests per second")
    body = got.get("payload") if isinstance(got, dict) else None
    if not isinstance(body, list) or any(not isinstance(row, dict) for row in body):
        raise AmazonError("getOrderMetrics returned no valid month list; retry after Amazon restores its response")
    out = []
    for row in body:
        month = str(row.get("interval") or "").split("--", 1)[0][:7]
        count = row.get("orderCount")
        if not re.fullmatch(r"\d{4}-\d{2}", month) or type(count) is not int or count < 0:
            raise AmazonError("getOrderMetrics returned a month without an interval or a nonnegative orderCount")
        first = datetime.fromisoformat(month + "-01").replace(tzinfo=timezone.utc)
        if lower <= first < upper:
            out.append((month + "-01", count))
    return sorted(out)


def _post_form(url, data, timeout=_TIMEOUT):
    # LWA exchanges credentials at api.amazon.com, not an SP-API operation. Its sole caller fixes
    # LWA_TOKEN_URL; the connector-wide gate checks that call separately from OPERATIONS.
    body = urllib.parse.urlencode(data).encode("ascii")
    req = urllib.request.Request(url, data=body, method="POST")
    req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
    req.add_header("User-Agent", _UA)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read().decode("utf-8") or "{}")
    except urllib.error.HTTPError as e:
        detail = ""
        try:
            payload = json.loads((e.read() or b"").decode("utf-8") or "{}")
            # LWA answers {error, error_description}. Neither echoes the secret.
            detail = str(payload.get("error_description") or payload.get("error") or "")[:200]
        except Exception:                                              # noqa: BLE001
            detail = ""
        raise AmazonError(f"{_safe(url)} answered {e.code}"
                          + (f": {detail}" if detail else "")) from None
    except Exception as e:                                             # noqa: BLE001
        raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None


def access_token(fields, timeout=_TIMEOUT):
    """Exchange a stored refresh token for a ~1 hour LWA access token.

    ⛔ The returned value is a live bearer credential. It is never logged, never written to disk,
    and never returned to a client: callers hold it for the length of one sync and drop it.
    """
    f = fields or {}
    missing = [k for k in ("client_id", "client_secret", "refresh_token") if not f.get(k)]
    if missing:
        raise AmazonError("credential is missing " + ", ".join(f"`{m}`" for m in missing))
    got = _post_form(LWA_TOKEN_URL, {
        "grant_type": "refresh_token",
        "refresh_token": str(f["refresh_token"]),
        "client_id": str(f["client_id"]),
        "client_secret": str(f["client_secret"]),
    }, timeout=timeout)
    tok = str(got.get("access_token") or "")
    if not tok:
        raise AmazonError("LWA returned no access token")
    _remember_token(f, tok)
    return tok


def notifications_token(fields, timeout=_TIMEOUT):
    """Mint a grantless Notifications token without reading the seller refresh token."""
    if not all(fields.get(key) for key in ("client_id", "client_secret")):
        raise AmazonError("Notifications requires client_id and client_secret in the keychain.")
    try:
        got = _post_form(LWA_TOKEN_URL, {
            "grant_type": "client_credentials", "scope": NOTIFICATIONS_SCOPE,
            "client_id": str(fields["client_id"]), "client_secret": str(fields["client_secret"]),
        }, timeout=timeout)
    except AmazonError as exc:
        reason = str(exc)
        for key in ("client_id", "client_secret"):
            reason = reason.replace(str(fields[key]), "[redacted]")
        raise AmazonError(reason.replace("\u2014", ". ").replace("\u2013", " to ")) from None
    if not got.get("access_token"):
        raise AmazonError("LWA returned no grantless Notifications access token.")
    tok = str(got["access_token"])
    _remember_token(fields, tok)
    return tok


class AmazonNotificationError(AmazonError):
    """An Amazon Notifications refusal carries its status and safe cause."""

    def __init__(self, status, reason):
        self.status = status
        super().__init__(f"Amazon Notifications answered {status}: {reason}")


def _notifications_post(operation, token, body, *, notification_type=None,
                        region=DEFAULT_REGION, sandbox=False, timeout=_TIMEOUT):
    """Create only a fixed EventBridge destination or an approved notification subscription."""
    if operation == "createDestination":
        path = _NOTIFICATION_DESTINATIONS_PATH
        bridge = (body.get("resourceSpecification") or {}).get("eventBridge") or {}
        if (set(body) != {"name", "resourceSpecification"}
                or body["name"] != "Loopable"
                or body["resourceSpecification"] != {"eventBridge": bridge}
                or set(bridge) != {"accountId", "region"}
                or not re.fullmatch(r"[0-9]{12}", str(bridge.get("accountId", "")))
                or not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-[0-9]+", str(bridge.get("region", "")))):
            raise AmazonError("Notifications destination requires an AWS account and region.")
    elif operation == "createSubscription" and notification_type in NOTIFICATION_TYPES:
        path = _NOTIFICATION_SUBSCRIPTIONS_PATH + "/" + notification_type
        if (set(body) != {"payloadVersion", "destinationId"}
                or body["payloadVersion"] != NOTIFICATION_TYPES[notification_type]["payload_version"]
                or not re.fullmatch(r"[A-Za-z0-9_.-]+", str(body["destinationId"]))):
            raise AmazonError("Notifications subscription requires an approved type and destination.")
    else:
        raise AmazonOperationRefused("Notifications operation")
    require_operation("POST", path)
    scope = _scope_for(token, region, sandbox)
    base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region or DEFAULT_REGION).lower())
    if not base:
        raise AmazonError("Notifications SP-API region is unknown.")

    def attempt():
        req = urllib.request.Request(f"{base}/{path}", data=json.dumps(body).encode("utf-8"), method="POST")
        req.add_header("x-amz-access-token", token)
        req.add_header("Content-Type", "application/json")
        req.add_header("User-Agent", _UA)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as response:
                _observe_rate(operation, scope, getattr(response, "headers", None))
                return json.loads(response.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as exc:
            _observe_rate(operation, scope, exc.headers)
            try:
                errors = json.loads(exc.read().decode("utf-8")).get("errors") or []
                reason = str(errors[0].get("message") or "Amazon refused this notification operation.")
            except (ValueError, KeyError, IndexError, TypeError):
                reason = "Amazon refused this notification operation."
            reason = reason.replace(token, "[redacted]").replace("\u2014", ". ").replace("\u2013", " to ")
            if exc.code == 429:
                raise AmazonThrottled("Amazon Notifications throttled (429). Retry with fewer setup calls.",
                                      retry_after=(exc.headers or {}).get("Retry-After")) from None
            raise AmazonNotificationError(exc.code, reason[:500]) from None
        except (OSError, ValueError) as exc:
            raise AmazonError(f"Amazon Notifications unavailable: {type(exc).__name__}.") from None

    return _retry(attempt, f"{base}/{path}", operation=operation, scope=scope)


def ensure_notifications(fields, aws_account_id, aws_region, *, granted_roles, timeout=_TIMEOUT):
    """Ensure only EventBridge subscriptions, returning their IDs and safe skip causes."""
    account, aws_region = str(aws_account_id), str(aws_region)
    if (not re.fullmatch(r"[0-9]{12}", account)
            or not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-[0-9]+", aws_region)):
        raise AmazonError("Notifications destination requires an AWS account and region.")
    bridge = {"accountId": account, "region": aws_region}
    region, sandbox = fields.get("region") or DEFAULT_REGION, is_sandbox(fields)
    grantless = notifications_token(fields, timeout=timeout)
    found = _request(_NOTIFICATION_DESTINATIONS_PATH, grantless, region=region,
                     sandbox=sandbox, timeout=timeout).get("payload") or []
    destination = next((row for row in found
                        if all(((row.get("resource") or {}).get("eventBridge") or {}).get(key) == value
                               for key, value in bridge.items())), None)
    if destination is None:
        destination = _notifications_post("createDestination", grantless, {
            "name": "Loopable", "resourceSpecification": {"eventBridge": bridge}},
            region=region, sandbox=sandbox, timeout=timeout).get("payload") or {}
    destination_id = destination.get("destinationId")
    if not isinstance(destination_id, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", destination_id):
        raise AmazonError("Amazon Notifications returned no valid destination ID.")
    # Destination setup remains grantless even when the seller has granted no event roles.
    seller_token, states = None, {}
    for event_type, spec in NOTIFICATION_TYPES.items():
        if "EventBridge" not in spec["destinations"]:
            states[event_type] = {"state": "skipped", "reason":
                "Amazon delivers this notification only to SQS. "
                "Set up an Amazon Simple Queue Service (SQS) queue and subscribe this type to it."}
            continue
        if not set(spec["roles"]).intersection(granted_roles):
            states[event_type] = {"state": "skipped", "reason":
                "Amazon requires one of these granted roles for " + event_type + ": "
                + ", ".join(spec["roles"]) + ". This connection has not granted one."}
            continue
        if seller_token is None:
            seller_token = access_token(fields, timeout=timeout)
        try:
            try:
                subscription = _request(_NOTIFICATION_SUBSCRIPTIONS_PATH + "/" + event_type,
                                        seller_token, region=region, sandbox=sandbox, timeout=timeout,
                                        payloadVersion=spec["payload_version"]).get("payload") or {}
            except AmazonError as exc:
                # Only an absent subscription can be created. Auth and vendor failures stay visible.
                if not isinstance(exc, AmazonNotificationError) or exc.status != 404:
                    raise
                subscription = {}
            if subscription and subscription.get("destinationId") != destination_id:
                raise AmazonError("Amazon already sends this type to another destination. Review its existing subscription.")
            if not subscription:
                subscription = _notifications_post("createSubscription", seller_token, {
                    "payloadVersion": spec["payload_version"], "destinationId": destination_id},
                    notification_type=event_type, region=region, sandbox=sandbox,
                    timeout=timeout).get("payload") or {}
            if not subscription.get("subscriptionId"):
                raise AmazonError("Amazon Notifications returned no subscription ID.")
            states[event_type] = {"state": "subscribed", "subscriptionId": subscription["subscriptionId"]}
        except AmazonError as exc:
            reason = str(exc)
            for value in (grantless, seller_token, *(str(fields.get(key) or "")
                          for key in ("client_id", "client_secret", "refresh_token"))):
                if value:
                    reason = reason.replace(value, "[redacted]")
            states[event_type] = {"state": "skipped", "reason":
                reason.replace("\u2014", ". ").replace("\u2013", " to ")}
    return {"destinationId": destination_id, "subscriptions": states}


def _request(path, token, region=DEFAULT_REGION, method="GET", timeout=_TIMEOUT,
             sandbox=False, throttle_fix=None, **params):
    """One read-only SP-API call. Returns the decoded JSON body.

    ⛔ NON-GET IS REFUSED HERE, BEFORE THE REQUEST IS BUILT. There is no flag, no keyword and no
    caller that can turn this off, which is the point: the guard sits below every route, payload
    and UI, so nothing above it has to be trusted to stay read-only.
    """
    if str(method).upper() != "GET":
        raise AmazonError("this connector is read-only: only GET is permitted")
    require_operation(method, path)
    operation = operation_for(method, path)["name"]
    scope = _scope_for(token, region, sandbox)

    def attempt():
        """One raw read-only SP-API attempt, with no retry or pacing policy."""
        # ⚠ AN EXPLICIT FLAG, NOT A `fields` DICT. This function is handed a TOKEN, never the
        # credential -- deliberately, so a secret cannot reach the request builder at all -- so the
        # sandbox decision is made by the caller that does hold the credential and passed in as one
        # boolean. A first draft reached for `fields` here, which does not exist in this scope.
        base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
            str(region or DEFAULT_REGION).lower())
        if not base:
            raise AmazonError(f"unknown region `{region}`")
        clean = {k: v for k, v in (params or {}).items() if v not in (None, "")}
        url = f"{base}/{str(path).lstrip('/')}"
        if clean:
            url += "?" + urllib.parse.urlencode(clean, doseq=True)
        req = urllib.request.Request(url, method="GET")
        req.add_header("x-amz-access-token", token)
        req.add_header("Accept", "application/json")
        req.add_header("User-Agent", _UA)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                _observe_rate(operation, scope, getattr(r, "headers", None))
                if (operation in FEEDBACK_INTERVALS
                        and getattr(r, "status", None) == 204):
                    return None
                return json.loads(r.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as e:
            _observe_rate(operation, scope, e.headers)
            detail = ""
            try:
                payload = json.loads((e.read() or b"").decode("utf-8") or "{}")
                errs = payload.get("errors") or []
                if errs:
                    detail = str((errs[0] or {}).get("message") or "")[:200]
            except Exception:                                              # noqa: BLE001
                detail = ""
            # 429 is the rate limiter, and standing rule 1 wants it NAMED rather than swallowed.
            if e.code == 429:
                fix = throttle_fix or "use the Reports API bulk path instead of a slower page loop"
                raise AmazonThrottled(
                    f"{_safe(url)} was throttled (429). SP-API is token-bucket limited per operation; "
                    f"the fix is to {fix}",
                    retry_after=(e.headers or {}).get("Retry-After")) from None
            if path.startswith("notifications/v1/"):
                reason = (detail or "Amazon refused this notification operation.").replace(token, "[redacted]")
                raise AmazonNotificationError(e.code, reason.replace("\u2014", ". ").replace("\u2013", " to ")) from None
            refusal = AmazonError(f"{_safe(url)} answered {e.code}" + (f": {detail}" if detail else ""))
            # Callers branch on the status attribute, never on the message text.
            refusal.status, refusal.vendor_message = e.code, detail
            raise refusal from None
        except Exception as e:                                             # noqa: BLE001
            raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None

    base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
        str(region or DEFAULT_REGION).lower(), "")
    return _retry(
        attempt, f"{base}/{str(path).lstrip('/')}",
        operation=operation, scope=scope,
        exhausted_fix=(throttle_fix
                       or "use the Reports API bulk path instead of a slower page loop"))


# Amazon models: models/{fulfillment-inbound-api-model,feeds-api-model} in
# https://github.com/amzn/selling-partner-api-models
SP_NAMED_WRITES = {
    "inbound_plan": ("createInboundPlan", "POST", "inbound/fba/2024-03-20/inboundPlans"),
    "inbound_plan_cancel": ("cancelInboundPlan", "PUT",
                            "inbound/fba/2024-03-20/inboundPlans/{inboundPlanId}/cancellation"),
    "removal_order": ("createFeed", "POST", "feeds/2021-06-30/feeds"),
}
APPROVAL_SOURCES = {
    "inbound_plan": {"modules.restock_planner": "modules.amazon_operator:app_approval"},
    "inbound_plan_cancel": {"modules.restock_planner": "modules.amazon_operator:app_approval"},
    "removal_order": {
        "modules.returns_refunds": "modules.returns_refunds:removal_approval",
        "modules.aged_stock": "modules.aged_stock:removal_approval",
    },
}
# Readers return {tenant_key, decision, approved_by, item_ids, writes: [{kind, payload}]}.
# A cancellation reader also returns original_plan, the saved successful create receipt.
# Producers persist the receipt before allowing another send for that approval.
REMOVAL_FEED_TYPE = "POST_FLAT_FILE_FBA_CREATE_REMOVAL"
_REMOVAL_CONTENT_TYPE = "text/tab-separated-values; charset=UTF-8"


class AmazonWriteRefused(AmazonError):
    """A named write failed local validation before credentials or transport access."""


def _sp_text(value, maximum=1024):
    return (isinstance(value, str) and 0 < len(value) <= maximum and bool(value.strip())
            and not any(ord(c) < 32 for c in value))


def _sp_item_ids(value):
    return (isinstance(value, list) and bool(value) and all(_sp_text(v) for v in value)
            and len(set(value)) == len(value))


def _removal_rows(content):
    """Parse every metadata and SKU row of Amazon's tab-separated removal template."""
    # https://developer-docs.amazon.com/sp-api/docs/fulfillment-by-amazon-feed-type-values
    if not isinstance(content, str) or not content or "\x00" in content:
        raise AmazonWriteRefused("removal content must be a UTF-8 tab-separated file")
    metadata, items, in_items = {}, [], False
    allowed = {"MerchantRemovalOrderID", "RemovalDisposition", "AddressName", "AddressFieldOne",
               "AddressFieldTwo", "AddressFieldThree", "AddressCity", "AddressCountryCode",
               "AddressStateOrRegion", "AddressPostalCode", "ContactPhoneNumber",
               "ShippingNotes", "RemoveFromCountryCode"}
    try:
        for row in csv.reader(io.StringIO(content), delimiter="\t", strict=True):
            if not row or not any(row):
                continue
            if any(any(ord(c) < 32 for c in cell) for cell in row):
                raise AmazonWriteRefused("removal cells must not contain embedded control characters")
            if row == ["MerchantSKU", "SellableQuantity", "UnsellableQuantity"] and not in_items:
                in_items = True
                continue
            if not in_items:
                if (len(row) not in (2, 3) or row[0] not in allowed or row[0] in metadata
                        or (len(row) == 3 and row[2])):
                    raise AmazonWriteRefused("removal metadata is unknown, duplicate or malformed")
                metadata[row[0]] = row[1]
                continue
            if (len(row) != 3 or not _sp_text(row[0], 255)
                    or any(not re.fullmatch(r"[0-9]+", v or "") for v in row[1:])
                    or sum(int(v) for v in row[1:]) <= 0):
                raise AmazonWriteRefused("every removal SKU row needs two quantities and positive total units")
            disposition = {"Return": "Return", "RETURN": "Return", "Disposal": "Disposal",
                           "DISPOSAL": "Disposal"}.get(metadata.get("RemovalDisposition"))
            if disposition is None:
                raise AmazonWriteRefused("every removal row must be Return or Disposal")
            items.append({"msku": row[0], "sellable": int(row[1]), "unsellable": int(row[2]),
                          "disposition": disposition})
    except (csv.Error, ValueError):
        raise AmazonWriteRefused("removal file is malformed") from None
    if (not items or len({r["msku"] for r in items}) != len(items)
            or not _sp_text(metadata.get("MerchantRemovalOrderID"), 40)
            or metadata.get("RemovalDisposition") not in ("Return", "RETURN", "Disposal", "DISPOSAL")):
        raise AmazonWriteRefused("removal file needs one order, unique SKUs and Return or Disposal")
    if metadata["RemovalDisposition"] in ("Return", "RETURN") and any(not _sp_text(metadata.get(k)) for k in (
            "AddressName", "AddressFieldOne", "AddressCity", "AddressCountryCode", "AddressPostalCode")):
        raise AmazonWriteRefused("a return removal needs its approved ship-to address")
    return items


def _prepare_sp_named_write(kind, payload):
    """Validate the complete payload and resolve only a C3 operation."""
    rule = SP_NAMED_WRITES.get(kind)
    if not rule or not isinstance(payload, dict) or payload.get("operation") != rule[0]:
        raise AmazonWriteRefused("the operation is not a named SP-API write")
    if not _sp_item_ids(payload.get("item_ids")):
        raise AmazonWriteRefused("a named write needs its exact approved item ids")
    common = {"operation", "item_ids"}
    operation, method, path = rule
    if kind == "inbound_plan":
        if set(payload) != common | {"body"}:
            raise AmazonWriteRefused("inbound plan payload has unknown fields")
        body = payload["body"]
        if (not isinstance(body, dict)
                or set(body) - {"destinationMarketplaces", "items", "sourceAddress", "name"}
                or not isinstance(body.get("destinationMarketplaces"), list)
                or len(body["destinationMarketplaces"]) != 1
                or not _sp_text(body["destinationMarketplaces"][0], 20)
                or not isinstance(body.get("items"), list) or not 1 <= len(body["items"]) <= 2000):
            raise AmazonWriteRefused("inbound plan needs one marketplace and 1 to 2000 items. Split larger batches explicitly")
        if "name" in body and not _sp_text(body["name"], 40):
            raise AmazonWriteRefused("inbound plan name is invalid")
        seen = set()
        for item in body["items"]:
            if (not isinstance(item, dict)
                    or set(item) - {"msku", "quantity", "labelOwner", "prepOwner", "expiration", "manufacturingLotCode"}
                    or not _sp_text(item.get("msku"), 255) or item["msku"] in seen
                    or type(item.get("quantity")) is not int or not 1 <= item["quantity"] <= 500000
                    or item.get("labelOwner") not in ("SELLER", "AMAZON", "NONE")
                    or item.get("prepOwner") not in ("SELLER", "AMAZON", "NONE")):
                raise AmazonWriteRefused("inbound plan item has invalid SKU, quantity, label owner or prep owner")
            seen.add(item["msku"])
            if body["destinationMarketplaces"] == [US_MARKETPLACE_ID] and item["labelOwner"] == "AMAZON":
                raise AmazonWriteRefused("Amazon labeling is unavailable in the US marketplace")
            if "expiration" in item:
                try:
                    if date.fromisoformat(item["expiration"]).isoformat() != item["expiration"]:
                        raise ValueError
                except (TypeError, ValueError):
                    raise AmazonWriteRefused("inbound item expiration must be YYYY-MM-DD") from None
            if "manufacturingLotCode" in item and not _sp_text(item["manufacturingLotCode"], 256):
                raise AmazonWriteRefused("inbound item lot code is invalid")
        address = body.get("sourceAddress")
        sizes = {"addressLine1": 180, "addressLine2": 60, "city": 30, "companyName": 50,
                 "countryCode": 2, "districtOrCounty": 50, "email": 1024, "name": 50,
                 "phoneNumber": 20, "postalCode": 32, "stateOrProvinceCode": 64}
        if (not isinstance(address, dict) or set(address) - sizes.keys()
                or not {"addressLine1", "city", "countryCode", "name", "phoneNumber", "postalCode"} <= address.keys()
                or any(not _sp_text(v, sizes[k]) for k, v in address.items())
                or not re.fullmatch(r"[A-Z]{2}", address["countryCode"])):
            raise AmazonWriteRefused("inbound plan needs a valid sourceAddress")
    elif kind == "inbound_plan_cancel":
        if (set(payload) != common | {"inboundPlanId", "original_approval_id"}
                or not isinstance(payload.get("inboundPlanId"), str)
                or not re.fullmatch(r"[a-zA-Z0-9-]{38}", payload["inboundPlanId"])
                or not _sp_text(payload.get("original_approval_id"))):
            raise AmazonWriteRefused("cancel needs the original plan id and original approval id")
        path = path.format(inboundPlanId=payload["inboundPlanId"])
        body = None
    else:
        if (set(payload) - (common | {"feedType", "marketplaceIds", "content", "validate_only"})
                or payload.get("feedType") != REMOVAL_FEED_TYPE
                or not isinstance(payload.get("marketplaceIds"), list)
                or not 1 <= len(payload["marketplaceIds"]) <= 25
                or any(not _sp_text(v, 20) for v in payload["marketplaceIds"])
                or type(payload.get("validate_only", False)) is not bool):
            raise AmazonWriteRefused("only POST_FLAT_FILE_FBA_CREATE_REMOVAL is admitted")
        _removal_rows(payload.get("content"))
        body = {"feedType": payload["feedType"], "marketplaceIds": payload["marketplaceIds"]}
    return operation, method, path, body


def _sp_named_approval(tenant_key, approval_id, kind, payload, source):
    """Require an exact batch write and a trusted original sent plan for cancellation."""
    module, _, name = source.partition(":")
    try:
        record = getattr(importlib.import_module(module), name)(tenant_key, approval_id)
    except Exception:
        raise AmazonWriteRefused("the approval could not be read") from None
    if (not isinstance(record, dict) or record.get("tenant_key") != tenant_key
            or record.get("decision") != "approved" or not _sp_text(record.get("approved_by"))
            or not _sp_item_ids(record.get("item_ids"))
            or sorted(record["item_ids"]) != sorted(payload["item_ids"])
            or not isinstance(record.get("writes"), list)
            or {"kind": kind, "payload": payload} not in record["writes"]):
        raise AmazonWriteRefused("the approval does not bind this tenant, batch and exact payload")
    if kind == "inbound_plan_cancel":
        original = record.get("original_plan")
        if (not isinstance(original, dict) or original.get("sent") is not True
                or original.get("kind") != "inbound_plan"
                or original.get("inboundPlanId") != payload["inboundPlanId"]
                or original.get("approval_id") != payload["original_approval_id"]
                or original.get("tenant_key") != tenant_key
                or not _sp_item_ids(original.get("item_ids"))
                or sorted(original["item_ids"]) != sorted(payload["item_ids"])):
            raise AmazonWriteRefused("cancel approval does not name its original sent plan")
    return record


def _sp_write_fields(tenant_key):
    """Resolve credentials only from the matching tenant runtime and keychain."""
    from harness.runtime import get_runtime
    from core.keychain import amazon_creds
    rt = get_runtime(tenant_key)
    if getattr(rt, "key", None) != tenant_key:
        raise AmazonWriteRefused("named write runtime does not match its tenant")
    fields = amazon_creds(rt)
    if not isinstance(fields, dict) or not all(fields.get(k) for k in (
            "client_id", "client_secret", "refresh_token", "marketplace_id", "seller_id")):
        raise AmazonWriteRefused("the tenant has no complete SP-API credential")
    return fields


def send_named_write(tenant_key, kind, payload, *, approval_id):
    """Send one exact approved C3 batch, or validate a removal locally without I/O."""
    caller = sys._getframe(1).f_globals.get("__name__", "")
    source = APPROVAL_SOURCES.get(kind, {}).get(caller)
    if not source:
        raise AmazonWriteRefused("this caller may not send the named SP-API write")
    key = str(tenant_key or "").strip().lower()
    if not key or not _sp_text(approval_id):
        raise AmazonWriteRefused("a named write needs its tenant and approval id")
    try:
        payload = json.loads(json.dumps(payload, allow_nan=False))
    except (TypeError, ValueError):
        raise AmazonWriteRefused("the approved payload must be JSON data") from None
    operation, method, path, body = _prepare_sp_named_write(kind, payload)
    receipt = {"sent": False, "kind": kind, "operation": operation, "method": method, "path": path,
               "tenant_key": key, "approval_id": approval_id, "item_ids": payload["item_ids"]}
    if kind == "removal_order" and payload.get("validate_only") is True:
        return {**receipt, "validated": True, "approval_checked": False,
                "rows": len(_removal_rows(payload["content"]))}
    approved = _sp_named_approval(key, approval_id, kind, payload, source)
    receipt["approved_by"] = approved["approved_by"]
    fields = _sp_write_fields(key)
    marketplaces = (body.get("destinationMarketplaces") if kind == "inbound_plan"
                    else payload.get("marketplaceIds"))
    if marketplaces and any(m != fields["marketplace_id"] for m in marketplaces):
        raise AmazonWriteRefused("the approved marketplace does not match the tenant credential")
    base = base_for(fields)
    with rate_limit_scope(key):
        token = access_token(fields)
        scope = _scope_for(token, fields.get("region", DEFAULT_REGION), is_sandbox(fields))
    logger = logging.getLogger(__name__)

    def call(op, verb, target, data, interval):
        _pace_operation(op, scope, interval, sleep=time.sleep, now=time.monotonic)
        logger.info("amazon_named_write tenant=%s kind=%s operation=%s approval_id=%s approved_by=%s item_ids=%s",
                    key, kind, op, approval_id, receipt["approved_by"], payload["item_ids"])
        req = urllib.request.Request(base + "/" + target, data=data, method=verb,
                                     headers={"x-amz-access-token": token, "Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req, timeout=_TIMEOUT) as response:
                _observe_rate(op, scope, getattr(response, "headers", None))
                return json.loads(response.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as error:
            _observe_rate(op, scope, error.headers)
            if error.code == 400:
                try:
                    errors = json.loads(error.read().decode("utf-8")).get("errors", [])
                    reason = json.dumps(errors, ensure_ascii=True)
                    for secret in (token, fields.get("client_secret"), fields.get("refresh_token")):
                        if secret:
                            reason = reason.replace(secret, "[redacted]")
                except Exception:
                    reason = "Amazon rejected this payload"
                raise AmazonReportError(op + " rejected the approved payload", reason, 400) from None
            # A write is never replayed after an ambiguous response.
            raise AmazonError(f"{op} answered {error.code}. Reconcile this approval before retrying") from None
        except Exception:
            raise AmazonError(f"{op} outcome is unknown. Reconcile this approval before retrying") from None

    if kind == "removal_order":
        document = call("createFeedDocument", "POST", "feeds/2021-06-30/documents",
                        json.dumps({"contentType": _REMOVAL_CONTENT_TYPE}).encode(), 2.0)
        url, document_id = document.get("url"), document.get("feedDocumentId")
        parsed = urllib.parse.urlsplit(str(url or ""))
        if (parsed.scheme != "https" or not (parsed.hostname or "").endswith(".amazonaws.com")
                or parsed.username or parsed.password or parsed.port not in (None, 443)
                or parsed.fragment or not _sp_text(document_id)):
            raise AmazonWriteRefused("Amazon returned an invalid removal upload document")

        def upload():
            logger.info("amazon_named_write tenant=%s kind=%s operation=%s approval_id=%s approved_by=%s item_ids=%s",
                        key, kind, "uploadFeedDocument", approval_id, receipt["approved_by"], payload["item_ids"])
            req = urllib.request.Request(url, data=payload["content"].encode("utf-8"), method="PUT",
                                         headers={"Content-Type": _REMOVAL_CONTENT_TYPE})
            try:
                with urllib.request.urlopen(req, timeout=_TIMEOUT):
                    pass
            except Exception:
                raise AmazonError("removal document upload failed. No feed was created") from None

        upload()
        body["inputFeedDocumentId"] = document_id
    response = call(operation, method, path, None if body is None else json.dumps(body).encode(),
                    1 / 0.0083 if kind == "removal_order" else 0.5)
    result = {**receipt, "sent": True, "approval_checked": True, "response": response}
    if kind == "inbound_plan" and isinstance(response, dict):
        result["inboundPlanId"] = response.get("inboundPlanId")
    return result


#: ⛔ THE SECOND NON-GET SP-API PATH. `getCompetitiveSummary` is an Amazon-defined POST wrapper,
#: but every item in its body is a GET to `_COMPETITIVE_SUMMARY_ITEM_URI`. The path, item method,
#: item URI, included data and 20-item maximum are all fixed below; no caller can turn this into a
#: write-shaped Product Pricing request.
def _competitive_summary_batch(token, asins, marketplace_id, region=DEFAULT_REGION,
                               timeout=_TIMEOUT, sandbox=False):
    """Read one fixed `getCompetitiveSummary` batch. -> its response list."""
    require_operation("POST", _COMPETITIVE_SUMMARY_BATCH_PATH)
    operation, scope = "getCompetitiveSummary", _scope_for(token, region, sandbox)
    items = [str(asin or "").strip() for asin in (asins or ()) if str(asin or "").strip()]
    if not 1 <= len(items) <= COMPETITIVE_SUMMARY_BATCH_SIZE:
        raise AmazonError(
            f"competitive summary needs 1 to {COMPETITIVE_SUMMARY_BATCH_SIZE} ASINs per batch")
    marketplace = str(marketplace_id or "").strip()
    if not marketplace:
        raise AmazonError("competitive summary needs a marketplace_id")

    body = {"requests": [{
        "asin": asin,
        "marketplaceId": marketplace,
        "includedData": list(_COMPETITIVE_SUMMARY_INCLUDED),
        "method": "GET",
        "uri": _COMPETITIVE_SUMMARY_ITEM_URI,
    } for asin in items]}

    def attempt():
        base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
            str(region or DEFAULT_REGION).lower())
        if not base:
            raise AmazonError(f"unknown region `{region}`")
        url = f"{base}/{_COMPETITIVE_SUMMARY_BATCH_PATH}"
        req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), method="POST")
        req.add_header("x-amz-access-token", token)
        req.add_header("Content-Type", "application/json")
        req.add_header("Accept", "application/json")
        req.add_header("User-Agent", _UA)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                _observe_rate(operation, scope, getattr(r, "headers", None))
                got = json.loads(r.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as e:
            _observe_rate(operation, scope, e.headers)
            detail = ""
            try:
                errs = (json.loads((e.read() or b"").decode("utf-8") or "{}").get("errors") or [])
                detail = str((errs[0] or {}).get("message") or "")[:200] if errs else ""
            except Exception:                                          # noqa: BLE001
                detail = ""
            if e.code == 429:
                raise AmazonThrottled(
                    f"{_safe(url)} was throttled (429). getCompetitiveSummary defaults to "
                    "0.033 requests/second with a burst of 1; keep 20 ASINs per batch",
                    retry_after=(e.headers or {}).get("Retry-After")) from None
            if e.code == 403:
                raise AmazonError(
                    f"{_safe(url)} refused getCompetitiveSummary (403). The application needs "
                    "the Pricing role") from None
            raise AmazonError(f"{_safe(url)} answered {e.code}"
                              + (f": {detail}" if detail else "")) from None
        except Exception as e:                                         # noqa: BLE001
            raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
        responses = got.get("responses")
        if not isinstance(responses, list):
            raise AmazonError("getCompetitiveSummary returned no response list")
        return responses

    base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
        str(region or DEFAULT_REGION).lower(), "")
    return _retry(
        attempt, f"{base}/{_COMPETITIVE_SUMMARY_BATCH_PATH}",
        operation=operation, scope=scope,
        exhausted_fix="retain 20 ASINs per batch and lower the batch request rate")


def competitive_summaries(fields, asins, timeout=_TIMEOUT, *, sleep=time.sleep,
                          now=time.monotonic):
    """Read competitive summaries for every distinct ASIN, in complete fixed-size batches."""
    unique = []
    seen = set()
    for raw in asins or ():
        asin = str(raw or "").strip()
        if asin and asin not in seen:
            unique.append(asin)
            seen.add(asin)
    if not unique:
        return []

    f = fields or {}
    region = str(f.get("region") or DEFAULT_REGION)
    marketplace = str(f.get("marketplace_id") or US_MARKETPLACE_ID)
    sandbox = is_sandbox(f)
    token = access_token(f, timeout=timeout)
    token_issued = now()
    out = []
    for offset in range(0, len(unique), COMPETITIVE_SUMMARY_BATCH_SIZE):
        _pace_entity("competitive_summary", COMPETITIVE_SUMMARY_INTERVAL,
                     sleep=sleep, now=now)
        if now() - token_issued >= 3000:
            token = access_token(f, timeout=timeout)
            token_issued = now()
        batch = unique[offset:offset + COMPETITIVE_SUMMARY_BATCH_SIZE]
        responses = _competitive_summary_batch(
            token, batch, marketplace, region=region, timeout=timeout, sandbox=sandbox)
        returned = [str(((r or {}).get("body") or {}).get("asin") or "") for r in responses]
        if len(responses) != len(batch) or sorted(returned) != sorted(batch):
            raise AmazonError(
                "getCompetitiveSummary returned an incomplete or mismatched ASIN batch; refusing "
                "to treat a partial response as complete")
        out.extend(responses)
    return out


_ITEM_OFFERS_BATCH_PATH = "batches/products/pricing/v0/itemOffers"
_ITEM_OFFERS_INNER_METHOD = "GET"
ITEM_OFFERS_BATCH_SIZE = 20
ITEM_OFFERS_INTERVAL = 10.0


def _item_offers_batch(token, asins, marketplace_id, region=DEFAULT_REGION, timeout=_TIMEOUT,
                       sandbox=False, *, sleep=time.sleep, now=time.monotonic):
    """Read one fixed Product Pricing v0 batch whose inner requests are all GETs."""
    require_operation("POST", _ITEM_OFFERS_BATCH_PATH)
    # Another approved POST path would carry these inner requests to a different operation.
    if _ITEM_OFFERS_BATCH_PATH != OPERATIONS["getItemOffersBatch"]["path"]:
        raise AmazonOperationRefused(f"POST {_safe(_ITEM_OFFERS_BATCH_PATH)} is not getItemOffersBatch")
    # Amazon's productPricingV0.json fixes this POST wrapper, GET items and 20-item maximum.
    items = list(asins)
    if (not 1 <= len(items) <= ITEM_OFFERS_BATCH_SIZE
            or any(not isinstance(v, str) or not re.fullmatch(r"[A-Z0-9]{10}", v) for v in items)
            or len(set(items)) != len(items) or not _sp_text(marketplace_id, 20)):
        raise AmazonError("getItemOffersBatch needs 1 to 20 unique ASINs and a marketplace")
    body = {"requests": [{"uri": f"/products/pricing/v0/items/{asin}/offers",
                          "method": _ITEM_OFFERS_INNER_METHOD,
                          "MarketplaceId": marketplace_id, "ItemCondition": "New",
                          "CustomerType": "Consumer"} for asin in items]}
    # The POST wrapper stays read-only only while every inner request is a GET.
    if any(r["method"] != "GET" for r in body["requests"]):
        raise AmazonOperationRefused("getItemOffersBatch inner requests must be GET")
    base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region or DEFAULT_REGION).lower())
    if not base:
        raise AmazonError("unknown region for getItemOffersBatch")
    operation, scope = "getItemOffersBatch", _scope_for(token, region, sandbox)

    def attempt():
        req = urllib.request.Request(base + "/" + _ITEM_OFFERS_BATCH_PATH,
                                     data=json.dumps(body).encode(), method="POST",
                                     headers={"x-amz-access-token": token, "Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req, timeout=timeout) as response:
                _observe_rate(operation, scope, getattr(response, "headers", None))
                result = json.loads(response.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as error:
            _observe_rate(operation, scope, error.headers)
            if error.code == 429:
                raise AmazonThrottled("getItemOffersBatch throttled (429)",
                                      retry_after=(error.headers or {}).get("Retry-After"),
                                      operation=operation) from None
            raise AmazonError(f"getItemOffersBatch answered {error.code}") from None
        except Exception:
            raise AmazonError("getItemOffersBatch unreachable") from None
        responses = result.get("responses") if isinstance(result, dict) else None
        if (not isinstance(responses, list) or len(responses) != len(items)
                or any(not isinstance(r, dict) or not isinstance(r.get("body"), dict)
                       or not isinstance(r.get("status"), dict)
                       or str(r["status"].get("statusCode")) != "200"
                       or r["body"].get("errors") for r in responses)):
            raise AmazonError("getItemOffersBatch returned failed or incomplete items. No partial snapshot was stored")
        returned = [((r["body"].get("payload") or {}).get("ASIN")) for r in responses]
        if sorted(str(v) for v in returned) != sorted(items):
            raise AmazonError("getItemOffersBatch returned mismatched ASINs. No partial snapshot was stored")
        return responses

    return _retry(attempt, base + "/" + _ITEM_OFFERS_BATCH_PATH, operation=operation, scope=scope,
                  sleep=sleep, now=now, exhausted_fix="resume all offer batches at the operation's advertised rate")


def item_offers(fields, asins, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
    """Read every distinct own ASIN in complete batches, without a row cap."""
    unique = list(dict.fromkeys(asins))
    if any(not isinstance(v, str) or not re.fullmatch(r"[A-Z0-9]{10}", v) for v in unique):
        raise AmazonError("item offers needs ASINs of ten uppercase letters or digits")
    if not unique:
        return []
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    if not _sp_text(marketplace, 20):
        raise AmazonError("item offers needs a marketplace")
    token, issued = access_token(fields, timeout=timeout), now()
    out = []
    for offset in range(0, len(unique), ITEM_OFFERS_BATCH_SIZE):
        # Own bucket, as competitive_summaries draws competitive_summary; _retry then skips its pace.
        _pace_entity("getItemOffersBatch", ITEM_OFFERS_INTERVAL, sleep=sleep, now=now)
        if now() - issued >= 3000:
            token, issued = access_token(fields, timeout=timeout), now()
        out.extend(_item_offers_batch(token, unique[offset:offset + ITEM_OFFERS_BATCH_SIZE], marketplace,
                                     region=fields.get("region", DEFAULT_REGION), timeout=timeout,
                                     sandbox=is_sandbox(fields), sleep=sleep, now=now))
    return out


def list_prep_details(fields, mskus, *, timeout=_TIMEOUT):
    """Read prep constraints for every MSKU through Amazon's verified GET operation."""
    items = list(dict.fromkeys(mskus))
    if not items or any(not _sp_text(v, 255) for v in items):
        raise AmazonError("listPrepDetails needs nonblank MSKUs")
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    if not _sp_text(marketplace, 20):
        raise AmazonError("listPrepDetails needs a marketplace")
    token, issued = access_token(fields, timeout=timeout), time.monotonic()
    out = []
    for offset in range(0, len(items), 100):
        if time.monotonic() - issued >= 3000:
            token, issued = access_token(fields, timeout=timeout), time.monotonic()
        # Amazon requires these three characters to be double percent encoded.
        batch = [v.replace("%", "%25").replace("+", "%2B").replace(",", "%2C")
                 for v in items[offset:offset + 100]]
        out.append(_request("inbound/fba/2024-03-20/items/prepDetails", token,
                            region=fields.get("region", DEFAULT_REGION), sandbox=is_sandbox(fields),
                            timeout=timeout, marketplaceId=marketplace, mskus=batch))
    return out


def get_inbound_operation_status(fields, operation_id, *, timeout=_TIMEOUT):
    """Read one asynchronous inbound result through Amazon's verified GET operation."""
    if not isinstance(operation_id, str) or not re.fullmatch(r"[a-zA-Z0-9-]{36,38}", operation_id):
        raise AmazonError("getInboundOperationStatus needs a valid operation id")
    return _request(f"inbound/fba/2024-03-20/operations/{operation_id}",
                    access_token(fields, timeout=timeout), timeout=timeout,
                    region=fields.get("region", DEFAULT_REGION), sandbox=is_sandbox(fields))


FEE_ESTIMATES_BATCH_SIZE = 20
_FEE_ESTIMATES_PATH = "products/fees/v0/feesEstimate"
_fee_estimates_interval = 2.0


def fee_estimate_request(estimate, marketplace_id):
    """Fix the seller SKU or ASIN, fulfillment and complete price basis before deriving a stable request identity."""
    sku, asin = estimate.get("sku"), estimate.get("asin")
    # Product Fees v0 takes SellerSKU or ASIN. It answers "SKU is not a supported IdType" to SKU.
    if sku is None and isinstance(asin, str) and asin.strip():
        id_type, id_value, label = "ASIN", asin, f"ASIN {asin}"
    elif isinstance(sku, str) and sku.strip():
        id_type, id_value, label = "SellerSKU", sku, f"SKU {sku}"
    else:
        raise AmazonError("Fee estimates need a nonempty SKU or ASIN for every requested price")
    fulfilled = estimate.get("is_amazon_fulfilled")
    if type(fulfilled) is not bool:
        raise AmazonError(f"Fee estimates need the fulfillment method for {label}")

    def money(value):
        if not isinstance(value, dict) or not re.fullmatch(r"[A-Z]{3}", str(value.get("CurrencyCode") or "")):
            raise AmazonError(f"Fee estimates need a price currency for {label}")
        try:
            amount = float(value["Amount"])
        except (KeyError, TypeError, ValueError):
            raise AmazonError(f"Fee estimates need a numeric price for {label}") from None
        if isinstance(value["Amount"], bool) or not math.isfinite(amount) or amount < 0:
            raise AmazonError(f"Fee estimates need a finite nonnegative price for {label}")
        return {"CurrencyCode": value["CurrencyCode"], "Amount": amount}

    basis = {"ListingPrice": money(estimate.get("price"))}
    if "shipping" in estimate:
        basis["Shipping"] = money(estimate["shipping"])
        if basis["Shipping"]["CurrencyCode"] != basis["ListingPrice"]["CurrencyCode"]:
            raise AmazonError(f"Fee estimate shipping and price currencies differ for {label}")
    if "points" in estimate:
        points = estimate["points"]
        if not isinstance(points, dict) or type(points.get("PointsNumber")) is not int or points["PointsNumber"] < 0:
            raise AmazonError(f"Fee estimates need a valid points basis for {label}")
        basis["Points"] = {"PointsNumber": points["PointsNumber"]}
        if "PointsMonetaryValue" in points:
            basis["Points"]["PointsMonetaryValue"] = money(points["PointsMonetaryValue"])
    request = {"MarketplaceId": marketplace_id, "IsAmazonFulfilled": fulfilled,
               "PriceToEstimateFees": basis}
    if estimate.get("optional_fulfillment_program"):
        request["OptionalFulfillmentProgram"] = estimate["optional_fulfillment_program"]
    identity = {"IdType": id_type, "IdValue": id_value, "FeesEstimateRequest": request}
    request["Identifier"] = hashlib.sha256(json.dumps(
        identity, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()
    return identity


def _fee_estimates_batch(token, requests, region=DEFAULT_REGION, timeout=_TIMEOUT, sandbox=False,
                         *, sleep=time.sleep, now=time.monotonic):
    """Send only fixed, read-only fee estimate requests at Amazon's operation pace."""
    require_operation("POST", _FEE_ESTIMATES_PATH)
    operation, scope = "getMyFeesEstimates", _scope_for(token, region, sandbox)
    if not 1 <= len(requests) <= FEE_ESTIMATES_BATCH_SIZE:
        raise AmazonError("getMyFeesEstimates needs 1 to 20 estimates per batch")
    # Rebuild each body to refuse caller-supplied methods, paths or unrelated fee operations.
    body = []
    for item in requests:
        request = item["FeesEstimateRequest"]
        price = request["PriceToEstimateFees"]
        id_key = "asin" if item.get("IdType") == "ASIN" else "sku"
        estimate = {id_key: item["IdValue"], "price": price["ListingPrice"],
                    "is_amazon_fulfilled": request["IsAmazonFulfilled"]}
        for source, target in (("Shipping", "shipping"), ("Points", "points")):
            if source in price:
                estimate[target] = price[source]
        if "OptionalFulfillmentProgram" in request:
            estimate["optional_fulfillment_program"] = request["OptionalFulfillmentProgram"]
        canonical = fee_estimate_request(estimate, request["MarketplaceId"])
        if item != canonical:
            raise AmazonOperationRefused("noncanonical fee estimate request")
        body.append(canonical)

    def observe_rate(headers):
        _observe_rate(operation, scope, headers)

    def attempt():
        base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(str(region or DEFAULT_REGION).lower())
        if not base:
            raise AmazonError(f"unknown region `{region}`")
        req = urllib.request.Request(f"{base}/{_FEE_ESTIMATES_PATH}",
                                     data=json.dumps(body).encode("utf-8"), method="POST")
        req.add_header("x-amz-access-token", token)
        req.add_header("Content-Type", "application/json")
        req.add_header("Accept", "application/json")
        req.add_header("User-Agent", _UA)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as response:
                observe_rate(getattr(response, "headers", None))
                got = json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            observe_rate(exc.headers)
            try:
                errors = json.loads(exc.read().decode("utf-8")).get("errors") or []
                reason = "; ".join(str(e.get("message") or e.get("code") or "Amazon gave no reason") for e in errors)
            except (ValueError, AttributeError, TypeError):
                reason = "Amazon gave no reason"
            if exc.code == 429:
                raise AmazonThrottled(
                    "getMyFeesEstimates throttled (429). Keep batches of 20 at 0.5 requests per second with a burst of one.",
                    retry_after=(exc.headers or {}).get("Retry-After")) from None
            raise AmazonReportError(f"getMyFeesEstimates refused ({exc.code}). Amazon reason",
                                    reason or "Amazon gave no reason", exc.code) from None
        except (OSError, ValueError) as exc:
            raise AmazonError(f"getMyFeesEstimates could not read Amazon's response: {type(exc).__name__}") from None
        if not isinstance(got, list) or any(not isinstance(row, dict) for row in got):
            raise AmazonError("getMyFeesEstimates returned no valid estimate list")
        return got

    with _pacing_scope(scope):
        _pace_entity("getMyFeesEstimates", _fee_estimates_interval, sleep=sleep, now=now)
    return _retry(attempt, _FEE_ESTIMATES_PATH, sleep=sleep, now=now, operation=operation, scope=scope,
                  exhausted_fix="keep batches of 20 and reduce the fee estimate request rate")


def fee_estimates(fields, estimates, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
    """Batch every requested SKU and price, refusing incomplete or mismatched estimate responses."""
    marketplace = fields.get("marketplace_id") or US_MARKETPLACE_ID
    requests = [fee_estimate_request(estimate, marketplace) for estimate in estimates]
    identifiers = [item["FeesEstimateRequest"]["Identifier"] for item in requests]
    if len(set(identifiers)) != len(identifiers):
        raise AmazonError("Fee estimates contain duplicate SKU and price bases; request each basis once")
    if not requests:
        return []
    token, issued = access_token(fields, timeout=timeout), now()
    records = []
    for offset in range(0, len(requests), FEE_ESTIMATES_BATCH_SIZE):
        if now() - issued >= 3000:
            token, issued = access_token(fields, timeout=timeout), now()
        batch = requests[offset:offset + FEE_ESTIMATES_BATCH_SIZE]
        returned = _fee_estimates_batch(token, batch, region=fields.get("region") or DEFAULT_REGION,
                                       timeout=timeout, sandbox=is_sandbox(fields), sleep=sleep, now=now)
        expected = {item["FeesEstimateRequest"]["Identifier"]: item for item in batch}
        seen = set()
        for record in returned:
            if record.get("Status") != "Success":
                error = record.get("Error") or {}
                raise AmazonReportError("getMyFeesEstimates refused an estimate. Amazon reason",
                                        str(error.get("Message") or error.get("Code") or record.get("Status")),
                                        error.get("Code") or record.get("Status"))
            echo = record.get("FeesEstimateIdentifier") or {}
            identifier = echo.get("SellerInputIdentifier")
            if identifier not in expected or identifier in seen:
                raise AmazonError("getMyFeesEstimates returned a duplicate or unrequested estimate identity")
            seen.add(identifier)
            sent = expected[identifier]
            request = sent["FeesEstimateRequest"]
            if (echo.get("IdType") != sent["IdType"] or echo.get("IdValue") != sent["IdValue"]
                    or any(echo.get(key) != request.get(key) for key in
                           ("MarketplaceId", "IsAmazonFulfilled", "PriceToEstimateFees", "OptionalFulfillmentProgram"))):
                raise AmazonError("getMyFeesEstimates returned a different IdType, SKU, ASIN or price basis; no partial snapshot was stored")
            estimate = record.get("FeesEstimate") or {}
            if (not isinstance(estimate.get("FeeDetailList"), list)
                    or any(not isinstance(line, dict) for line in estimate["FeeDetailList"])
                    or not isinstance(estimate.get("TotalFeesEstimate"), dict)):
                raise AmazonError("getMyFeesEstimates omitted its fee lines or total; no partial snapshot was stored")
        if seen != set(expected):
            raise AmazonError("getMyFeesEstimates returned an incomplete estimate batch; no partial snapshot was stored")
        records.extend(returned)
    return records


def awd_inventory(fields, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
    """Read every AWD inventory page, including through empty pages. -> inventory summaries."""
    f = fields or {}
    region = str(f.get("region") or DEFAULT_REGION)
    sandbox = is_sandbox(f)
    token = access_token(f, timeout=timeout)
    token_issued = now()
    next_token = None
    seen_tokens = set()
    rows = []
    while True:
        _pace_entity("awd_inventory", AWD_INVENTORY_INTERVAL, sleep=sleep, now=now)
        if now() - token_issued >= 3000:
            token = access_token(f, timeout=timeout)
            token_issued = now()
        try:
            got = _request(
                _AWD_INVENTORY_PATH, token, region=region, timeout=timeout, sandbox=sandbox,
                throttle_fix="resume the same listInventory pagination later without dropping pages",
                details="SHOW", maxResults=AWD_INVENTORY_PAGE_SIZE, nextToken=next_token)
        except AmazonError as e:
            if "answered 403" in str(e):
                raise AmazonError(
                    f"{_AWD_INVENTORY_PATH} was refused (403). The application needs the Amazon "
                    "Warehousing and Distribution role") from None
            raise
        page = got.get("inventory")
        if not isinstance(page, list):
            raise AmazonError("listInventory returned no inventory list")
        rows.extend(page)
        following = str(got.get("nextToken") or "").strip()
        if not following:
            break
        if following in seen_tokens:
            raise AmazonError(
                "listInventory repeated a nextToken; refusing an infinite or duplicate page loop")
        seen_tokens.add(following)
        next_token = following
    return rows


#: ⛔⛔ THE REPORT-JOB NON-GET PATH, AND IT IS A CONSTANT RATHER THAN A PARAMETER.
#:
#: The Reports API bulk path cannot be reached with GET alone: asking Amazon to BUILD a report is
#: `POST /reports/2021-06-30/reports`. Standing rule 1 forbids a silent cap on a connector's
#: records and names the Reports API as the fix, so refusing this one call would mean either no
#: bulk path at all or a quiet page loop over entity endpoints. Both are worse.
#:
#: ⭐ **THE EXCEPTION IS SHAPED LIKE `modules/collections_send.py`'s, deliberately** — that is the
#: codebase's single standing precedent for a connector that writes, and its discipline is: ONE
#: named operation, whitelisted in the data layer where no route, payload or UI can widen it.
#: Here the path is a module constant and `_create_report` takes NO path argument, so there is no
#: caller-supplied value to smuggle another operation through.
#:
#: ⚠ AND THE BLAST RADIUS IS WORTH STATING PLAINLY, because "read-only" is a promise to the owner
#: and this is one of two places the HTTP verb bends: a report request creates a JOB, not seller
#: data. The other is Amazon's POST-wrapped batch of fixed competitive-summary GETs. Neither can
#: alter a listing, a price, an order or an inventory level, and neither can send a buyer anything.
#: The two roles that could do those things were REFUSED at registration (R7).
_REPORTS_CREATE_PATH = "reports/2021-06-30/reports"


def _create_report(token, report_type, marketplace_ids, region=DEFAULT_REGION,
                   start=None, end=None, options=None, timeout=_TIMEOUT, sandbox=False):
    """Ask Amazon to build one report. -> its `reportId`.

    ⛔ NO `path` PARAMETER, ON PURPOSE. See `_REPORTS_CREATE_PATH` above: the whole safety argument
    is that this function can reach exactly one operation and a caller cannot redirect it.
    """
    require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
    operation, scope = "createReport", _scope_for(token, region, sandbox)
    if any(s.get("snapshot") and not s.get("dated_snapshot") and s.get("report") == report_type
           for s in REPORT_TYPES.values()):
        if start is not None or end is not None:
            raise AmazonError("Snapshot reports cannot take a data window")

    def attempt():
        """One raw attempt at the declared report-creation POST."""
        base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
            str(region or DEFAULT_REGION).lower())
        if not base:
            raise AmazonError(f"unknown region `{region}`")
        body = {"reportType": str(report_type),
                "marketplaceIds": list(marketplace_ids or [US_MARKETPLACE_ID])}
        if start:
            body["dataStartTime"] = str(start)
        if end:
            body["dataEndTime"] = str(end)
        if options:
            body["reportOptions"] = dict(options)
        url = f"{base}/{_REPORTS_CREATE_PATH}"
        req = urllib.request.Request(url, data=json.dumps(body).encode("utf-8"), method="POST")
        req.add_header("x-amz-access-token", token)
        req.add_header("Content-Type", "application/json")
        req.add_header("Accept", "application/json")
        req.add_header("User-Agent", _UA)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                _observe_rate(operation, scope, getattr(r, "headers", None))
                got = json.loads(r.read().decode("utf-8") or "{}")
        except urllib.error.HTTPError as e:
            _observe_rate(operation, scope, e.headers)
            detail = ""
            try:
                detail = (e.read() or b"").decode("utf-8", errors="replace")
                errs = json.loads(detail or "{}").get("errors") or []
                detail = " ".join(str(err.get(part) or "") for err in errs
                                  for part in ("message", "details") if err.get(part)) or detail
            except Exception:                                              # noqa: BLE001
                pass
            if e.code == 429:
                raise AmazonThrottled(
                    f"{_safe(url)} was throttled (429) creating a {report_type} report. Report "
                    "creation is limited to about one call every 60 seconds with a burst of 15; the "
                    "fix is fewer, wider report windows, not more frequent requests",
                    retry_after=(e.headers or {}).get("Retry-After")) from None
            if e.code == 403:
                raise AmazonError(
                    f"{_safe(url)} refused a {report_type} report (403). That is a ROLE answer: this "
                    "report needs a role the application was not granted") from None
            if e.code == 400 and report_type == REPORT_TYPES["search_query_performance"]["report"]:
                raise AmazonReportError("Amazon refused Search Query Performance (400)",
                                        detail, 400) from None
            raise AmazonError(f"{_safe(url)} answered {e.code}"
                              + (f": {detail[:200]}" if detail else "")) from None
        except Exception as e:                                             # noqa: BLE001
            raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
        rid = str(got.get("reportId") or "")
        if not rid:
            raise AmazonError(f"Amazon accepted the {report_type} request but returned no reportId")
        return rid

    base = (SANDBOX_ENDPOINTS if sandbox else ENDPOINTS).get(
        str(region or DEFAULT_REGION).lower(), "")
    # ⭐ Pace once per new report. Retrying that same report pays only the shared backoff.
    with _pacing_scope(scope):
        _report_pacer["waited"].set(_pace_report_create())
    return _retry(
        attempt, f"{base}/{_REPORTS_CREATE_PATH}",
        operation=operation, scope=scope,
        exhausted_fix="create fewer reports with wider report windows")


#: Terminal processing states. `DONE` is the only one that yields a document.
_REPORT_DONE = "DONE"
_REPORT_DEAD = {"CANCELLED", "FATAL"}


def report_document(fields, report_type, start=None, end=None, options=None,
                    poll_seconds=15, max_wait=900, log=None, timeout=_TIMEOUT, report_id=None, once=False):
    """The whole bulk path for one report: request, poll, resolve the document. -> `(text, meta)`.

    ⭐ THIS IS STANDING RULE 1'S "RECOMMENDED FIX", IMPLEMENTED RATHER THAN CITED. Amazon's own
    guidance is that entity endpoints are for deltas and lookups and the Reports API is for a set:
    one report document carries every row for its window, so a backfill costs one rate-limited
    request instead of one per page.

    ⚠ THE WAIT IS BOUNDED AND THE TIMEOUT IS REPORTED, NOT SWALLOWED. A report that is still
    `IN_PROGRESS` after `max_wait` raises with the reportId in the message, so the next call can
    resume from it rather than paying for the whole build again.
    """
    # Refuse an undeclared report even before its LWA exchange; _create_report guards its own door.
    require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
    held = _prefetched(fields, report_type, start, end, options)
    if held is not None:
        return held
    if not report_id:
        _draw_report_token(fields)
    say = log or (lambda *_a, **_k: None)
    token = access_token(fields, timeout=timeout)
    region = str((fields or {}).get("region") or DEFAULT_REGION)
    mkts = [str((fields or {}).get("marketplace_id") or US_MARKETPLACE_ID)]
    sbx = is_sandbox(fields)
    pace_context = _report_pacer["waited"].set(0.0)
    try:
        rid = report_id or _create_report(token, report_type, mkts, region=region, start=start, end=end,
                             options=options, timeout=timeout, sandbox=sbx)
    finally:
        paced = _report_pacer["waited"].get()
        _report_pacer["waited"].reset(pace_context)
        if paced:
            say(f"    {report_type}: waited {paced:.2f}s to stagger report creation")
    say(f"    {report_type}: reportId {rid}")

    def read(path):
        try:
            return _request(path, token, region=region, timeout=timeout, sandbox=sbx)
        except AmazonError as exc:
            exc.report_id = rid
            raise

    waited, state, doc_id = 0, "", ""
    while waited <= max_wait:
        got = read(f"reports/2021-06-30/reports/{rid}")
        state = str(got.get("processingStatus") or "")
        if state == _REPORT_DONE:
            doc_id = str(got.get("reportDocumentId") or "")
            break
        if state in _REPORT_DEAD:
            if state == "FATAL" and report_type == REPORT_TYPES["search_query_performance"]["report"]:
                error_id = got.get("reportDocumentId") or got.get("errorDocumentId")
                reason = str(got.get("errorMessage") or "No error document was supplied by Amazon")
                if error_id:
                    meta = read(f"reports/2021-06-30/documents/{error_id}")
                    if meta.get("url"):
                        reason = _download_document(meta["url"], str(meta.get("compressionAlgorithm") or ""))
                error = AmazonReportError(f"Amazon ended Search Query Performance as FATAL (reportId {rid})",
                                          reason, state)
                error.report_id = rid
                raise error
            if state == "CANCELLED" and not (got.get("errorMessage") or got.get("errorDocumentId")
                                              or got.get("reportDocumentId")):
                # S66-T42 (lead, observed live 2026-09-25): Amazon documents CANCELLED as also
                # meaning "the report had no data to return". Raising turned an empty period into
                # a role-shaped refusal on screen and left the window to retry forever. An empty
                # document lets the window complete and the connector detail name the empty period.
                say(f"    {report_type}: Amazon cancelled report {rid}; no data for the requested period")
                return "", {"reportId": rid, "reportDocumentId": None, "processingStatus": state,
                            "cancelled": True,
                            "dataStartTime": got.get("dataStartTime"),
                            "dataEndTime": got.get("dataEndTime"),
                            "createdTime": got.get("createdTime"), "compression": None,
                            "marketplaceIds": got.get("marketplaceIds")}
            # Every FATAL report now carries Amazon's OWN reason when it supplied an error document,
            # so the connector detail names why, never only a generic role hint.
            detail = ""
            error_id = got.get("reportDocumentId") or got.get("errorDocumentId")
            if error_id:
                try:
                    meta = read(f"reports/2021-06-30/documents/{error_id}")
                    if meta.get("url"):
                        detail = _download_document(meta["url"], str(meta.get("compressionAlgorithm") or ""))
                except AmazonError:
                    detail = ""
            detail = " ".join(str(detail).replace("\u2014", "; ").replace("\u2013", " to ").split())[:240]
            reason = detail or str(got.get("errorMessage") or "No error document was supplied by Amazon")
            error = AmazonReportError(f"Amazon ended the {report_type} report as {state} (reportId {rid})",
                                      reason, state)
            error.report_id = rid
            error.has_error_document = bool(error_id or got.get("errorMessage"))
            raise error
        if once:
            break
        time.sleep(poll_seconds)
        waited += poll_seconds
        # ⛔ The token is ~1 hour and a long report can outlive it. Re-mint rather than 403.
        if waited and waited % 1800 == 0:
            token = access_token(fields, timeout=timeout)
    if not doc_id:
        raise AmazonReportPending(rid, state)

    meta = read(f"reports/2021-06-30/documents/{doc_id}")
    url = str(meta.get("url") or "")
    if not url:
        error = AmazonError(f"the {report_type} report document carried no download URL")
        error.report_id = rid
        raise error
    try:
        text = _download_document(url, str(meta.get("compressionAlgorithm") or ""), spool=True)
    except AmazonError as exc:
        exc.report_id = rid
        raise
    say(f"    {report_type}: {len(text):,} chars")
    return text, {"reportId": rid, "reportDocumentId": doc_id, "processingStatus": state,
                  "dataStartTime": got.get("dataStartTime"),
                  "dataEndTime": got.get("dataEndTime"), "createdTime": got.get("createdTime"),
                  "compression": meta.get("compressionAlgorithm"), "marketplaceIds": got.get("marketplaceIds")}


def create_report_id(fields, report_type, start=None, end=None, options=None, timeout=_TIMEOUT):
    """S82-T14: request one report and return its reportId. `poll_report` reads it later."""
    require_operation("POST", _REPORTS_CREATE_PATH, report_type=str(report_type))
    token = access_token(fields, timeout=timeout)
    return _create_report(token, report_type, [str((fields or {}).get("marketplace_id") or US_MARKETPLACE_ID)],
                          region=str((fields or {}).get("region") or DEFAULT_REGION), start=start, end=end,
                          options=options, timeout=timeout, sandbox=is_sandbox(fields))


def poll_report(fields, report_type, report_id, *, log=None, timeout=_TIMEOUT):
    """S82-T14: one status read. None while Amazon builds the report, else `(text, meta)` as `report_document`."""
    try:
        return report_document(fields, report_type, report_id=str(report_id), once=True, log=log,
                               timeout=timeout)
    except AmazonReportPending:
        return None


SETTLEMENT_REPORT_PAGE_CAP = 1000


def settlement_reports(fields, *, since=None, timeout=_TIMEOUT, log=None):
    """List settlements Amazon has already created, oldest first.

    Amazon issues these on its own fortnightly cycle, so this lists rather than requests.
    Only safe, named metadata leaves this function; vendor extras and tokens stay here.
    """
    require_operation("GET", _REPORTS_CREATE_PATH,
                      report_type=REPORT_TYPES["settlements"]["report_discover"])
    import re

    rtype = REPORT_TYPES["settlements"]["report_discover"]
    token = access_token(fields, timeout=timeout)
    region = str((fields or {}).get("region") or DEFAULT_REGION)
    params = {"reportTypes": rtype, "processingStatuses": "DONE", "pageSize": 100}
    if since is not None:
        params["createdSince"] = str(since)
    reports = []
    for _page in range(SETTLEMENT_REPORT_PAGE_CAP):
        # _request owns the same _retry policy as the existing report/document reads.
        got = _request(_REPORTS_CREATE_PATH, token, region=region, timeout=timeout,
                       sandbox=is_sandbox(fields), **params)
        for raw in got.get("reports") or ():
            row = {key: str(raw[key]) if raw.get(key) is not None else "" for key in (
                "reportId", "reportDocumentId", "reportType", "dataStartTime",
                "dataEndTime", "createdTime")}
            # Match the API status door without importing upward into the API layer.
            # Refuse unsafe values with a fixed sentence that cannot echo the credential.
            if any(len(value) > 512 or "Atzr|" in value
                   or re.search(r"\bbearer\s+\S+", value, flags=re.IGNORECASE)
                   or any(ch in value for ch in ("\u2014", "\u2013"))
                   for value in row.values()):
                raise AmazonError("Settlement discovery returned unsafe metadata; no status was emitted.")
            if row["reportType"] != rtype or not row["reportDocumentId"]:
                raise AmazonError("Settlement discovery returned an unexpected type or no document ID.")
            reports.append(row)
        next_token = got.get("nextToken")
        if not next_token:
            if log:
                log(f"getReports discovered {len(reports)} settlement reports")
            return sorted(reports, key=lambda row: (row["createdTime"], row["reportId"]))
        # Amazon continuation tokens replace the original filters, which the token carries.
        params = {"nextToken": str(next_token)}
    raise AmazonError(
        f"Settlement discovery hit the {SETTLEMENT_REPORT_PAGE_CAP}-page cap because Amazon kept "
        "returning nextToken; retry with a narrower createdSince window.")


def settlement_document(fields, document_id, *, timeout=_TIMEOUT):
    """One settlement document's text through getReportDocument and the presigned URL."""
    require_operation("GET", f"reports/2021-06-30/documents/{document_id}")
    token = access_token(fields, timeout=timeout)
    region = str((fields or {}).get("region") or DEFAULT_REGION)
    meta = _request(f"reports/2021-06-30/documents/{document_id}", token, region=region,
                    timeout=timeout, sandbox=is_sandbox(fields))
    url = str(meta.get("url") or "")
    if not url:
        raise AmazonError("The settlement document carried no download URL.")
    return _download_document(url, str(meta.get("compressionAlgorithm") or ""))


def _workbook_as_tsv(raw):
    """An Excel workbook document, as the tab-separated text every flat-file parser reads.

    S66-T42 (lead, observed live 2026-09-25): Amazon delivers some reports (FEE_DISCOUNTS_REPORT,
    GET_REMOTE_FULFILLMENT_ELIGIBILITY) as an .xlsx workbook, a ZIP container. Decoded as text it
    became garbage column names carrying NUL bytes, and Postgres refused the whole Amazon write.
    The first sheet is the report; its first row is the header, like a flat file. Tabs and line
    breaks inside a cell become spaces so the TSV shape holds.
    """
    import io
    try:
        import openpyxl
        book = openpyxl.load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
    except Exception as e:                                             # noqa: BLE001
        raise AmazonError(f"the report document is a workbook that did not open: {type(e).__name__}") from None
    sheet = book.worksheets[0] if book.worksheets else None
    lines = []
    for values in (sheet.iter_rows(values_only=True) if sheet is not None else ()):
        cells = ["" if v is None else " ".join(str(v).replace("\x00", "").split()) for v in values]
        if any(cells):
            lines.append("\t".join(cells))
    book.close()
    return "\n".join(lines)


class ReportDocument:
    """One downloaded report document spooled to a temporary file, read back as text in pieces.

    ⛔ A report has no row cap (standing rule 1), so its text never sits in memory whole: the Brand
    Analytics month held the body, its decompressed copy and its decoded text at once (D-7081).
    The file is removed when the object is closed or collected.
    """

    def __init__(self, path, encoding, errors, chars, size, compressed):
        self.path, self.encoding, self.errors = path, encoding, errors
        self.chars, self.size, self.compressed = chars, size, compressed

    def open_text(self):
        """The decoded text as a stream; `newline=""` keeps line ends exactly as `bytes.decode` did."""
        return open(self.path, "r", encoding=self.encoding, errors=self.errors, newline="")

    def read_text(self):
        """The whole text, for a consumer whose document is small."""
        with self.open_text() as handle:
            return handle.read()

    def __len__(self):
        return self.chars

    def close(self):
        path, self.path = getattr(self, "path", None), None
        if path:
            try:
                os.unlink(path)
            except Exception:                                          # noqa: BLE001
                pass

    def __del__(self):
        self.close()


_SPOOL_CHUNK = 1 << 20


def _spool_file(prefix):
    handle, path = tempfile.mkstemp(prefix=prefix, suffix=".part")
    os.close(handle)
    return path


def _unlink(path):
    try:
        os.unlink(path)
    except OSError:
        pass


def _decoded_chars(path, encoding, errors="strict"):
    """Characters in the file under one encoding; raises UnicodeDecodeError like `bytes.decode`."""
    chars = 0
    with open(path, "r", encoding=encoding, errors=errors, newline="") as handle:
        while True:
            piece = handle.read(_SPOOL_CHUNK)
            if not piece:
                return chars
            chars += len(piece)


def _spooled_document(body, compression):
    """The spooled body as a `ReportDocument`: gunzip and decode stream through disk, never memory."""
    compressed = os.path.getsize(body)
    with open(body, "rb") as handle:
        head = handle.read(4)
    if not compression and head[:2] == b"\x1f\x8b":
        compression = "GZIP"
    if str(compression).upper() == "GZIP":
        plain = _spool_file("amazon-document-")
        try:
            with gzip.open(body, "rb") as source, open(plain, "wb") as out:
                shutil.copyfileobj(source, out, _SPOOL_CHUNK)
        except Exception as e:                                         # noqa: BLE001
            _unlink(plain)
            raise AmazonError(f"the report document did not decompress: {type(e).__name__}") from None
        finally:
            _unlink(body)
        body = plain
        with open(body, "rb") as handle:
            head = handle.read(4)
    if head[:4] == b"PK\x03\x04":
        try:
            with open(body, "rb") as handle:
                return _workbook_as_tsv(handle.read())
        finally:
            _unlink(body)
    size = os.path.getsize(body)
    for enc in ("utf-8", "cp1252"):
        try:
            return ReportDocument(body, enc, "strict", _decoded_chars(body, enc), size, compressed)
        except UnicodeDecodeError:
            continue
    return ReportDocument(body, "utf-8", "replace", _decoded_chars(body, "utf-8", "replace"), size, compressed)


def _download_document(url, compression="", timeout=120, *, spool=False):
    """Fetch one presigned report document and decode it. -> text, or a `ReportDocument` when spooled.

    ⚠ THE URL IS PRESIGNED AND SHORT-LIVED, AND IT IS NEVER LOGGED. `_safe` strips the query
    string, which for an S3 presigned URL is the entire credential.
    ⚠ Amazon flat files are frequently `cp1252`, not UTF-8, and a hard decode drops whole rows on
    one smart quote. Decoded with replacement, and that is a deliberate lossy choice on a
    presentation field rather than on a number.
    """
    # This is the presigned URL returned by getReportDocument, not an SP-API operation. Do not
    # apply OPERATIONS here: its host and signature belong to Amazon's document download service.
    req = urllib.request.Request(url, method="GET")
    req.add_header("User-Agent", _UA)
    body = _spool_file("amazon-document-") if spool else None
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            if body:
                with open(body, "wb") as out:
                    shutil.copyfileobj(r, out, _SPOOL_CHUNK)
            else:
                raw = r.read()
    except Exception as e:                                             # noqa: BLE001
        if body:
            _unlink(body)
        raise AmazonError(f"{_safe(url)} unreachable: {type(e).__name__}") from None
    if body:
        return _spooled_document(body, compression)
    # S66-T40 (lead, measured live 2026-09-25): Data Kiosk's getDocument answers only
    # `documentId` and `documentUrl`, yet the JSONL it points at IS gzip. With no declared
    # algorithm the bytes were decoded as text and every economics window failed to parse. The
    # gzip magic number is unambiguous (no text report starts with 0x1f 0x8b), so it decides.
    if not compression and raw[:2] == b"\x1f\x8b":
        compression = "GZIP"
    if str(compression).upper() == "GZIP":
        import gzip
        try:
            raw = gzip.decompress(raw)
        except Exception as e:                                         # noqa: BLE001
            raise AmazonError(f"the report document did not decompress: {type(e).__name__}") from None
    if raw[:4] == b"PK\x03\x04":
        return _workbook_as_tsv(raw)
    for enc in ("utf-8", "cp1252"):
        try:
            return raw.decode(enc)
        except UnicodeDecodeError:
            continue
    return raw.decode("utf-8", errors="replace")


def marketplace_participations(fields, timeout=_TIMEOUT):
    """The cheapest honest liveness call: which marketplaces this seller participates in.

    Chosen over an orders or inventory read on purpose. It needs no role beyond the basic grant, it
    returns no PII, it is not a bulk endpoint so it cannot burn a report quota, and a credential
    that authenticates but participates in NO marketplace is a real and reportable state rather
    than an empty result.
    """
    token = access_token(fields, timeout=timeout)
    region = str((fields or {}).get("region") or DEFAULT_REGION)
    got = _request("sellers/v1/marketplaceParticipations", token, region=region, timeout=timeout,
                   sandbox=is_sandbox(fields))
    return got.get("payload") or []


def _sales_rank(item, marketplace):
    """`{"rank", "group"}` from one catalog item: the display group rank, else the best classification rank."""
    for entry in (item or {}).get("salesRanks") or ():
        if not isinstance(entry, dict) or entry.get("marketplaceId") not in (None, marketplace):
            continue
        display = [r for r in entry.get("displayGroupRanks") or () if isinstance((r or {}).get("rank"), int)]
        if display:
            return {"rank": display[0]["rank"], "group": display[0].get("title")}
        ranks = [r for r in entry.get("classificationRanks") or () if isinstance((r or {}).get("rank"), int)]
        if ranks:
            best = min(ranks, key=lambda r: r["rank"])
            return {"rank": best["rank"], "group": best.get("title")}
    return {"rank": None, "group": None}


def catalog_sales_ranks(fields, asins, timeout=_TIMEOUT, *, sleep=time.sleep, now=time.monotonic):
    """Read sales ranks for any ASINs through `searchCatalogItems`, 20 per call. -> {asin: {"rank", "group"}}.

    An ASIN Amazon does not return is absent from the result; the caller names it.
    """
    unique = sorted({str(a or "").strip() for a in asins or () if str(a or "").strip()})
    if not unique:
        return {}
    if any(not re.fullmatch(r"[A-Z0-9]{10}", a) for a in unique):
        raise AmazonError("A sales rank read needs 10 character ASINs")
    f = fields or {}
    marketplace = str(f.get("marketplace_id") or US_MARKETPLACE_ID)
    region = str(f.get("region") or DEFAULT_REGION)
    path = OPERATIONS["searchCatalogItems"]["path"]
    token, issued = access_token(f, timeout=timeout), now()
    out = {}
    for offset in range(0, len(unique), 20):
        _pace_entity("searchCatalogItems", ENTITY_INTERVALS["searchCatalogItems"], sleep=sleep, now=now)
        if now() - issued >= 3000:
            token, issued = access_token(f, timeout=timeout), now()
        batch = unique[offset:offset + 20]
        got = _request(path, token, region=region, sandbox=is_sandbox(f), timeout=timeout,
                       marketplaceIds=marketplace, identifiersType="ASIN", identifiers=",".join(batch),
                       includedData="summaries,salesRanks", pageSize=20,
                       throttle_fix="read sales ranks again after the next weekly pull")
        items = got.get("items") if isinstance(got, dict) else None
        if not isinstance(items, list):
            raise AmazonError("searchCatalogItems returned no item list; retry after Amazon restores its response")
        for item in items:
            asin = str((item or {}).get("asin") or "")
            if asin in batch:
                out[asin] = _sales_rank(item, marketplace)
    return out