File size: 201,555 Bytes
cdb06e5
cf09724
 
9e15897
cf09724
 
 
 
 
b2aa446
 
cdb06e5
a5981db
 
 
b2aa446
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
cf09724
 
cdb06e5
3e19b1e
cdb06e5
b2aa446
 
cdb06e5
cf09724
58155d7
 
 
cdb06e5
82f0f29
cdb06e5
82f0f29
cdb06e5
85f794d
82f0f29
cdb06e5
 
b2aa446
 
 
 
 
 
cf09724
9e15897
cf09724
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
cf09724
 
 
cdb06e5
 
 
 
 
cf09724
 
3a021ea
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
cf09724
 
 
 
3e19b1e
b2aa446
3e19b1e
 
 
 
b2aa446
cdb06e5
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
 
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
85f794d
9e15897
cf09724
 
 
 
 
b2aa446
cf09724
9e15897
 
 
 
 
 
 
 
 
 
 
 
cf09724
cdb06e5
22987e4
 
85f794d
 
 
cdb06e5
b2aa446
 
 
 
 
82f0f29
3e19b1e
85f794d
b2aa446
cf09724
 
b2aa446
cf09724
 
 
 
 
 
b2aa446
cf09724
b2aa446
 
 
 
 
 
 
cf09724
b2aa446
 
cf09724
 
 
 
b2aa446
 
cf09724
 
 
 
 
b2aa446
 
 
cf09724
b2aa446
 
 
 
cf09724
 
 
 
 
cdb06e5
b2aa446
cdb06e5
 
cf09724
cdb06e5
b2aa446
 
cdb06e5
3a021ea
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
b2aa446
85f794d
 
 
 
 
 
 
 
b2aa446
 
 
85f794d
 
b2aa446
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
cdb06e5
 
 
 
85f794d
cdb06e5
 
 
 
 
 
 
 
22987e4
 
cdb06e5
82f0f29
3e19b1e
 
 
 
85f794d
3e19b1e
cdb06e5
 
 
 
 
 
 
 
99cf221
 
cdb06e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
3e19b1e
cdb06e5
 
b2aa446
cdb06e5
b2aa446
cdb06e5
 
3e19b1e
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
cf09724
cdb06e5
cf09724
 
9e15897
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5981db
 
 
 
 
 
cf09724
 
 
a5981db
cf09724
 
 
 
 
 
 
 
 
a5981db
 
cf09724
 
 
 
a5981db
 
cf09724
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
a5981db
 
3a021ea
a5981db
 
 
3a021ea
a5981db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
a5981db
 
 
 
85f794d
a5981db
 
 
85f794d
 
 
 
 
 
 
 
 
a5981db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5981db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
a5981db
 
 
 
 
 
 
 
 
 
 
 
85f794d
3a021ea
a5981db
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a021ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
cf09724
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4810fa
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
 
 
 
 
 
 
b2aa446
 
 
 
9e15897
 
 
 
 
 
b2aa446
 
c4810fa
9e15897
b2aa446
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
cf09724
 
 
 
 
 
 
 
 
 
 
 
3e19b1e
cf09724
 
 
 
 
 
 
 
 
 
 
3e19b1e
 
 
 
 
 
 
 
 
 
 
cf09724
9e15897
cf09724
 
 
 
 
 
 
58155d7
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
 
cf09724
cdb06e5
 
82f0f29
cdb06e5
 
 
 
 
 
 
 
cf09724
cdb06e5
cf09724
 
 
 
cdb06e5
cf09724
 
 
 
 
58155d7
 
 
 
 
82f0f29
3e19b1e
82f0f29
3e19b1e
 
58155d7
3e19b1e
 
 
 
 
82f0f29
 
cf09724
 
 
 
 
 
 
99cf221
 
 
 
 
 
 
 
 
 
3e19b1e
b2aa446
3e19b1e
99cf221
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
22987e4
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58155d7
 
 
 
 
 
 
 
 
b2aa446
 
22987e4
 
cdb06e5
b2aa446
cdb06e5
 
b2aa446
cdb06e5
11c14e3
58155d7
 
b2aa446
cdb06e5
b2aa446
cdb06e5
 
b2aa446
 
82f0f29
 
 
99cf221
cdb06e5
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82f0f29
 
b2aa446
 
 
 
cf09724
 
a0472aa
 
b2aa446
a0472aa
 
cdb06e5
cf09724
cdb06e5
cf09724
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
b2aa446
cdb06e5
 
b2aa446
 
 
 
 
 
 
 
3e19b1e
 
 
b2aa446
 
 
 
 
 
 
 
cf09724
 
b2aa446
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
cf09724
cdb06e5
cf09724
 
cdb06e5
cf09724
 
 
 
 
 
 
 
 
cdb06e5
cf09724
 
cdb06e5
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
22987e4
 
b2aa446
 
 
 
 
 
 
 
 
 
22987e4
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
22987e4
cf09724
 
 
22987e4
85f794d
b2aa446
85f794d
 
 
 
 
 
b2aa446
 
22987e4
 
 
 
 
 
 
 
 
 
 
 
 
 
58155d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
9e15897
b2aa446
 
 
cf09724
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
cf09724
 
 
 
 
 
9e15897
cf09724
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
cf09724
b2aa446
 
cf09724
 
 
 
 
 
b2aa446
 
cf09724
 
b2aa446
cf09724
 
 
 
 
 
 
 
a5981db
 
cf09724
 
 
 
 
 
3a021ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
cf09724
3a021ea
b2aa446
cf09724
b2aa446
 
 
3a021ea
b2aa446
 
 
 
3a021ea
b2aa446
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
cdb06e5
 
 
 
85f794d
cdb06e5
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
cdb06e5
 
 
 
 
 
 
 
b2aa446
 
cdb06e5
b2aa446
3e19b1e
cdb06e5
 
 
22987e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
22987e4
3e19b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99cf221
 
cdb06e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
cdb06e5
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
b2aa446
 
 
 
 
cdb06e5
 
b2aa446
 
cdb06e5
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
85f794d
 
 
 
 
 
cdb06e5
b2aa446
 
 
cdb06e5
b2aa446
 
 
 
 
 
 
 
 
 
cdb06e5
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cdb06e5
 
9e15897
cf09724
 
 
3a021ea
 
 
cf09724
 
 
 
 
3a021ea
 
 
 
 
cf09724
 
b2aa446
3a021ea
 
b2aa446
 
3a021ea
b2aa446
cf09724
 
 
 
 
cdb06e5
 
58155d7
9e15897
 
 
 
 
 
 
 
 
 
 
 
b2aa446
9e15897
b2aa446
9e15897
 
 
 
 
b2aa446
 
 
 
 
 
 
 
cdb06e5
 
 
 
 
 
3a021ea
cdb06e5
 
 
 
 
b2aa446
 
22987e4
 
 
cf09724
 
b2aa446
 
 
c4810fa
 
cdb06e5
 
22987e4
 
 
 
 
3a021ea
cdb06e5
b2aa446
 
cdb06e5
 
 
 
b2aa446
 
cdb06e5
85f794d
 
 
cdb06e5
 
 
 
 
 
3e19b1e
85f794d
cf09724
 
 
 
 
b2aa446
3a021ea
b2aa446
3a021ea
 
b2aa446
 
 
 
 
cf09724
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a021ea
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
b2aa446
 
 
 
 
 
 
85f794d
 
 
b2aa446
 
 
 
 
3a021ea
 
b2aa446
 
 
 
 
85f794d
 
 
 
 
 
b2aa446
 
 
 
 
 
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
a5981db
3e19b1e
a5981db
 
cf09724
 
 
 
 
 
85f794d
cf09724
85f794d
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
3e19b1e
a5981db
85f794d
3e19b1e
cf09724
 
 
 
 
 
 
a5981db
 
 
 
 
 
 
 
b2aa446
 
a5981db
b2aa446
a5981db
 
 
 
b2aa446
 
 
a5981db
 
 
3a021ea
a5981db
b2aa446
a5981db
cf09724
 
a5981db
 
cf09724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15897
b2aa446
 
85f794d
 
3e19b1e
 
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
"""Command Center: one row per Amazon SKU with Odoo cost, profit, ads, stock, returns, health and score.

Net proceeds = net sales minus fees minus sponsored ads, from the `amzn_economics` mirror.
COGS follows incoming receipt valuations and posted landed costs through FIFO.
The module owns its table (`ut_amazon_sku_profit`). It is not a connector table, so people
edit the owned columns (Odoo product, units per SKU, owner, status, due date). A refresh
rewrites only the computed columns, keyed by SKU, so owned cells belong to the SKU and
survive every period switch.

`ut_amazon_asin_profit` and `ut_amazon_parent_profit` roll the SKU rows up on every refresh.
Projects retain their own verified period totals and Impact in the tenant projects store.

`validate()` ties each net proceeds component to independent Amazon amounts within 2% over settled
days, with order charges on purchase dates and monthly storage in its service month.
A refresh runs it for the last complete month and writes no figures when it
fails. A passing refresh stores the verified range and the day the rest is due to settle.

Owned items (R10, R31): a refresh opens one item on a Losing or Thin SKU with no status, for the
default owner, due in 14 days. It reopens a failed fix 30 days after the status was set. The
`status_set` column records the status and the date a refresh first saw it, because the
activity log is delivered async and pruned, so a refresh cannot read a status date from it.
"""
from __future__ import annotations

import atexit
import datetime as dt
import hashlib
import json
import math
import re
import shutil
import tempfile
import threading
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

from modules import amazon_sku_metrics as M
from modules import amazon_part_dates as _part_dates
import core.user_tables as _registry
from core import module_tables
from core import amazon_rivals as _rivals

TABLE_KEY = "ut_amazon_sku_profit"
TABLE_LABEL = "Project manager"
#: Earlier module labels of the SKU table. Only these are renamed; a label a person chose stays.
_PRIOR_TABLE_LABELS = ("Project management", "Command Center", "Amazon SKU profit")
PROJECTS_KEY = "ut_amazon_projects"
PROJECTS_LABEL = "Projects"
ASIN_KEY = "ut_amazon_asin_profit"
ASIN_LABEL = "Child ASIN"
PARENT_KEY = "ut_amazon_parent_profit"
PROFIT_MAX_FIELDS = 100  # A module table declares its field cap; a connector table stays exempt.
PARENT_LABEL = "Parent ASIN"
# The four tables are the module's, not a person's: they take no MAX_TABLES slot (D-3284 spirit).
_registry.register_module_tables(TABLE_KEY, PROJECTS_KEY, ASIN_KEY, PARENT_KEY)
# S82-T70 (R33): refresh adds the SKU, ASIN and Parent ASIN rows; a person edits them but never adds
# one. Never `register_locked_records`: that turns `records_mutable` False and the edit doors then
# refuse Owner, Status, Due date and Odoo product. Projects stays open.
NO_ADD_KEYS = (TABLE_KEY, ASIN_KEY, PARENT_KEY)
NO_ADD_LINE = "Rows here come from Amazon. Edit a row instead."
module_tables.register_no_add_records(*NO_ADD_KEYS, line=NO_ADD_LINE)
SETTINGS_KEY = "amazon_profit_settings"
COST_HISTORY_KEY = "amazon_profit_cost_history"
VIA = "amazon_profit"
WRITER = "automation"
TENANT_ZERO = "royal-imports"

PERIOD_DEFAULT = "90d"
PERIOD_DAYS = {"30d": 30, "90d": 90}
THIN_DEFAULT = 0.10
STATUSES = ("Open", "Repriced", "Ads cut", "Delisted", "Keep", "COGS wrong")
#: A fix that reopens when the SKU still loses money or runs thin 30 days on. Keep never reopens.
FIX_STATUSES = ("Repriced", "Ads cut", "Delisted", "COGS wrong")
BANDS = ("Losing", "Thin")
NEEDS_REVIEW, LINKED, WRONG_MATCH = "Needs review", "Linked", "Wrong match"
#: The old names stay for callers. A decision word is a Link status option.
CONFIRMED, REJECTED = LINKED, WRONG_MATCH
MATCH_STATES = (NEEDS_REVIEW, LINKED, WRONG_MATCH)
#: Option words a stored table may still hold. `ensure_table` rewrites them, cells included.
LEGACY_MATCH_STATES = {"Confirmed": LINKED, "Rejected": WRONG_MATCH}
LINK_PURPOSE = "the Amazon SKU to its Odoo product for cost and profit"
DUE_DAYS = 14
REOPEN_DAYS = 30
TEMPLATE_KEY = "amazon_sku_profit"
ASIN_TEMPLATE_KEY = "amazon_asin_profit"
PARENT_TEMPLATE_KEY = "amazon_parent_profit"
PROJECT_STATUSES = ("Open", "Done")
PROJECT_HEALTH = ("On track", "Due this week", "Overdue", "Done")
DUE_SOON_DAYS = 7
PICKER_MONTHS = 12
SETTLEMENT_TOLERANCE = 0.02
#: Amazon releases funds about 7 days after delivery, so a month settles about two weeks after it ends.
SETTLEMENT_DEFERRAL_DAYS = 14

ECONOMICS = "amzn_economics"
SETTLEMENTS = "amzn_settlements"
LISTINGS = "amzn_listings"
LOAN_REPAYMENT = "Automated Loan Repayment"
WITHHELD_TAX = "ItemWithheldTax"
_ECONOMICS_REQUIRED = ("msku", "start_date", "sales_net_product_sales_amount",
                       "sales_net_units_sold", "fees_total_amount")
_SETTLEMENT_REQUIRED = ("amount", "posted_date", "transaction_type", "amount_type")
_ADS_TOTAL = re.compile(r"ads_[a-z0-9_]+_amount")
_MONTH = re.compile(r"(\d{4})-(\d{2})")
_LOCK = threading.Lock()


class SourceUnavailable(RuntimeError):
    """The Amazon mirror lacks a table or column this module reads."""


class TableRefused(RuntimeError):
    """The store refused the module table; the message names the cause and the fix."""


def _field(key, label, ftype, description, *, computed, **extra):
    out = {"key": key, "label": label, "type": ftype, "origin": "loopable",
           "valueAuthority": "computed" if computed else "user-entered",
           "scope": "tenant", "description": description}
    if ftype == "currency":
        out["format"] = {"decimals": 2}
    out.update(extra)
    return out


def _progress_fields(description, *, key="projects", label="Projects", empty_label="No projects"):
    """Project progress and its completed-count label, written by the Projects doors."""
    return (_field(key, label, "pct", description, computed=True,
                   format={"display": "progress", "labelKey": key + "_label", "emptyLabel": empty_label}),
            _field(key + "_label", label + (" completed" if key == "projects" else " label"), "text",
                   "Completed projects of the counted ones." if key == "projects" else "Open PDP workflow stage and progress.",
                   computed=True))


HISTORY_FIELD = _field("history", "History", "text", "Open the row's recorded changes.", computed=True)
ASIN_APP_KEYS = ("asin", "projects", "pdp_update", "trend_score", "search_trend", "market_share_trend",
                 "click_share_trend", "exposure", "funnel_score", "pdp_last_updated", "title_last_updated",
                 "bullets_last_updated", "images_last_updated", "aplus_last_updated", "history")
SEARCH_TRENDS = (("search", "search_trend", "Search trend", "int"),
                 ("market_share", "market_share_trend", "Market share trend", "pct"),
                 ("click_share", "click_share_trend", "Click share trend", "pct"))
EXPOSURES = {"under": "Under-exposed", "match": "Matched", "over": "Over-exposed",
             "few": "Few", "none": "Not seen"}
PDP_PART_DATE_KEYS = tuple(part + "_last_updated" for part in ("title", "bullets", "images", "aplus"))
PDP_CELL_KEYS = ("pdp_update", "pdp_update_label", "pdp_update_more") + PDP_PART_DATE_KEYS
_PDP_PROGRESS_FIELDS = _progress_fields("Progress of the earliest open PDP workflow.", key="pdp_update",
                                       label="PDP update", empty_label="No open workflow")
_SIGNAL_FIELDS = (
    _field("trend_score", "Trend score", "int", "Search trend score from 0 to 100.", computed=True),
    *(_field(key, label, "pct", "Change against the same reported months last year.", computed=True)
      for _, key, label, _ in SEARCH_TRENDS),
    _field("exposure", "Exposure", "select", "Sales or click share against impression share.",
           computed=True, options=list(EXPOSURES.values())),
    _field("funnel_score", "Funnel score", "int", "Search-weighted funnel score, with 5 at the market.",
           computed=True, format={"decimals": 1}),
)
_ASIN_DATE_FIELDS = tuple(_field(key, label, "date", "Latest recorded listing or part change.", computed=True)
                          for key, label in zip(("pdp_last_updated",) + PDP_PART_DATE_KEYS,
                                                ("PDP last updated", "Title last updated", "Bullets last updated",
                                                 "Images last updated", "A+ last updated")))
_SIGNAL_COMPANIONS = tuple(field for kind, key, label, now_type in SEARCH_TRENDS for field in (
    _field(key + "_series", label + " series", "text", "Every reported historical month, with raw values, ASIN gaps and reasons.", computed=True),
    _field(key + "_now", label + " now", now_type, "Searches in the newest complete store month." if kind == "search"
           else "Share aggregated over the twelve-month calculation window.", computed=True),
    _field(key + "_reason", label + " reason", "text", "Why the year comparison is unavailable.", computed=True),
    _field(key + "_now_reason", label + " now reason", "text", "Why the current value is unavailable.", computed=True),
)) + tuple(_field(key + "_reason", label + " reason", "text", "Why this signal is unavailable.", computed=True)
           for key, label in (("trend_score", "Trend score"), ("funnel_score", "Funnel score"), ("exposure", "Exposure")))
_ASIN_COMPANIONS = (_PDP_PROGRESS_FIELDS[1:]
                    + (_field("pdp_update_more", "More PDP workflows", "int", "Other open PDP workflows.", computed=True),)
                    + _SIGNAL_COMPANIONS
                    + (_field("exposure_label", "Exposure detail", "text", "Exposure multiple and comparison base.", computed=True),
                       _field("pdp_last_updated_reason", "PDP date reason", "text", "Why Amazon's listing date is unavailable.", computed=True)))
_ASIN_SOURCE_KEYS = tuple(f["key"] for f in _SIGNAL_FIELDS + _SIGNAL_COMPANIONS) + (
    "exposure_label", "pdp_last_updated", "pdp_last_updated_reason")


def _metric_fields(skip=()):
    """The sibling metric module's columns, as computed fields of this module."""
    return tuple(_field(key, label, ftype, description, computed=True, **dict(extra or {}))
                 for key, label, ftype, description, extra in M.METRIC_COLUMNS if key not in skip)


#: The profit columns: figures from the economics mirror and Odoo cost, written by `cells`.
_ECON_FIELDS = (
    _field("sku", "SKU", "text", "Amazon seller SKU.", computed=True),
    _field("asin", "ASIN", "text", "Amazon product id.", computed=True),
    _field("title", "Title", "text", "Listing title.", computed=True),
    _field("period", "Period", "text", "Dates these figures cover.", computed=True),
    _field("units_sold", "Units sold", "int", "Net units sold in the period.", computed=True),
    _field("net_sales", "Net sales", "currency", "Sales after refunds.", computed=True),
    _field("fees", "Fees", "currency", "Amazon fees.", computed=True),
    _field("sponsored_ads", "Sponsored ads", "currency", "Ad spend.", computed=True),
    _field("net_proceeds", "Net proceeds", "currency", "Net sales minus fees and ads.",
           computed=True),
    _field("sales_note", "Sales note", "text", "Why sales, units, fees or proceeds are blank.", computed=True),
    _field("cogs_per_unit", "COGS per unit", "currency", "Receipt purchase and landed cost per Amazon unit.",
           computed=True),
    _field("cogs_total", "COGS total", "currency", "COGS per unit times units sold.",
           computed=True),
    _field("net_profit", "Net profit", "currency", "Net proceeds minus COGS.", computed=True),
    _field("margin", "Margin", "pct", "Net profit over net sales.", computed=True),
    _field("cost_note", "Cost note", "text", "Why COGS, profit or margin is blank.", computed=True),
    _field("band", "Band", "select", "Losing or thin.", computed=True, options=list(BANDS)),
    _field("cost_receipt", "Receipt", "text", "Receipts supplying these units in FIFO order.", computed=True),
    _field("cost_source", "Cost source", "text", "Landed cost, purchase price or missing coverage.", computed=True),
    _field("cost_coverage", "Cost coverage", "text", "Covered Odoo units and allocation method.", computed=True),
    _field("cost_history", "Cost history", "text", "Saved receipt observations, appended only on refresh.",
           computed=True),
    _field("odoo_channel_sales", "Odoo channel sales", "currency", "Confirmed Fisch and Royal sales excluding Amazon.",
           computed=True),
    _field("odoo_channel_profit", "Odoo channel profit", "currency", "Odoo margin on those sales in this period.",
           computed=True),
    _field("odoo_channel_margin", "Odoo channel margin", "pct", "Odoo margin divided by those sales.",
           computed=True),
    _field("odoo_margin_source", "Odoo margin source", "text", "Scope or missing Odoo margin data.", computed=True),
)
_ECON_KEYS = tuple(f["key"] for f in _ECON_FIELDS)
#: The row's main listing picture: an identity cell, set after the rollup and never summed.
PICTURE_FIELD = _field("picture", "Picture", "image", "Main Amazon listing picture.", computed=True)
#: Why a health label, the score, the priority or a trend is blank. It sits after the trends.
HEALTH_NOTE_FIELD = _field("health_note", "Health note", "text", "Why health, score or a trend is blank.",
                           computed=True)
#: Computed columns: a refresh owns them and the pre-set lock keeps people out of them.
COMPETITOR_FIELDS = tuple(_field(k, label, t, d, computed=True, **dict(x))
                          for k, label, t, d, x in _rivals.ROW_COLUMNS)
PARENT_COMPETITOR_FIELDS = tuple(_field(k, label, t, d, computed=True, **dict(x))
                                 for k, label, t, d, x in _rivals.PARENT_COLUMNS)
COMPETITOR_KEYS = _rivals.ROW_KEYS + _rivals.PARENT_KEYS
_SKU_PROJECT_FIELDS = _progress_fields("Average progress of the projects on this SKU, its ASIN and its parent ASIN.")
COMPUTED_FIELDS = (_ECON_FIELDS[:1] + _SKU_PROJECT_FIELDS[:1] + (HISTORY_FIELD, PICTURE_FIELD) + _ECON_FIELDS[1:] + _metric_fields()
                   + (HEALTH_NOTE_FIELD,) + _SKU_PROJECT_FIELDS[1:]
                   + COMPETITOR_FIELDS)
#: Owned columns: people edit them and a refresh never writes them.
OWNED_FIELDS = (
    _field("odoo_product", "Odoo product", "text", f"Links {LINK_PURPOSE}.", computed=False),
    _field("units_per_sku", "Units per SKU", "int", "Odoo units in one Amazon unit.",
           computed=False, format={"decimals": 4}),
    _field("owner", "Owner", "user", "Who acts on this SKU.", computed=False),
    _field("status", "Status", "select", "Where the action stands.", computed=False,
           options=list(STATUSES)),
    _field("due", "Due date", "date", "When the action is due.", computed=False),
    _field("match_state", "Link status", "select", f"Linked links {LINK_PURPOSE}.",
           computed=False, options=list(MATCH_STATES)),
    # S82-T71: Data Entry writes these back here. Restock reads carton CBM over units per carton.
    _field("carton_size", "Carton size", "text", "Carton dimensions, as typed.", computed=False),
    _field("units_per_carton", "Units per carton", "int", "Amazon units in one carton.",
           computed=False, format={"decimals": 4}),
    _field("carton_cbm", "Carton CBM", "int", "Cubic meters of one carton.",
           computed=False, format={"decimals": 6}),
    _field("amazon_cogs", "Amazon COGS", "currency", "Typed cost of one Amazon unit.", computed=False),
)
#: Owned columns Data Entry writes back besides the link (S82-T71). Their keys stay stable.
ENTRY_KEYS = ("carton_size", "units_per_carton", "carton_cbm", "amazon_cogs")
#: Tracking columns: a refresh writes them, people read them, and a period switch keeps them.
TRACK_FIELDS = (
    _field("status_set", "Status set", "text", "The status and the day a refresh first saw it.",
           computed=True),
    _field("suggested_product", "Suggested Odoo product", "text",
           f"The match a person can accept. It links {LINK_PURPOSE}.", computed=True),
    _field("suggested_units", "Suggested units", "int", "Odoo units in one Amazon unit.",
           computed=True, format={"decimals": 4}),
    _field("match_rule", "Match rule", "text", "How the matcher found the product.", computed=True),
    _field("match_rejected", "Rejected matches", "text", "Odoo codes a person rejected.",
           computed=True),
    # S82-T73 (R43): which cost a refresh used. A period switch keeps it.
    _field("cogs_source", "COGS source", "text", "Odoo receipt, or Typed when no receipt exists.",
           computed=True),
)
#: COGS source cells (R43): the Odoo receipt cost wins and a typed Amazon COGS fills SKUs with no receipt.
COGS_RECEIPT = "Odoo receipt"
COGS_TYPED = "Typed"
TYPED_COST_SOURCE = "Typed Amazon COGS"
COMPUTED_KEYS = tuple(f["key"] for f in COMPUTED_FIELDS)
OWNED_KEYS = tuple(f["key"] for f in OWNED_FIELDS)
TRACK_KEYS = tuple(f["key"] for f in TRACK_FIELDS)
ALL_KEYS = COMPUTED_KEYS + OWNED_KEYS + TRACK_KEYS
SUGGESTION_KEYS = ("suggested_product", "suggested_units", "match_rule")
METRIC_KEYS = tuple(column[0] for column in M.METRIC_COLUMNS)
#: A failed rollup tie blanks Amazon totals while independent receipt observations remain visible.
#: Metrics built from economics figures blank with them. Ads, stock, returns and listing
#: metrics come from their own mirror tables, so they stay.
_UNVERIFIED_KEYS = ("units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds",
                    "cogs_total", "net_profit", "margin", "band") + tuple(
    k for k in ("tacos", "profit_health", "score", "priority", "units_30d", "net_sales_30d", "ad_spend",
                "ad_spend_30d")
    if k in METRIC_KEYS)
#: What a failed settlement component withholds (`withheld_parts`). Any failure also withholds profit.
_WITHHELD_BY_PART = {
    "product sales": tuple(k for k in ("net_sales", "units_sold", "net_sales_30d", "units_30d", "tacos")
                           if k in ("net_sales", "units_sold") or k in METRIC_KEYS),
    "order fees": ("fees",),
    # Published fees is fees_total_amount, which carries the storage, reimbursement and account accruals.
    "monthly storage": ("fees",),
    "reimbursements": ("fees",),
    "account fees": ("fees",),
    "ads": tuple(k for k in ("sponsored_ads", "ad_spend", "ad_spend_30d", "tacos")
                 if k == "sponsored_ads" or k in METRIC_KEYS),
}
_WITHHELD_PROFIT = ("net_proceeds", "cogs_total", "net_profit", "margin", "band") + tuple(
    k for k in ("profit_health", "score", "priority") if k in METRIC_KEYS)
#: A metric check that fails blanks these on every table. The ids and the notes stay.
_METRIC_VALUE_KEYS = tuple(k for k in METRIC_KEYS if k not in ("parent_asin",) + M.NOTE_KEYS)
#: Cost reasons (R5, D-11172 sibling): a blank COGS, profit or margin names what is missing.
LINK_NOTE = "Link this SKU to its Odoo product in Data Entry."
PRODUCT_MISSING_NOTE = "Linked Odoo product not found. Check the link in Data Entry."
GRAIN_LINK_NOTE = "Link each SKU here to its Odoo product in Data Entry."
GRAIN_COST_NOTE = "A SKU here has no cost. Check the SKU tab."
NO_COST_NOTE = "No Odoo cost for this SKU."
COST_FIGURES = ("cogs_per_unit", "cogs_total", "net_profit", "margin")
ODOO_CHANNEL_FIGURES = ("odoo_channel_sales", "odoo_channel_profit", "odoo_channel_margin")
#: The period, sales and rollup count figures. A blank one comes only from a refusal or an absent row.
SALES_FIGURES = ("period", "sku_count", "skus", "units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds")
#: Health labels, score, priority and trends. A blank one comes only from a refusal or an absent row.
HEALTH_FIGURES = ("stock_health", "profit_health", "ads_health", "listing_health", "score", "priority",
                  "units_30d", "net_sales_30d", "ad_spend_30d")
#: Every reason column and the figures it explains, on all three tables.
BLANK_REASONS = {"sales_note": SALES_FIGURES, **M.NOTE_GROUPS, "cost_note": COST_FIGURES,
                 "odoo_margin_source": ODOO_CHANNEL_FIGURES, "health_note": HEALTH_FIGURES}
#: Every declared figure that holds a number or a reason (S85-T125). A blank Band is "neither Losing nor Thin"
#: when net profit is set; otherwise the cost or sales note explains it.
DECLARED_FIGURES = tuple(dict.fromkeys(f for figures in BLANK_REASONS.values() for f in figures)) + ("band",)
BLANK_CHECK = "every blank says why"
#: Every refusal sentence starts so.
REFUSED_PREFIX = "Not verified"


def unexplained_blanks(row, keys=None):
    """`[figure key]` blank in `row` with an empty reason column. `keys`: the table's field keys.
    A refusal in the Period cell is no reason: the rows route projects it to the period label."""
    have = set(row if keys is None else keys)
    out = [figure for note, figures in BLANK_REASONS.items() if not str(row.get(note) or "").strip()
           for figure in figures if figure in have and row.get(figure) in (None, "")]
    explained = any(str(row.get(k) or "").strip() for k in ("net_profit", "cost_note", "sales_note"))
    if "band" in have and row.get("band") in (None, "") and not explained:
        out.append("band")
    return out


def declared_figures(keys):
    """The declared figures a table with these field keys holds, in declaration order."""
    have = set(keys)
    return [figure for figure in DECLARED_FIGURES if figure in have]


def row_active(row):
    """A row with units sold or net sales in its period."""
    return M._active(row)


def blank_check(tables):
    """`every blank says why` over `{table key: (field keys, rows)}`: ok when no declared figure is blank
    without its reason. Counts only; it names figures, never row keys or values."""
    blanks = unexplained = rows = 0
    figures = {}
    for keys, table_rows_ in tables.values():
        declared = declared_figures(keys)
        for row in table_rows_:
            rows += 1
            blanks += sum(1 for figure in declared if row.get(figure) in (None, ""))
            for figure in unexplained_blanks(row, keys):
                unexplained += 1
                figures[figure] = figures.get(figure, 0) + 1
    return {"check": BLANK_CHECK, "ok": rows > 0 and not unexplained, "rows": rows, "blanks": blanks,
            "unexplained": unexplained, "figures": dict(sorted(figures.items()))}


def cost_note(row, *, code=None, found=True):
    """Why a SKU's COGS, profit or margin is blank; "" when all four are set."""
    blank = [k for k in COST_FIGURES if row.get(k) is None]
    if not blank:
        return ""
    if not code and not found:
        return LINK_NOTE
    if not found:
        return PRODUCT_MISSING_NOTE
    if blank == ["margin"]:
        return M.NO_NET_SALES_NOTE
    source = str(row.get("cost_source") or "").strip()
    if source and row.get("cogs_per_unit") is None:
        return source if source.endswith(".") else source + "."
    return NO_COST_NOTE
_IDENTITY_KEYS = ("sku", "picture", "asin", "parent_asin", "title", "projects", "projects_label", "history")
_PERIOD_KEYS = tuple(k for k in COMPUTED_KEYS if k not in _IDENTITY_KEYS + COMPETITOR_KEYS)

#: The profit block a rollup table carries; `_ECON_ADDITIVE` sums, margin and band recompute.
_ECON_ADDITIVE = ("units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds", "cogs_total",
                  "net_profit")
_ROLLUP_ECON = ("period",) + _ECON_ADDITIVE[:5] + ("sales_note",) + _ECON_ADDITIVE[5:] + ("margin", "cost_note", "band")


def _grain_fields(key_column, grain):
    """ASIN or parent ASIN table columns: ids, SKU count, the profit block, metrics, projects."""
    econ = {f["key"]: f for f in _ECON_FIELDS}
    metric = {f["key"]: f for f in _metric_fields()}
    rollup = tuple(_field(key, label, ftype, description, computed=True, **dict(extra or {}))
                   for key, label, ftype, description, extra in M.ROLLUP_COLUMNS)
    ids = ((econ["asin"], PICTURE_FIELD, metric["parent_asin"]) if key_column == "asin"
           else (metric["parent_asin"], PICTURE_FIELD))
    where = "this ASIN or its parent ASIN" if key_column == "asin" else "this parent ASIN"
    progress = _progress_fields(f"Average progress of the projects on {where}.")
    app = (_PDP_PROGRESS_FIELDS[:1] + _SIGNAL_FIELDS + _ASIN_DATE_FIELDS + (HISTORY_FIELD,)
           if key_column == "asin" else (HISTORY_FIELD,))
    companions = _ASIN_COMPANIONS if key_column == "asin" else ()
    return (ids[:1] + progress[:1] + app + ids[1:] + (econ["title"],) + rollup + tuple(econ[k] for k in _ROLLUP_ECON)
            + _metric_fields(skip=("parent_asin",)) + (HEALTH_NOTE_FIELD,)
            + progress[1:] + companions)


ASIN_FIELDS = _grain_fields("asin", "asin")
PARENT_FIELDS = _grain_fields("parent_asin", "parent_asin")
_ROAS = next((c for c in M.METRIC_COLUMNS if c[0] == "roas"), ("roas", "ROAS", "int", "", {}))
#: Project columns people write: rows are added in the Grid and from the Projects popup.
PROJECT_USER_FIELDS = (
    _field("title", "Title", "text", "What the project changes.", computed=False),
    _field("grain", "Grain", "select", "SKU, ASIN or parent ASIN.", computed=False,
           options=[M.GRAIN_LABELS[grain] for grain in M.GRAINS]),
    _field("key", "Key", "text", "The SKU, ASIN or parent ASIN it works on.", computed=False),
    _field("owner", "Owner", "user", "Who runs the project.", computed=False),
    _field("start_on", "Start", "date", "When the work starts.", computed=False),
    _field("deadline_on", "Deadline", "date", "When the work is due.", computed=False),
    _field("completed_on", "Completed", "date", "When the work was done. Impact counts from this day.",
           computed=False),
    _field("status", "Status", "select", "Open or Done.", computed=False, options=list(PROJECT_STATUSES)),
)
#: Project columns a refresh writes.
PROJECT_COMPUTED_FIELDS = (
    _field("health", "Health", "select", "On track, due this week, overdue or done, from the deadline.",
           computed=True, options=list(PROJECT_HEALTH), format={"display": "dot"}),
    _field("impact", "Impact", "currency", "Net sales since completion minus the same days one year earlier.",
           computed=True),
    _field("net_sales_since", "Net sales since", "currency", "Net sales from completion to yesterday.",
           computed=True),
    _field("net_sales_prior", "Net sales prior", "currency", "Net sales over the same days one year earlier.",
           computed=True),
    _field("units_since", "Units since", "int", "Units from completion to yesterday.", computed=True),
    _field("units_prior", "Units prior", "int", "Units over the same days one year earlier.", computed=True),
    _field("impact_units", "Impact units", "int", "Units since completion minus the same days one year earlier.",
           computed=True),
    _field("roas_since", "ROAS since", _ROAS[2], "Return on ad spend from completion to yesterday.",
           computed=True, **dict(_ROAS[4] or {})),
    _field("roas_prior", "ROAS prior", _ROAS[2], "Return on ad spend over the same days one year earlier.",
           computed=True, **dict(_ROAS[4] or {})),
    _field("impact_state", "Impact state", "text", "Why impact is blank.", computed=True),
)
PROJECT_FIELDS = PROJECT_USER_FIELDS + PROJECT_COMPUTED_FIELDS
PROJECT_USER_KEYS = tuple(f["key"] for f in PROJECT_USER_FIELDS)
PROJECT_COMPUTED_KEYS = tuple(f["key"] for f in PROJECT_COMPUTED_FIELDS)


def table_specs():
    """Every module table in creation order."""
    specs = (
        {"key": TABLE_KEY, "label": TABLE_LABEL, "fields": COMPUTED_FIELDS + OWNED_FIELDS + TRACK_FIELDS,
         "owned": OWNED_KEYS, "keyColumn": "sku", "template": TEMPLATE_KEY},
        {"key": ASIN_KEY, "label": ASIN_LABEL, "fields": ASIN_FIELDS + COMPETITOR_FIELDS, "owned": (),
         "keyColumn": "asin", "template": ASIN_TEMPLATE_KEY},
        {"key": PARENT_KEY, "label": PARENT_LABEL, "fields": PARENT_FIELDS + PARENT_COMPETITOR_FIELDS, "owned": (),
         "keyColumn": "parent_asin", "template": PARENT_TEMPLATE_KEY},
    )
    for spec in specs:
        fields = {f["key"]: f for f in spec["fields"]}
        spec["fields"] = tuple(fields[key] for key in _project_field_order(fields))
    return specs


# ---------------------------------------------------------------- period and threshold

def _today():
    return dt.datetime.now(dt.timezone.utc).date()


def period_bounds(period=None, today=None):
    """`{key, start, end, label}` for 30d, 90d or YYYY-MM; ISO dates, end inclusive."""
    key = str(period or PERIOD_DEFAULT).strip().lower()
    today = today or _today()
    if key in PERIOD_DAYS:
        end = today - dt.timedelta(days=1)
        start = end - dt.timedelta(days=PERIOD_DAYS[key] - 1)
        label = f"Last {PERIOD_DAYS[key]} days"
    else:
        match = _MONTH.fullmatch(key)
        if not match or not 1 <= int(match.group(2)) <= 12:
            raise ValueError("Choose 30 days, 90 days or a calendar month.")
        start = dt.date(int(match.group(1)), int(match.group(2)), 1)
        if start > today:
            raise ValueError("Choose a month that has started.")
        following = (start.replace(day=28) + dt.timedelta(days=4)).replace(day=1)
        end = following - dt.timedelta(days=1)
        label = start.strftime("%B %Y")
    return {"key": key, "start": start.isoformat(), "end": end.isoformat(),
            "label": f"{label} ({start.isoformat()} to {end.isoformat()})"}


def period_choices(today=None, months=PICKER_MONTHS):
    """`[{key, label}]`: 30 days, 90 days, then the last `months` complete calendar months."""
    out = [{"key": key, "label": f"Last {days} days"} for key, days in PERIOD_DAYS.items()]
    first = (today or _today()).replace(day=1)
    for _ in range(months):
        first = (first - dt.timedelta(days=1)).replace(day=1)
        out.append({"key": first.strftime("%Y-%m"), "label": first.strftime("%B %Y")})
    return out


def clean_thin(value):
    """The Thin threshold as a fraction of net sales, 0 to under 1."""
    if value is None or value == "":
        return THIN_DEFAULT
    try:
        number = float(str(value).strip().rstrip("%"))
    except (TypeError, ValueError):
        raise ValueError("Enter the thin margin as a number.") from None
    if str(value).strip().endswith("%"):
        number /= 100.0
    if not math.isfinite(number) or not 0 <= number < 1:
        raise ValueError("Enter the thin margin between 0% and 99%.")
    return number


def last_complete_month(today=None):
    first = (today or _today()).replace(day=1)
    return (first - dt.timedelta(days=1)).strftime("%Y-%m")


def verification_month(period=None, today=None):
    """The month a refresh ties to settlements: a picked month once it has ended, else the last one."""
    key = str(period or PERIOD_DEFAULT).strip().lower()
    last = last_complete_month(today)
    return key if _MONTH.fullmatch(key) and key <= last else last


# ---------------------------------------------------------------- pure arithmetic

def _num(value):
    try:
        number = float(value)
    except (TypeError, ValueError):
        return 0.0
    return number if math.isfinite(number) else 0.0


def band_for(net_profit, margin, thin=THIN_DEFAULT):
    """Losing below 0 profit, Thin below the threshold margin, else no band."""
    if net_profit is None:
        return None
    if net_profit < 0:
        return "Losing"
    if margin is not None and margin < thin:
        return "Thin"
    return None


def compute_row(econ, cost=None, units_per_sku=1, thin=THIN_DEFAULT):
    """One SKU's figures. `cost` None means unlinked: COGS, profit, margin and band stay blank."""
    net_sales = _num(econ.get("net_sales"))
    fees = _num(econ.get("fees"))
    ads = _num(econ.get("ads"))
    units = int(_num(econ.get("units")))
    net_proceeds = net_sales - fees - ads
    row = {"sku": econ.get("sku"), "asin": econ.get("asin") or None,
           "title": econ.get("title") or None, "units_sold": units, "net_sales": net_sales,
           "fees": fees, "sponsored_ads": ads, "net_proceeds": net_proceeds,
           "cogs_per_unit": None, "cogs_total": None, "net_profit": None, "margin": None,
           "band": None}
    if cost is None:
        return row
    cogs_per_unit = _num(cost) * (units_per_sku or 1)
    cogs_total = cogs_per_unit * units
    net_profit = net_proceeds - cogs_total
    margin = (net_profit / net_sales) if net_sales else None
    row.update(cogs_per_unit=cogs_per_unit, cogs_total=cogs_total, net_profit=net_profit,
               margin=margin, band=band_for(net_profit, margin, thin))
    return row


def cells(row, period_label=""):
    """Computed cells as stored strings; None means the cell is blank."""
    out = {}
    for key in _ECON_KEYS:
        value = period_label if key == "period" else row.get(key)

        if value is None or value == "":
            out[key] = None
        elif key in ("margin", "odoo_channel_margin"):
            out[key] = f"{value * 100:.2f}"
        elif key == "units_sold":
            out[key] = str(int(value))
        elif isinstance(value, float):
            out[key] = f"{value:.2f}"
        else:
            out[key] = str(value)
    return out


def odoo_code(value):
    """The Odoo internal reference a cell names: `RI-1` or `[RI-1] Name`."""
    text = str(value or "").strip()
    match = re.match(r"\[([^\]]+)\]", text)
    return (match.group(1) if match else text).strip()


UNITS_DECIMALS = 4


def units_per_sku(value):
    """Odoo units in one Amazon unit, a positive number that may be a fraction (0.1 of a
    1000-piece box). Blank, unreadable or not above 0 reads 1."""
    try:
        number = round(float(str(value).strip()), UNITS_DECIMALS)
    except (TypeError, ValueError):
        return 1.0
    return number if math.isfinite(number) and number > 0 else 1.0


def units_text(value):
    """The stored cell for a units value: at most 4 decimals, no trailing zeros."""
    return f"{units_per_sku(value):.{UNITS_DECIMALS}f}".rstrip("0").rstrip(".")


# ---------------------------------------------------------------- owned items (pure)

_STATUS_SET = re.compile(r"(.+) since (\d{4}-\d{2}-\d{2})")


def status_set_cell(status, day):
    return f"{status} since {day.isoformat()}"


def parse_status_set(value):
    """`(status, date)` from a `status_set` cell, or `(None, None)`."""
    match = _STATUS_SET.fullmatch(str(value or "").strip())
    if not match:
        return None, None
    try:
        return match.group(1), dt.date.fromisoformat(match.group(2))
    except ValueError:
        return None, None


def owned_changes(row, band, *, today, owner=None):
    """Cells a refresh writes on one SKU's owned item. It never overwrites a person's choice,
    except the reopen: a fix 30 days old on a SKU still Losing or Thin goes back to Open."""
    status = str(row.get("status") or "").strip()
    seen, since = parse_status_set(row.get("status_set"))
    due = (today + dt.timedelta(days=DUE_DAYS)).isoformat()
    if not status:
        if band in BANDS:
            out = {"status": "Open", "status_set": status_set_cell("Open", today)}
            if owner and not str(row.get("owner") or "").strip():
                out["owner"] = owner
            if not str(row.get("due") or "").strip():
                out["due"] = due
            return out
        return {"status_set": None} if row.get("status_set") else {}
    if seen != status or since is None:
        return {"status_set": status_set_cell(status, today)}
    if status in FIX_STATUSES and band in BANDS and (today - since).days >= REOPEN_DAYS:
        return {"status": "Open", "due": due, "status_set": status_set_cell("Open", today)}
    return {}


# ---------------------------------------------------------------- mirror reads (SQL only)

def _columns(con, table):
    rows = con.execute("SELECT column_name FROM information_schema.columns WHERE table_name = ?",
                       [table]).fetchall()
    return {r[0] for r in rows}


def _require(con, table, required):
    cols = _columns(con, table)
    if not cols:
        raise SourceUnavailable(f"The Amazon mirror has no {table} table. Sync Amazon first.")
    missing = [c for c in required if c not in cols]
    if missing:
        raise SourceUnavailable(f"{table} lacks {', '.join(missing)}. Resync Amazon economics.")
    return cols


def ads_columns(cols):
    """Per ad type totals; charge detail columns are parts of these totals."""
    return sorted(c for c in cols if _ADS_TOTAL.fullmatch(c) and "_charge_" not in c)


def economics_by_sku(con, start, end):
    """`[{sku, asin, units, net_sales, fees, ads}]`: every SKU in the mirror, period sums."""
    cols = _require(con, ECONOMICS, _ECONOMICS_REQUIRED)
    if "currency_code" in cols:
        currencies = con.execute(f"SELECT count(DISTINCT currency_code) FROM {ECONOMICS}").fetchone()[0]
        if currencies > 1:
            raise SourceUnavailable("Amazon economics mixes currencies; profit needs one currency.")
    ads = " + ".join(f'COALESCE("{c}", 0)' for c in ads_columns(cols)) or "0"
    asin = "arg_max(child_asin, start_date)" if "child_asin" in cols else "NULL"
    window = "FILTER (WHERE left(start_date, 10) BETWEEN ? AND ?)"
    sql = (f"SELECT msku, {asin}, "
           f"COALESCE(SUM(sales_net_units_sold) {window}, 0), "
           f"COALESCE(SUM(sales_net_product_sales_amount) {window}, 0), "
           f"COALESCE(SUM(fees_total_amount) {window}, 0), "
           f"COALESCE(SUM({ads}) {window}, 0) "
           f"FROM {ECONOMICS} WHERE NULLIF(trim(msku), '') IS NOT NULL GROUP BY msku ORDER BY msku")
    rows = con.execute(sql, [start, end] * 4).fetchall()
    return [{"sku": r[0], "asin": r[1], "units": r[2], "net_sales": r[3], "fees": r[4],
             "ads": r[5]} for r in rows]


def titles(con):
    """`{seller_sku: item_name}` from the newest listing snapshot; empty without listings."""
    cols = _columns(con, LISTINGS)
    if not {"seller_sku", "item_name"} <= cols:
        return {}
    order = "COALESCE(_snapshot_date, '')" if "_snapshot_date" in cols else "1"
    rows = con.execute(f"SELECT seller_sku, arg_max(item_name, {order}) FROM {LISTINGS} "
                       "WHERE seller_sku IS NOT NULL GROUP BY seller_sku").fetchall()
    return {r[0]: r[1] for r in rows if r[1]}


def net_proceeds_total(con, start, end, *, drop_fees=False):
    """Net sales minus fees and ads over the window; `drop_fees` is the negative control."""
    cols = _require(con, ECONOMICS, _ECONOMICS_REQUIRED)
    ads = " + ".join(f'COALESCE("{c}", 0)' for c in ads_columns(cols)) or "0"
    fees = "0" if drop_fees else "COALESCE(fees_total_amount, 0)"
    return float(con.execute(
        f"SELECT COALESCE(SUM(COALESCE(sales_net_product_sales_amount, 0) - {fees} - ({ads})), 0) "
        f"FROM {ECONOMICS} WHERE left(start_date, 10) BETWEEN ? AND ?", [start, end]).fetchone()[0])


def reported_net_proceeds(con, start, end):
    """Amazon's own netProceeds total over the window, or None if the column is absent."""
    if "net_proceeds_total_amount" not in _columns(con, ECONOMICS):
        return None
    return float(con.execute(
        f"SELECT COALESCE(SUM(net_proceeds_total_amount), 0) FROM {ECONOMICS} "
        "WHERE left(start_date, 10) BETWEEN ? AND ?", [start, end]).fetchone()[0])


def economics_currency(con):
    if "currency_code" not in _columns(con, ECONOMICS):
        return None
    currency, count, missing = con.execute(
        f"SELECT max(currency_code), count(DISTINCT currency_code), "
        f"count(*) FILTER (WHERE NULLIF(trim(currency_code), '') IS NULL) FROM {ECONOMICS}").fetchone()
    if count > 1 or missing:
        raise SourceUnavailable("Amazon economics needs one known currency.")
    return currency


def settlements_total(con, start, end, currency=None):
    """Sum posted settlements with both collected and withheld sales tax included.

    `currency` keeps settlements whose header row names it: Amazon.ca and Amazon.com.mx settle
    in their own currency, outside the economics marketplace. Their reports write DD.MM.YYYY.
    """
    cols = _require(con, SETTLEMENTS, _SETTLEMENT_REQUIRED)
    scoped = currency is not None and {"currency", "settlement_id"} <= cols
    stream = ("JOIN (SELECT settlement_id FROM {t} WHERE currency IS NOT NULL GROUP BY settlement_id "
              "HAVING any_value(currency) = ?) h USING (settlement_id)").format(t=SETTLEMENTS) if scoped else ""
    total, rows, undated = con.execute(
        "SELECT COALESCE(SUM(TRY_CAST(amount AS DECIMAL(38, 2))) "
        "FILTER (WHERE d BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)), 0), "
        "count(*) FILTER (WHERE d BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)), "
        "count(*) FILTER (WHERE d IS NULL AND posted_date IS NOT NULL) "
        "FROM (SELECT amount, posted_date, COALESCE(TRY_CAST(left(posted_date, 10) AS DATE), "
        "CAST(try_strptime(left(posted_date, 10), '%d.%m.%Y') AS DATE)) AS d "
        f"FROM {SETTLEMENTS} s {stream} WHERE COALESCE(transaction_type, '') <> ?)",
        [start, end, start, end] + ([currency] if scoped else []) + [LOAN_REPAYMENT]).fetchone()
    return {"total": float(total), "rows": int(rows), "undated": int(undated),
            "currency": currency if scoped else None}


def _source_drill(con, sql, params, expected):
    """Read every private source row and return only its count, digest and replay query."""
    digest, count = hashlib.sha256(), 0
    cursor = con.execute(sql, params)
    while rows := cursor.fetchmany(256):
        for row in rows:
            digest.update(json.dumps(row, default=str, ensure_ascii=True, separators=(",", ":")).encode())
            digest.update(b"\n")
            count += 1
    return {"sql": sql, "params": params, "expectedRows": int(expected), "rows": count,
            "countMatches": count == expected, "sha256": digest.hexdigest(), "executed": True}


def settlement_components(con, start, end, currency=None, *, drill=False):
    """Tie purchase-date order charges, service-month storage and daily ads to independent sources."""
    month = dt.date.fromisoformat(start).strftime("%B %Y")
    parts, problems, drills, named = [], [], [], []

    def problem(component, reason):
        problems.append(f"Not verified: {component} in {month}: {reason}.")
        named.append(component)

    def tie(component, ours, source, *, reason=None):
        ours = float(ours)
        source = None if source is None else float(source)
        ok, gap = _tie(ours, source) if source is not None else (False, math.inf)
        basis = {"product sales": "order purchase date", "order fees": "order purchase date",
                 "monthly storage": "storage service month", "ads": "daily ad report date"}
        parts.append({"component": component, "month": start[:7], "ok": ok and not reason,
                      "a": ours, "b": source, "gap": gap, "tolerance": SETTLEMENT_TOLERANCE,
                      "dateBasis": basis.get(component, "order purchase date when present, otherwise posted date"),
                      "sourceTables": ([ECONOMICS] + [f"amzn_ads_{kind}_advertised_products" for kind in ("sp", "sb", "sd")]
                                       if component == "ads" else [ECONOMICS, SETTLEMENTS, "amzn_orders"])})
        if reason:
            problem(component, reason)
        elif not ok:
            problem(component, f"independent Amazon amounts differ by {gap:.1%}")

    sc = _columns(con, SETTLEMENTS)
    ec = _columns(con, ECONOMICS)
    required = set(_SETTLEMENT_REQUIRED) | {"settlement_id", "currency", "order_id", "amount_description"}
    if not required <= sc:
        problem("settlement components", "missing source columns " + ", ".join(sorted(required - sc)))
        return {"total": None, "parts": parts, "reason": problems[0], "rows": 0}
    if currency is None:
        problem("settlement components", "economics currency unavailable")
        return {"total": None, "parts": parts, "reason": problems[0], "rows": 0}
    if not {"amazon_order_id", "purchase_date"} <= _columns(con, "amzn_orders"):
        problem("order charges", "missing amzn_orders purchase dates")
        return {"total": None, "parts": parts, "reason": problems[0], "rows": 0}
    unscoped = con.execute(f"""SELECT count(*) FROM {SETTLEMENTS} s
        LEFT JOIN (SELECT settlement_id FROM {SETTLEMENTS} GROUP BY settlement_id
          HAVING count(DISTINCT currency) = 1) h USING (settlement_id)
        WHERE h.settlement_id IS NULL AND (s.amount IS NOT NULL OR NULLIF(s.amount_type, '') IS NOT NULL)
          AND (CAST({_moment_sql('posted_date')} AS DATE) BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)
               OR {_moment_sql('posted_date')} IS NULL)""", [start, end]).fetchone()[0]
    if unscoped:
        problem("settlement currency", "missing or conflicting settlement header currency")
    # Aggregate in SQL before reading: duplicate order lines must not multiply settlement amounts.
    cte = f"""WITH orders AS (
        SELECT amazon_order_id, min(CAST({_moment_sql('purchase_date')} AS DATE)) AS bought,
               count(DISTINCT CAST({_moment_sql('purchase_date')} AS DATE)) AS dates,
               count(*) FILTER (WHERE {_moment_sql('purchase_date')} IS NULL) AS bad_dates
        FROM amzn_orders GROUP BY amazon_order_id),
      streams AS (SELECT settlement_id FROM {SETTLEMENTS} GROUP BY settlement_id
        HAVING count(DISTINCT currency) = 1 AND max(currency) = ?),
      lines AS (SELECT s.*, TRY_CAST(amount AS DECIMAL(38, 2)) AS currency_amount,
                       CAST({_moment_sql('s.posted_date')} AS DATE) AS posted,
                       o.bought, o.dates, o.bad_dates,
          lower(regexp_replace(COALESCE(amount_description, ''), '[^a-zA-Z0-9]', '', 'g')) AS description,
          lower(regexp_replace(COALESCE(amount_type, ''), '[^a-zA-Z0-9]', '', 'g')) AS kind,
          lower(regexp_replace(COALESCE(transaction_type, ''), '[^a-zA-Z0-9]', '', 'g')) AS transaction
        FROM {SETTLEMENTS} s JOIN streams USING (settlement_id)
        LEFT JOIN orders o ON trim(s.order_id) = o.amazon_order_id
        WHERE (amount IS NOT NULL OR NULLIF(amount_type, '') IS NOT NULL)
          AND COALESCE(transaction_type, '') <> ?),
      classified AS (SELECT *, CASE
          WHEN concat(kind, description, transaction) LIKE '%inbounddefect%' THEN 'Inbound Defect Fee'
          WHEN concat(kind, description, transaction) LIKE '%mcf%' THEN 'MCF credits'
          WHEN kind = 'itemwithheldtax' OR description IN ('tax', 'shippingtax', 'giftwraptax')
            OR description LIKE 'marketplacefacilitatortax%' THEN 'tax'
          WHEN (kind = 'itemprice' AND (description IN ('shipping', 'giftwrap')
              OR description LIKE '%promotion%')) OR kind IN ('promotion', 'shipping', 'shippingfees')
            THEN 'shipping and promotions'
          WHEN 'costofadvertising' IN (kind, description, transaction)
            OR description IN ('advertising', 'advertisingfee') THEN 'ads billing'
          WHEN description IN ('storagefee', 'fbamonthlystoragefee', 'monthlystoragefee')
            OR 'fbainventorystoragefee' IN (kind, description, transaction) THEN 'monthly storage'
          WHEN concat(kind, description, transaction) LIKE '%reimbursement%' THEN 'reimbursements'
          WHEN description IN ('subscription', 'subscriptionfee', 'fbaremovalfee', 'fbadisposalfee',
                               'fbainboundtransportationfee', 'couponredemptionfee', 'dealfee')
            OR kind IN ('dealfee', 'lightningdealfee', 'dealparticipationfee', 'dealperformancefee',
                        'fbacustomerreturnfee', 'fbacustomerreturnsfee', 'fbacustomerreturnperunitfee',
                        'fbacustomerreturnprocessingfee', 'fbainboundplacementservicefee')
            OR description IN ('lightningdealfee', 'dealparticipationfee', 'dealperformancefee',
                               'fbacustomerreturnfee', 'fbacustomerreturnsfee', 'fbacustomerreturnperunitfee',
                               'fbacustomerreturnprocessingfee', 'fbainboundplacementservicefee')
            OR transaction IN ('dealfee', 'lightningdealfee', 'dealparticipationfee', 'dealperformancefee',
                               'fbacustomerreturnfee', 'fbacustomerreturnsfee', 'fbacustomerreturnperunitfee',
                               'fbacustomerreturnprocessingfee', 'fbainboundplacementservicefee') THEN 'account fees'
          WHEN NULLIF(trim(order_id), '') IS NOT NULL AND kind = 'itemprice'
            AND description = 'principal' THEN 'product sales'
          WHEN NULLIF(trim(order_id), '') IS NOT NULL AND kind IN ('itemfee', 'itemfees') THEN 'order fees'
          ELSE 'unmatched component' END AS component FROM lines),
      dated AS (SELECT *, CASE
          WHEN component = 'monthly storage' THEN CAST(date_trunc('month', posted) - INTERVAL '1 month' AS DATE)
          WHEN NULLIF(trim(order_id), '') IS NOT NULL THEN bought
          ELSE posted END AS basis FROM classified)
    """
    window = """basis BETWEEN CAST(? AS DATE) AND CAST(? AS DATE)
        OR ((basis IS NULL OR dates <> 1 OR bad_dates <> 0)
            AND (posted BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) OR posted IS NULL))"""
    source_params = [currency, LOAN_REPAYMENT, start, end, start, end]
    groups = con.execute(cte + """SELECT component, COALESCE(SUM(currency_amount), 0), count(*),
        count(*) FILTER (WHERE currency_amount IS NULL OR posted IS NULL),
        count(*) FILTER (WHERE NULLIF(trim(order_id), '') IS NOT NULL
                        AND (bought IS NULL OR dates <> 1 OR bad_dates <> 0))
      FROM dated WHERE """ + window + " GROUP BY component ORDER BY component", source_params).fetchall()
    amounts = {name: total for name, total, *_ in groups}
    if not groups:
        problem("settlement components", "no settlement source rows on the purchase or service dates")
    if drill:
        counts = {row[0]: row[2] for row in groups}
        for name in sorted(set(counts) | {"product sales", "order fees", "monthly storage",
                                          "reimbursements", "account fees", "tax"}):
            query = (cte + "SELECT settlement_id, order_id, posted_date, amount_type, amount_description, "
                     "amount, bought, dates, bad_dates, component, basis FROM dated WHERE (" + window
                     + ") AND component = ? ORDER BY ALL")
            drills.append(dict(_source_drill(con, query, source_params + [name], counts.get(name, 0)),
                               component="sales tax" if name == "tax" else name, source=SETTLEMENTS))
    for name, _total, _n, bad, unmatched in groups:
        if bad or unmatched:
            problem(name, "unmatched purchase date, unreadable posting date or unavailable amount")
        if name in ("unmatched component", "Inbound Defect Fee", "MCF credits"):
            problem(name, "settlement category has no economics mapping")
    fee_columns = sorted(c for c in ec if c.startswith("fee_") and c.endswith("_amount") and "_charge_" not in c)
    storage_columns = [c for c in fee_columns if "storage" in c]
    reimbursement_columns = [c for c in fee_columns if "reimbursement" in c]
    account_columns = [c for c in fee_columns if any(name in c for name in
                      ("subscription", "removal", "disposal", "inbound_transportation", "inbound_placement",
                       "coupon", "deal_", "customer_return", "return_processing", "returns_processing"))]
    # Storage fee columns are accruals in economics; only monthly settlement charges use the prior month.
    sums = ["sales_net_product_sales_amount", "fees_total_amount", *ads_columns(ec),
            *storage_columns, *reimbursement_columns, *account_columns]
    observed = con.execute("SELECT " + ", ".join(f'COALESCE(SUM(TRY_CAST("{c}" AS DECIMAL(38, 2))), 0)' for c in sums)
                           + ", count(*) FILTER (WHERE "
                           + " OR ".join(f'("{c}" IS NOT NULL AND TRY_CAST("{c}" AS DECIMAL(38, 2)) IS NULL)'
                                         for c in sums) + ")"
                           + f" FROM {ECONOMICS} WHERE left(start_date, 10) BETWEEN ? AND ?",
                           [start, end]).fetchone()
    if observed[-1]:
        problem("settlement components", "unavailable economics amount")
    values = dict(zip(sums, observed[:-1]))
    sales, fees = values[sums[0]], values[sums[1]]
    storage = sum(values[c] for c in storage_columns)
    reimbursements = sum(values[c] for c in reimbursement_columns)
    account_fees = sum(values[c] for c in account_columns)
    ads = sum(values[c] for c in ads_columns(ec))
    if drill:
        def expression(columns):
            return " + ".join(f'COALESCE(TRY_CAST("{c}" AS DECIMAL(38, 2)), 0)' for c in columns) or "0"

        non_order = storage_columns + reimbursement_columns + account_columns
        component_columns = {"product sales": ["sales_net_product_sales_amount"],
                             "order fees": ["fees_total_amount", *non_order],
                             "monthly storage": storage_columns, "reimbursements": reimbursement_columns,
                             "account fees": account_columns, "ads": ads_columns(ec)}
        for name, columns in component_columns.items():
            amount = expression(columns)
            if name == "order fees":
                amount = expression(["fees_total_amount"]) + " - (" + expression(non_order) + ")"
            invalid = " OR ".join(f'("{c}" IS NOT NULL AND TRY_CAST("{c}" AS DECIMAL(38, 2)) IS NULL)'
                                  for c in columns) or "FALSE"
            where = f"left(start_date, 10) BETWEEN ? AND ? AND (({amount}) <> 0 OR {invalid})"
            count = con.execute(f"SELECT count(*) FROM {ECONOMICS} WHERE {where}", [start, end]).fetchone()[0]
            selected = list(dict.fromkeys(["start_date", "msku", "currency_code", *columns]))
            projection = ", ".join(f'"{c}"' for c in selected if c in ec)
            query = f"SELECT {projection} FROM {ECONOMICS} WHERE {where} ORDER BY ALL"
            drills.append(dict(_source_drill(con, query, [start, end], count), component=name, source=ECONOMICS))
    tie("product sales", sales, amounts.get("product sales", 0.0))
    tie("order fees", fees - storage - reimbursements - account_fees, -amounts.get("order fees", 0.0))
    tie("monthly storage", storage, -amounts.get("monthly storage", 0.0))
    tie("reimbursements", reimbursements, -amounts.get("reimbursements", 0.0))
    tie("account fees", account_fees, -amounts.get("account fees", 0.0))
    tie("sales tax", 0.0, amounts.get("tax", 0.0))
    # Shipping and promotions lie outside net product sales; ad invoices use a separate billing period.
    if ads or "ads billing" in amounts:
        ad_total = 0
        for kind in ("sp", "sb", "sd"):
            table = f"amzn_ads_{kind}_advertised_products"
            if not {"date", "cost"} <= _columns(con, table):
                problem("ads", f"missing source {table}.cost")
                ad_total = None
                break
            total, count, present = con.execute(
                f"SELECT SUM(TRY_CAST(cost AS DECIMAL(38, 2))), count(*), "
                f"count(TRY_CAST(cost AS DECIMAL(38, 2))) FROM {table} "
                "WHERE left(CAST(date AS VARCHAR), 10) BETWEEN ? AND ?", [start, end]).fetchone()
            if drill:
                query = (f"SELECT date, cost FROM {table} WHERE left(CAST(date AS VARCHAR), 10) "
                         "BETWEEN ? AND ? ORDER BY ALL")
                drills.append(dict(_source_drill(con, query, [start, end], count), component="ads", source=table))
            if not count or count != present or total is None or not math.isfinite(float(total)):
                problem("ads", f"unavailable daily amounts in {table}")
                ad_total = None
                break
            ad_total += total
        tie("ads", ads, ad_total)
    else:
        ad_total = 0
    target = (float(sum(amounts.get(name, 0) for name in
                        ("product sales", "order fees", "monthly storage", "reimbursements", "account fees")))
              - float(ad_total)) if ad_total is not None else None
    return {"total": target, "parts": parts, "reason": problems[0] if problems else None,
            **({"drills": drills, "problems": problems} if drill else {}),
            "failedComponents": list(dict.fromkeys(named)),
            "rows": sum(row[2] for row in groups),
            "excluded": {k: float(amounts[k]) for k in ("shipping and promotions", "ads billing") if k in amounts}}


_COVERAGE_REQUIRED = ("settlement_id", "total_amount", "settlement_start_date", "settlement_end_date")


def _moment_sql(name):
    """A settlement header moment as a UTC timestamp; Amazon.ca and .com.mx write DD.MM.YYYY."""
    text = f"replace(trim(CAST({name} AS VARCHAR)), ' UTC', '')"
    return (f"COALESCE(TRY_CAST({text} AS TIMESTAMPTZ) AT TIME ZONE 'UTC', "
            f"try_strptime({text}, ['%d.%m.%Y %H:%M:%S', '%d.%m.%Y %H:%M', '%d.%m.%Y']))")


def _day_label(day):
    return f"{day.day} {day:%b}"


def settlement_coverage(con, start, end, currency=None):
    """The days of `start`..`end` inside issued settlements, cut at the last full day, and the clear day.

    Without settlement header dates in the mirror the whole window is the tie range, as before.
    `start` is None when no issued settlement covers a full day of the window. `clear` is the last
    close plus the median settlement cycle, stepped until it passes `end`.
    """
    lo, hi = dt.date.fromisoformat(start), dt.date.fromisoformat(end)
    out = {"start": start, "end": end, "partial": False, "clear": None, "source": "window"}
    cols = _columns(con, SETTLEMENTS)
    if not set(_COVERAGE_REQUIRED) <= cols:
        return _coverage_words(out)
    scoped = currency is not None and "currency" in cols
    rows = con.execute(
        f"SELECT {_moment_sql('settlement_start_date')}, {_moment_sql('settlement_end_date')} "
        f"FROM {SETTLEMENTS} WHERE total_amount IS NOT NULL"
        + (" AND trim(CAST(currency AS VARCHAR)) = ?" if scoped else ""),
        [currency] if scoped else []).fetchall()
    spans = sorted((s, e) for s, e in rows if s is not None and e is not None and e > s)
    if not spans:
        return _coverage_words(out)
    merged = []
    for s, e in spans:
        if merged and s <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], e)
        else:
            merged.append([s, e])
    midnight = dt.time(0, 0)
    covered = None
    for s, e in merged:
        # A close is mid-day, so its own day is partial: only whole days count on both sides.
        first = s.date() if s.time() == midnight else s.date() + dt.timedelta(days=1)
        last = (e + dt.timedelta(seconds=1)).date() - dt.timedelta(days=1)
        first, last = max(first, lo), min(last, hi)
        if first <= last:
            covered = (first, last)
    out["source"] = "settlements"
    if covered is None:
        out.update(start=None, end=None)
        return _coverage_words(out)
    out.update(start=covered[0].isoformat(), end=covered[1].isoformat(),
               partial=covered != (lo, hi))
    if covered[1] < hi:
        cycles = sorted(e - s for s, e in spans)
        cycle = cycles[len(cycles) // 2]
        close = max(e for _s, e in spans)
        for _ in range(60):
            if (close + dt.timedelta(seconds=1)).date() - dt.timedelta(days=1) >= hi:
                break
            close += cycle
        out["clear"] = close.date().isoformat()
    return _coverage_words(out)


def _coverage_words(out):
    """Adds `label` and `sentence`: the verified range and the day the rest is due to settle."""
    if out["start"] is None:
        return dict(out, label=None, sentence=None)
    label = " to ".join(_day_label(dt.date.fromisoformat(out[k])) for k in ("start", "end"))
    sentence = f"Verified {label}."
    if out["clear"]:
        sentence += f" The rest settles about {_day_label(dt.date.fromisoformat(out['clear']))}."
    return dict(out, label=label, sentence=sentence)


def _newest_close(con, currency=None):
    """The newest issued settlement close in `currency`, or None without settlement header dates."""
    cols = _columns(con, SETTLEMENTS)
    if not set(_COVERAGE_REQUIRED) <= cols:
        return None
    scoped = currency is not None and "currency" in cols
    close = con.execute(
        f"SELECT max({_moment_sql('settlement_end_date')}) FROM {SETTLEMENTS} WHERE total_amount IS NOT NULL"
        + (" AND trim(CAST(currency AS VARCHAR)) = ?" if scoped else ""),
        [currency] if scoped else []).fetchone()[0]
    return close if isinstance(close, dt.datetime) else None


def _month_end(month):
    first = dt.date.fromisoformat(f"{month}-01")
    return (first.replace(day=28) + dt.timedelta(days=4)).replace(day=1) - dt.timedelta(days=1)


def settled_month(con, month, currency=None):
    """`(month, settling)`: `month` stepped back, at most twice, while Amazon still holds its funds.

    A month is settling while the newest close is before its last day plus SETTLEMENT_DEFERRAL_DAYS.
    `settling` is None when `month` is settled or the mirror has no settlement header dates."""
    close = _newest_close(con, currency)
    if close is None:
        return month, None
    asked = month
    for _ in range(2):
        if close.date() >= _month_end(month) + dt.timedelta(days=SETTLEMENT_DEFERRAL_DAYS):
            break
        month = (dt.date.fromisoformat(f"{month}-01") - dt.timedelta(days=1)).strftime("%Y-%m")
    if month == asked:
        return month, None
    end = _month_end(asked)
    due = end + dt.timedelta(days=SETTLEMENT_DEFERRAL_DAYS)
    clear = settlement_coverage(con, f"{asked}-01", end.isoformat(), currency).get("clear")
    if clear and dt.date.fromisoformat(clear) > due:
        due = dt.date.fromisoformat(clear)
    words = {m: dt.date.fromisoformat(f"{m}-01").strftime("%B %Y") for m in (asked, month)}
    line = (f"{words[asked]} is still settling, so the figures tie to {words[month]}. "
            f"{words[asked]} settles about {_day_label(due)}.")
    return month, {"month": asked, "verifiedMonth": month, "clear": due.isoformat(), "line": line}


# ---------------------------------------------------------------- Odoo cost (read only)

def odoo_costs(codes):
    """`({code: {id, name, cost}}, problems)` for linked references; search_read only (rule 4)."""
    codes = sorted({c for c in codes if c})
    if not codes:
        return {}, []
    import core.odoo as O
    domain = [("default_code", "in", codes), ("active", "in", [True, False])]
    rows = O.search_read("product.product", domain,
                         ["id", "default_code", "name", "standard_price"], limit=len(codes) * 4 + 50)
    expected = O.get_odoo().search_count("product.product", domain)
    if len(rows) != expected:
        raise SourceUnavailable(f"Odoo returned {len(rows)} of {expected} linked products; "
                                "the cost read is incomplete.")
    found, problems = {}, []
    by_code = {}
    for row in rows:
        by_code.setdefault(str(row.get("default_code") or ""), []).append(row)
    for code in codes:
        matches = by_code.get(code) or []
        if len(matches) == 1:
            row = matches[0]
            found[code] = {"id": row["id"], "name": row.get("name") or "",
                           "cost": _num(row.get("standard_price"))}
        elif matches:
            problems.append(f"{code}: {len(matches)} Odoo products share this reference")
        else:
            problems.append(f"{code}: no Odoo product has this reference")
    return found, problems


def bound_cost_reader(runtime):
    """Legacy explicit cost injection, bound to the tenant and unused by production refreshes."""
    def read(codes):
        source = runtime.odoo_source() if hasattr(runtime, "odoo_source") else None
        if source is None:
            return {}, [f"{code}: this workspace has no Odoo connection" for code in sorted(codes)]
        with source._bound():
            return odoo_costs(codes)
    return read


# ---------------------------------------------------------------- receipt costs (mirror only)

_RECEIPT_COLUMNS = {
    "stock_valuation_layer": {"product_id", "quantity", "value", "create_date", "stock_move_id"},
    "stock_move": {"id", "product_id", "date", "state", "picking_id", "location_id", "location_dest_id"},
    "stock_location": {"id", "usage"},
    "stock_picking": {"id", "name", "date_done"},
    "stock_valuation_adjustment_lines": {"id", "cost_id", "product_id", "move_id", "quantity",
                                         "additional_landed_cost", "write_date"},
    "stock_landed_cost": {"id", "date", "state", "amount_total"},
}
_RECEIPT_FROM = (
    "stock_valuation_layer v JOIN stock_move m ON m.id=v.stock_move_id AND m.product_id=v.product_id "
    "JOIN stock_location src ON src.id=m.location_id "
    "JOIN stock_location dst ON dst.id=m.location_dest_id "
    "LEFT JOIN stock_picking p ON p.id=m.picking_id")
_RECEIPT_DATE = ("left(COALESCE(NULLIF(CAST(p.date_done AS VARCHAR), ''), "
                 "NULLIF(CAST(m.date AS VARCHAR), ''), CAST(v.create_date AS VARCHAR)), 10)")


def _require_odoo(con, required):
    """Require physical mirror columns and completed population and column checkpoints."""
    tracked = {"entity", "phase"} <= _columns(con, "_sync_state")
    for table, fields in required.items():
        if not fields <= _columns(con, table):
            raise SourceUnavailable(f"{table}: receipt or margin source unavailable. Sync Odoo.")
        if not tracked:
            raise SourceUnavailable(f"{table}: source completeness unavailable. Sync Odoo.")
        if tracked:
            from harness import datastore as DS
            key = DS._connection_state_key(table)
            state = con.execute("SELECT phase FROM _sync_state WHERE entity=?", [key]).fetchone()
            if not state or state[0] != "live":
                raise SourceUnavailable(f"{table}: source coverage incomplete. Sync Odoo.")
            spec = DS.ENTITIES.get(table) or {}
            fields_to_check = set(spec.get("backfill_fields") or ()) - {"write_date"}
            if table == "stock_landed_cost":
                fields_to_check.update(("date", "state", "amount_total"))
            if fields_to_check:
                states = DS._column_backfill_states(con, table)
                if any(states.get(field, (None,))[0] != "done" for field in fields_to_check):
                    raise SourceUnavailable(f"{table}: source columns incomplete. Sync Odoo.")


def mirror_products(con, codes):
    """Resolve unique internal references without reading standard_price."""
    if not codes:
        return {}, []
    try:
        _require_odoo(con, {"product_product": {"id", "default_code", "name"}})
    except SourceUnavailable as exc:
        return {}, [str(exc)]
    codes = sorted(codes)
    rows = con.execute("SELECT id, default_code, name FROM product_product WHERE default_code IN ("
                       + ",".join("?" for _ in codes) + ") ORDER BY id", codes).fetchall()
    grouped, found, problems = {}, {}, []
    for pid, code, name in rows:
        grouped.setdefault(code, []).append({"id": int(pid), "name": name})
    for code in codes:
        candidates = grouped.get(code, [])
        if len(candidates) == 1:
            found[code] = candidates[0]
        else:
            problems.append(f"{code}: Odoo product reference missing or ambiguous")
    return found, problems


def receipt_costs(con, product_ids=None):
    """Read vendor receipts and posted adjustments, excluding zero-quantity revaluations."""
    if product_ids is not None and not product_ids:
        return []
    _require_odoo(con, _RECEIPT_COLUMNS)
    params = sorted(set(product_ids or ()))
    scope = (" AND v.product_id IN (" + ",".join("?" for _ in params) + ")") if params else ""
    rows = con.execute(
        f"SELECT v.product_id, m.id, p.name, {_RECEIPT_DATE} AS day, SUM(v.quantity), SUM(v.value), "
        f"count(*) FILTER (WHERE v.value IS NULL OR NOT isfinite(v.value)) FROM {_RECEIPT_FROM} "
        "WHERE m.state='done' AND src.usage='supplier' AND dst.usage='internal' AND v.quantity>0"
        + scope + " GROUP BY v.product_id, m.id, p.name, day ORDER BY day, m.id, v.product_id", params).fetchall()
    adjustments = con.execute(
        "SELECT a.id, a.cost_id, a.product_id, a.move_id, a.quantity, a.additional_landed_cost, "
        "CAST(a.write_date AS VARCHAR), h.state, CAST(h.date AS VARCHAR) "
        "FROM stock_valuation_adjustment_lines a LEFT JOIN stock_landed_cost h ON h.id=a.cost_id"
        + (" WHERE a.product_id IN (" + ",".join("?" for _ in params) + ")" if params else "")
        + " ORDER BY a.id", params).fetchall()
    by_move = {}
    for aid, cid, pid, move, quantity, amount, written, state, day in adjustments:
        if state is None:
            raise SourceUnavailable("Landed cost header missing. Sync Odoo before using receipt costs.")
        if state != "done":
            continue
        by_move.setdefault((pid, move), []).append({"id": int(aid), "cost_id": int(cid),
            "quantity": None if quantity is None else float(quantity),
            "amount": None if amount is None else float(amount), "write_date": written, "date": day})
    receipts = []
    for pid, move, name, day, quantity, value, invalid in rows:
        lines = by_move.get((pid, move), [])
        invalid_line = any(line["quantity"] is None or _num(line["quantity"]) <= 0
                           or line["amount"] is None or not math.isfinite(float(line["amount"]))
                           or not line["date"] for line in lines)
        if invalid or invalid_line or not name or not day or not math.isfinite(float(quantity)):
            raise SourceUnavailable("Receipt valuation or landed allocation incomplete. Sync Odoo.")
        try:
            dt.date.fromisoformat(day)
        except ValueError:
            raise SourceUnavailable("Receipt date unavailable. Sync Odoo.") from None
        purchase = float(value) / float(quantity)
        landed = sum(float(line["amount"]) / float(line["quantity"]) for line in lines)
        row = {"receipt_key": f"{int(pid)}:{int(move)}", "product_id": int(pid), "move_id": int(move),
               "receipt": name, "date": day, "quantity": float(quantity),
               "purchase_unit_cost": purchase, "landed_unit_cost": landed,
               "unit_cost": purchase + landed, "landed_lines": lines,
               "source": "Landed cost" if lines else "Purchase price (no landed costs)"}
        row["observation_id"] = hashlib.sha256(json.dumps(row, sort_keys=True).encode()).hexdigest()
        receipts.append(row)
    return receipts


def read_cost_history(st):
    """Read saved observations strictly so a failed read cannot replace history."""
    # A TenantRuntime has no _read_strict of its own: read through its backend's, under its key.
    reader = getattr(st, "_read_strict", None)
    if reader is None and callable(getattr(st, "_store", None)) and callable(getattr(st, "store_key", None)):
        strict = getattr(st._store(), "_read_strict", None)
        if callable(strict):
            reader = lambda name: strict(st.store_key(name))  # noqa: E731
    doc = (reader(COST_HISTORY_KEY) if reader else st.get(COST_HISTORY_KEY, fresh=True)) or {}
    required = {"observation_id", "product_id", "move_id", "receipt", "date", "quantity",
                "purchase_unit_cost", "landed_unit_cost", "unit_cost", "source"}
    if (not isinstance(doc, dict) or doc.get("version", 1) != 1
            or not isinstance(doc.get("receipts", []), list)
            or any(not isinstance(row, dict) or not required <= row.keys() for row in doc.get("receipts", []))):
        raise TableRefused("Receipt cost history is unreadable. Restore it before refreshing.")
    return doc.get("receipts", [])


def append_cost_history(st, receipts):
    """Append new receipt evidence and retain every previous observation unchanged."""
    stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="microseconds")

    def append(cur):
        cur = dict(cur or {})
        prior = cur.get("receipts", [])
        if not isinstance(prior, list) or any(not isinstance(row, dict) or not row.get("observation_id")
                                             for row in prior):
            raise TableRefused("Receipt cost history is unreadable. Restore it before refreshing.")
        seen = {row["observation_id"] for row in prior}
        added = []
        for row in receipts:
            if row["observation_id"] not in seen:
                added.append(dict(row, observed_at=stamp))
                seen.add(row["observation_id"])
        return {**cur, "version": 1, "receipts": prior + added}

    st.update(COST_HISTORY_KEY, append, flush="sync")
    return read_cost_history(st)


def _history_text(history, product_id):
    return "\n".join(
        f"{row['receipt']} | {row['date']} | {row['quantity']:g} Odoo units | "
        f"Purchase {row['purchase_unit_cost']:.2f} | Landed {row['landed_unit_cost']:.2f} | "
        f"Total {row['unit_cost']:.2f} per Odoo unit | {row['source']}"
        for row in history if row["product_id"] == product_id)


def odoo_channel_margins(con, start, end):
    """Read confirmed margins of the tenant's wholesale teams, excluding GIFTWARE DEALS."""
    required = {"sale_order_line": {"order_id", "product_id", "margin", "price_subtotal"},
                "sale_order": {"id", "state", "team_id", "partner_id", "date_order"},
                "res_partner": {"id", "name"}}
    try:
        _require_odoo(con, required)
    except SourceUnavailable:
        return {}, "Odoo margin unavailable"
    import core.odoo as O
    teams = O.active_team_ids()
    if not teams:
        return {}, "Odoo margin unavailable"
    rows = con.execute(
        "SELECT l.product_id, SUM(l.margin), SUM(l.price_subtotal), "
        "count(*) FILTER (WHERE l.margin IS NULL OR l.price_subtotal IS NULL "
        "OR NOT isfinite(l.margin) OR NOT isfinite(l.price_subtotal)) "
        "FROM sale_order_line l JOIN sale_order o ON o.id=l.order_id "
        "JOIN res_partner p ON p.id=o.partner_id WHERE o.state IN ('sale','done') "
        f"AND o.team_id IN ({','.join('?' * len(teams))}) "
        "AND upper(p.name) NOT LIKE '%GIFTWARE DEALS%' "
        "AND l.product_id IS NOT NULL "
        "AND left(CAST(o.date_order AS VARCHAR),10) BETWEEN ? AND ? GROUP BY l.product_id",
        [*teams, start, end]).fetchall()
    return {int(pid): {"profit": None if missing else float(profit),
                      "sales": None if missing else float(sales),
                      "margin": float(profit) / float(sales) if sales and not missing else None,
                      "source": "Odoo margin unavailable" if missing else "Confirmed Fisch and Royal sales"}
            for pid, profit, sales, missing in rows}, "Confirmed Fisch and Royal sales"


def fifo_costs(con, start, end, row_links, products, receipts, history):
    """Allocate each product once by receipt date, sale date and seller SKU, including prior depletion."""
    saved = {row["observation_id"]: row for row in history}
    pools = {}
    for receipt in receipts:
        observed = saved.get(receipt["observation_id"])
        if observed is not None:
            pools.setdefault(receipt["product_id"], []).append({"receipt": observed,
                                                               "left": receipt["quantity"]})
    linked = {sku: (products[link["code"]]["id"], units_per_sku(link.get("units_per_sku")))
              for sku, link in row_links.items() if link.get("code") in products}
    if not linked:
        return {}, []
    product_ids = sorted({pid for pid, _multiplier in linked.values()})
    seller_skus = sorted(linked)
    events = con.execute(
        f"SELECT left(CAST(start_date AS VARCHAR),10), msku, SUM(sales_net_units_sold) "
        f"FROM {ECONOMICS} WHERE left(CAST(start_date AS VARCHAR),10)<=? "
        "AND msku IN (" + ",".join("?" for _ in seller_skus) + ") "
        "GROUP BY 1,2 ORDER BY 1,2", [end, *seller_skus]).fetchall()
    outgoing = con.execute(
        "SELECT v.product_id, left(CAST(m.date AS VARCHAR),10) AS day, m.id, -SUM(v.quantity) "
        f"FROM {_RECEIPT_FROM} WHERE m.state='done' AND src.usage='internal' "
        "AND dst.usage<>'internal' AND v.quantity<0 AND left(CAST(m.date AS VARCHAR),10)<? "
        "AND v.product_id IN (" + ",".join("?" for _ in product_ids) + ") "
        "GROUP BY v.product_id, day, m.id ORDER BY day,m.id", [start, *product_ids]).fetchall()
    prior_products = {int(row[0]) for row in outgoing}
    incomplete = set()
    usage, result = [], {}

    def consume(pid, quantity, day, sku=None):
        remaining, used = quantity, []
        for batch in pools.get(pid, []):
            receipt = batch["receipt"]
            if remaining <= 1e-8:
                break
            if receipt["date"] > day or batch["left"] <= 1e-8:
                continue
            taken = min(batch["left"], remaining)
            batch["left"] -= taken
            remaining -= taken
            used.append({"sku": sku, "product_id": pid, "move_id": receipt["move_id"],
                         "sale_date": day,
                         "observation_id": receipt["observation_id"], "units": taken,
                         "purchase_used": taken * receipt["purchase_unit_cost"],
                         "landed_used": taken * receipt["landed_unit_cost"], "receipt": receipt})
        return used, max(remaining, 0.0)

    for pid, day, _move, quantity in outgoing:
        _used, missing = consume(int(pid), float(quantity), day)
        if missing > 1e-8:
            incomplete.add(int(pid))
    prior_amazon, prior_outgoing = {}, {}
    for day, sku, units in events:
        if day and day < start and sku in linked:
            pid, multiplier = linked[sku]
            prior_amazon[pid] = prior_amazon.get(pid, 0.0) + max(float(units or 0), 0.0) * multiplier
    for pid, _day, _move, quantity in outgoing:
        prior_outgoing[int(pid)] = prior_outgoing.get(int(pid), 0.0) + float(quantity)
    incomplete.update(pid for pid in prior_products if prior_outgoing[pid] + 1e-8 < prior_amazon.get(pid, 0.0))
    for day, sku, units in events:
        if sku not in linked or not day:
            continue
        pid, multiplier = linked[sku]
        quantity = float(units or 0) * multiplier
        if day < start and pid in prior_products:
            continue
        if quantity < 0:
            if day < start:
                incomplete.add(pid)
            else:
                result.setdefault(sku, {"units": 0.0, "missing": 0.0, "usage": []})["returns"] = True
            continue
        used, missing = consume(pid, quantity, day, sku if day >= start else None)
        if day < start:
            if missing > 1e-8:
                incomplete.add(pid)
            continue
        row = result.setdefault(sku, {"units": 0.0, "missing": 0.0, "usage": []})
        row["units"] += quantity
        row["missing"] += missing
        row["usage"].extend(used)
        usage.extend(used)
    for sku, (pid, _multiplier) in linked.items():
        row = result.setdefault(sku, {"units": 0.0, "missing": 0.0, "usage": []})
        row["incomplete_prior"] = pid in incomplete
        row["prior_source"] = "Odoo stock moves" if pid in prior_products else "Amazon unit history"
    return result, usage


def _odoo_binding(runtime):
    source = runtime.odoo_source() if hasattr(runtime, "odoo_source") else None
    if source is None:
        raise SourceUnavailable("This workspace has no Odoo connection.")
    return source._bound()


# ---------------------------------------------------------------- suggested matches (R13)

#: Rule labels a `match_rule` cell stores, in the order the matcher tries them.
RULE_CODE = "Odoo code"
RULE_PREFIX = "Odoo code without prefix"
RULE_PACK = "Odoo code for the pack"
RULE_AMAZON = "Amazon Odoo code"
RULE_BARCODE = "Barcode"
RULE_NAME = "Name"
RULES = (RULE_CODE, RULE_PREFIX, RULE_PACK, RULE_AMAZON, RULE_BARCODE, RULE_NAME)
#: Listing report product id types that carry a barcode: 3 is UPC, 4 is EAN.
BARCODE_ID_TYPES = ("3", "4")
_NAME_STOP = frozenset("a an and the of for with per in x h to by or on inch inches set pack "
                       "piece pieces box bag roll count pcs".split())
_PACK = re.compile(r"(.+?)_(\d{1,4})")
_SELLER_PREFIX = re.compile(r"[A-Za-z]{2,3}[-_ ](?=.)")
_ODOO_PACK = re.compile(r"(\d+)\s*-?\s*pieces?\s+per\s+(?:box|pack|case|bag)", re.I)
_TITLE_PACK = re.compile(r"\b(?:set|pack)\s+of\s+(\d+)\b|\b(\d+)\s*-?\s*(?:pack|pcs|pieces|count)\b", re.I)


def title_pack(title):
    """Pieces in one Amazon unit as the listing title states them ("Set of 12", "100 Pack"), or None."""
    match = _TITLE_PACK.search(str(title or ""))
    n = int(match.group(1) or match.group(2)) if match else 0
    return n if n > 0 else None


def odoo_pack(name):
    """Pieces in one Odoo unit from its name (`24-Piece Per Box` is 24), or None."""
    match = _ODOO_PACK.search(str(name or ""))
    return int(match.group(1)) if match and int(match.group(1)) > 0 else None


def odoo_units(n, name):
    """Odoo units in one Amazon unit of `n` pieces: n / k when the Odoo name states k pieces,
    to 4 decimals and never 0; n when it states none."""
    n = max(int(n or 1), 1)
    k = odoo_pack(name)
    if k is None:
        return float(n)
    return max(round(n / k, UNITS_DECIMALS), 10.0 ** -UNITS_DECIMALS)


def _norm_code(value):
    return re.sub(r"[^A-Z0-9]", "", str(value or "").upper())


def _norm_barcode(value):
    return re.sub(r"\D", "", str(value or "")).lstrip("0")


def _name_tokens(text, brand=()):
    text = str(text or "").lower().split("|")[0]
    return {w for w in re.findall(r"[a-z0-9]+(?:\.[0-9]+)?", text)
            if w not in _NAME_STOP and w not in brand and (len(w) > 1 or w.isdigit())}


def odoo_catalogue():
    """Every Odoo product, active and archived, in one read; search_read and search_count only."""
    import core.odoo as O
    domain = [("active", "in", [True, False])]
    expected = O.get_odoo().search_count("product.product", domain)
    rows = O.search_read("product.product", domain,
                         ["id", "default_code", "barcode", "name"], limit=expected + 50)
    if len(rows) != expected:
        raise SourceUnavailable(f"Odoo returned {len(rows)} of {expected} products; "
                                "the product read is incomplete.")
    return rows


def listing_barcodes(con):
    """`{seller_sku: barcode}` from the newest listing snapshot, UPC and EAN ids only."""
    cols = _columns(con, LISTINGS)
    if not {"seller_sku", "product_id", "product_id_type"} <= cols:
        return {}
    order = "COALESCE(_snapshot_date, '')" if "_snapshot_date" in cols else "1"
    rows = con.execute(f"SELECT seller_sku, arg_max(product_id, {order}), "
                       f"arg_max(CAST(TRY_CAST(product_id_type AS BIGINT) AS VARCHAR), {order}) FROM {LISTINGS} "
                       "WHERE seller_sku IS NOT NULL GROUP BY seller_sku").fetchall()
    return {r[0]: r[1] for r in rows if r[1] and str(r[2]).strip() in BARCODE_ID_TYPES}


class Matcher:
    """Suggests one Odoo product per Amazon SKU. Only a product whose code is unique can link."""

    def __init__(self, products, brand=("royal", "imports")):
        codes = {}
        for p in products:
            code = str(p.get("default_code") or "").strip()
            if code and code != "False":
                codes.setdefault(code, []).append(p)
        self.by_code = {code: rows[0] for code, rows in codes.items() if len(rows) == 1}
        self.by_norm, self.by_barcode = {}, {}
        for code, p in self.by_code.items():
            self.by_norm.setdefault(_norm_code(code), []).append(code)
            barcode = p.get("barcode")
            if barcode and barcode is not False and _norm_barcode(barcode):
                self.by_barcode.setdefault(_norm_barcode(barcode), []).append(code)
        self.brand = frozenset(brand)
        self.tokens = {code: _name_tokens(p.get("name"), self.brand) for code, p in self.by_code.items()}
        df = {}
        for toks in self.tokens.values():
            for w in toks:
                df[w] = df.get(w, 0) + 1
        total = max(len(self.tokens), 1)
        self.idf = {w: math.log(total / (1 + n)) + 1.0 for w, n in df.items()}
        self.index = {}
        for code, toks in self.tokens.items():
            for w in toks:
                self.index.setdefault(w, []).append(code)

    def label(self, code):
        return f"[{code}] {self.by_code[code].get('name') or ''}".strip()

    def _one(self, codes, rejected):
        codes = [c for c in codes or () if c not in rejected]
        return codes[0] if len(codes) == 1 else None

    def _by_code(self, candidate, rejected):
        exact = [c for c in self.by_norm.get(_norm_code(candidate), ()) if c.upper() == candidate.upper()]
        return self._one(exact, rejected) or self._one(self.by_norm.get(_norm_code(candidate)), rejected)

    def code_candidates(self, sku):
        """`[(candidate code, pieces, rule)]` in the order the code rules try them. Pieces is
        the `_n` count for the pack stem, 0 for a pack code (one Odoo unit), None otherwise."""
        raw = str(sku or "").strip()
        out = [(raw, None, RULE_CODE)]
        plain = re.sub(r"\s*\(#?[^)]*\)\s*$", "", raw).lstrip(".#-_ ")
        base = _SELLER_PREFIX.sub("", plain, count=1)
        out += [(plain, None, RULE_PREFIX), (base, None, RULE_PREFIX)]
        pack = _PACK.fullmatch(base)
        if pack:
            stem, n = pack.group(1), int(pack.group(2))
            out += [(f"{stem}-{n:02d}", 0, RULE_PACK), (stem, max(n, 1), RULE_PACK)]
        out += [("AMZ" + c, u, RULE_AMAZON) for c, u, _ in list(out)]
        return [item for item in out if item[0]]

    def pack_units(self, sku):
        base = _SELLER_PREFIX.sub("", str(sku or "").strip().lstrip(".#-_ "), count=1)
        pack = _PACK.fullmatch(re.sub(r"\s*\(#?[^)]*\)\s*$", "", base))
        return max(int(pack.group(2)), 1) if pack else None

    def by_name(self, title, rejected):
        """The product whose every name word (three or more) is in the title, with a clear lead
        on the next. A short generic name such as `WEDDING ARCH` matches too many titles."""
        words = _name_tokens(title, self.brand)
        if not words:
            return None
        seen, scored = set(), []
        for w in words:
            for code in self.index.get(w, ()):
                if code in seen or code in rejected:
                    continue
                seen.add(code)
                toks = self.tokens[code]
                if len(toks) >= 3 and sum(not t[0].isdigit() for t in toks) >= 2 and toks <= words:
                    scored.append((sum(self.idf[t] for t in toks), code))
        scored.sort(reverse=True)
        if not scored or (len(scored) > 1 and scored[0][0] - scored[1][0] < 1.0):
            return None
        return scored[0][1]

    def _units(self, code, n):
        """Pieces in the Amazon unit become Odoo units; 0 (a pack code) or unknown stays 1."""
        return odoo_units(n, self.by_code[code].get("name")) if n else 1.0

    def suggest(self, sku, *, title=None, barcode=None, rejected=()):
        """`{code, product, units, rule}` or None."""
        rejected = set(rejected or ())
        suffix = self.pack_units(sku)
        pieces = suffix or title_pack(title)
        for candidate, n, rule in self.code_candidates(sku):
            code = self._by_code(candidate, rejected)
            if code:
                if n is None:
                    n = None if suffix else pieces
                return {"code": code, "product": self.label(code), "rule": rule,
                        "units": self._units(code, n)}
        if barcode and _norm_barcode(barcode):
            code = self._one(self.by_barcode.get(_norm_barcode(barcode)), rejected)
            if code:
                return {"code": code, "product": self.label(code), "units": self._units(code, pieces),
                        "rule": RULE_BARCODE}
        code = self.by_name(title, rejected) if title else None
        if code:
            return {"code": code, "product": self.label(code), "units": self._units(code, pieces),
                    "rule": RULE_NAME}
        return None


def _rejected_codes(row):
    return [c for c in (s.strip() for s in str(row.get("match_rejected") or "").split(",")) if c]


def decision_changes(row, state):
    """Cells a person's Linked or Wrong match writes on one row; {} when there is nothing to apply."""
    state = LEGACY_MATCH_STATES.get(state, state)
    if str(row.get("odoo_product") or "").strip():
        return {}
    suggested = str(row.get("suggested_product") or "").strip()
    if state == CONFIRMED and suggested:
        return {"odoo_product": suggested,
                "units_per_sku": units_text(row.get("suggested_units")),
                "match_state": CONFIRMED}
    if state == REJECTED and suggested:
        rejected = _rejected_codes(row)
        code = odoo_code(suggested)
        if code and code not in rejected:
            rejected.append(code)
        return {"match_state": REJECTED, "match_rejected": ", ".join(rejected),
                **{k: None for k in SUGGESTION_KEYS}}
    return {}


def _apply_cells(row, changes):
    for key, value in changes.items():
        if value is None:
            row.pop(key, None)
        else:
            row[key] = value


def apply_decisions(st, *, by=WRITER, sku=None, state=None):
    """Apply every Linked or Wrong match status a person set, or one door's decision on
    `sku`. Returns `{confirmed, rejected}` and, for a door, the row after the change."""
    import core.user_tables as ut
    counts, after = {}, {}

    def _set(cur):
        counts.clear()
        after.clear()
        counts.update(confirmed=0, rejected=0)
        table = (cur or {}).get(TABLE_KEY)
        if table is None:
            return cur
        for row in (table.get("rows") or {}).values():
            row_sku = str(row.get("sku") or "").strip()
            if sku is not None and row_sku != sku:
                continue
            want = state if sku is not None else str(row.get("match_state") or "").strip()
            want = LEGACY_MATCH_STATES.get(want, want)
            changes = decision_changes(row, want)
            if changes:
                _apply_cells(row, changes)
                counts["confirmed" if want == CONFIRMED else "rejected"] += 1
            if sku is not None:
                after.update(row)
        return cur

    ut.update_with_activity(TABLE_KEY, _set, st=st, by=by or WRITER, via=VIA, row_ids=None)
    return {**counts, "row": dict(after) if sku is not None else None}


def suggest_matches(st, con, products, *, by=WRITER):
    """Suggest an Odoo product for every unlinked SKU, no cap, in one store write. A SKU whose
    Odoo product is set is never touched. Suggestions go to this table only, never to Odoo."""
    import core.user_tables as ut
    matcher = Matcher(products)
    names, barcodes = titles(con), listing_barcodes(con)
    counts = {}

    def _set(cur):
        counts.clear()
        counts.update(considered=0, suggested=0, unmatched=0, **{rule: 0 for rule in RULES})
        table = (cur or {}).get(TABLE_KEY)
        if table is None:
            return cur
        for row in (table.get("rows") or {}).values():
            sku = str(row.get("sku") or "").strip()
            if not sku or str(row.get("odoo_product") or "").strip():
                continue
            counts["considered"] += 1
            state = str(row.get("match_state") or "").strip()
            found = matcher.suggest(sku, title=names.get(sku) or row.get("title"),
                                    barcode=barcodes.get(sku), rejected=_rejected_codes(row))
            if found is None:
                counts["unmatched"] += 1
                changes = {k: None for k in SUGGESTION_KEYS}
                if state in (NEEDS_REVIEW, CONFIRMED):
                    changes["match_state"] = None
            else:
                counts["suggested"] += 1
                counts[found["rule"]] += 1
                changes = {"suggested_product": found["product"], "match_state": NEEDS_REVIEW,
                           "suggested_units": units_text(found["units"]), "match_rule": found["rule"]}
            _apply_cells(row, {k: v for k, v in changes.items()
                               if v != row.get(k) and not (v is None and k not in row)})
        return cur

    ut.update_with_activity(TABLE_KEY, _set, st=st, by=by or WRITER, via=VIA, row_ids=None)
    return dict(counts)


def _log(line):
    try:
        print(f"amazon_profit: {line}", flush=True)
    except Exception:                                                  # noqa: BLE001
        pass


def _sync_cursor(tenant_key, rt):
    """`(cursor, close)` on the tenant mirror the sync just wrote, else a fresh stored snapshot."""
    from harness import amazon_store
    path = Path(amazon_store._tenant_mirror_path(tenant_key, rt))
    if path.is_file():
        from harness import datastore
        try:
            shared = Path(datastore.DB_PATH).resolve() == path.resolve()
        except Exception:                                              # noqa: BLE001
            shared = False
        if shared:
            cur = datastore.ro_cursor()
        else:
            import duckdb
            cur = duckdb.connect(str(path), read_only=True)
        if _mirror_has_economics(cur) or {'sku', 'attributes', 'summaries'} <= _columns(cur, 'amzn_listing_items'):
            return cur, cur.close
        cur.close()
    for key in [k for k in _SNAPSHOT if k[0] == tenant_key]:
        _SNAPSHOT.pop(key, None)
    cur = snapshot_cursor(tenant_key)
    return cur, cur.close


def sync_matches(tenant_key, synced_tables, *, st=None, con=None, catalogue=None, today=None):
    """Refresh the current period, apply decisions, then suggest for every unlinked SKU.
    Returns the report. It raises on failure; `on_amazon_sync` is the never-raise wrapper."""
    synced = {str(t or "").strip().lower() for t in synced_tables or ()}
    if not synced & {"economics", "listings", "listing_items"}:
        return {"state": "skipped", "synced": sorted(synced)}
    if st is None:
        from harness import amazon_store
        st = amazon_store._runtime_for(tenant_key)
        if st is None:
            raise SourceUnavailable(f"The store for {tenant_key} could not be opened.")
    close = None
    if con is None:
        con, close = _sync_cursor(tenant_key, st)
    try:
        report = {"state": "done"}
        if synced & {"listings", "listing_items"}:
            try:
                report["partDates"] = _part_dates.observe(st, con, day=today or _today())
                report["partDateCells"] = paint_asin_part_dates(st)
            except Exception as exc:  # quality-ok: Date storage failure must not block profit matching.
                report['partDatesError'] = f'{type(exc).__name__}: {exc}'
                _log(f"{tenant_key}: listing part dates failed ({report['partDatesError']}).")
                if not synced & {'economics', 'listings'}:
                    return dict(report, state='failed', reason=report['partDatesError'])
        if not synced & {"economics", "listings"}:
            return report
        try:
            refreshed = refresh(st, con, by=WRITER, today=today, tenant=tenant_key)
            report["refresh"] = {k: refreshed.get(k) for k in ("skus", "linked", "refusal")}
        except Exception as exc:                                       # noqa: BLE001
            report["refreshError"] = f"{type(exc).__name__}: {exc}"
            _log(f"{tenant_key}: the profit refresh failed ({report['refreshError']}); "
                 "suggesting on the rows already stored.")
            with _LOCK:
                ensure_table(st, WRITER)
                reconcile_views(st)
                report["decisions"] = apply_decisions(st)
        if catalogue is None:
            with _odoo_binding(st):
                products = odoo_catalogue()
        else:
            products = catalogue()
        with _LOCK:
            report["matches"] = suggest_matches(st, con, products)
        write_settings(st, matchedAt=dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
                       matches=report["matches"], matchError=None)
        return report
    finally:
        if close is not None:
            try:
                close()
            except Exception:                                          # noqa: BLE001
                pass


def on_amazon_sync(tenant_key, synced_tables):
    """Contract C2 callback after an Amazon sync. Never raises: a failure logs one line naming
    the cause, links nothing and returns."""
    try:
        return sync_matches(tenant_key, synced_tables)
    except Exception as exc:                                           # noqa: BLE001
        reason = f"{type(exc).__name__}: {exc}"
        _log(f"{tenant_key}: no Odoo matches suggested; every SKU stays unlinked. Cause: {reason}")
        try:
            from harness import amazon_store
            st = amazon_store._runtime_for(tenant_key)
            if st is not None:
                write_settings(st, matchError=reason)
        except Exception:                                              # noqa: BLE001
            pass
        return {"state": "failed", "reason": reason}


# ---------------------------------------------------------------- module-owned table

def _definition_fields(fields=None, owned_keys=None):
    """Stored field definitions for one module table; the SKU table by default."""
    import core.user_tables as ut
    fields = tuple(COMPUTED_FIELDS + OWNED_FIELDS + TRACK_FIELDS if fields is None else fields)
    owned = set(OWNED_KEYS if owned_keys is None else owned_keys)
    keys = _project_field_order([f["key"] for f in fields])
    by_key = {}
    # One field per call: `clean_fields` slices a list at `MAX_FIELDS`.
    for raw in fields:
        for field in ut.clean_fields([dict(raw)]) or ():
            by_key[field["key"]] = field
    missing = [key for key in keys if key not in by_key]
    if missing:
        raise TableRefused(f"The Command Center columns failed the table field check: {', '.join(missing)}.")
    out = []
    for key in keys:
        field = dict(by_key[key])
        # editRole governs the column definition only. Cell values on owned columns follow the
        # database edit grant (`may_edit_database`), so editors edit them and viewers cannot.
        field["editRole"] = "admins"
        if key not in owned:
            field["automation"] = {"preset": True, "flowId": VIA}
        out.append(field)
    return out


def _pinned_keys(grain):
    """The App's pinned columns of one grain table, grain key first."""
    return ASIN_APP_KEYS if grain == "asin" else (grain, "projects", "history")


def _project_field_order(keys):
    """Pin App fields in schema defaults and keep companions last, without changing saved layouts."""
    keys = list(keys)
    if not keys or keys[0] not in ("sku", "asin", "parent_asin"):
        return keys
    pinned = _pinned_keys(keys[0])
    companions = (("projects_label",) + tuple(f["key"] for f in _ASIN_COMPANIONS)
                  if keys[0] == "asin" else ())
    return ([key for key in pinned if key in keys]
            + [key for key in keys if key not in pinned + companions]
            + [key for key in companions if key in keys])


def _format_repairs(fields, wanted):
    """`{key: format}` for module fields an adopted table holds without their format."""
    want = {f["key"]: f["format"] for f in wanted if f.get("format")}
    return {f.get("key"): want[f.get("key")] for f in fields or ()
            if isinstance(f, dict) and f.get("key") in want and not f.get("format")}


def _grain_word_repairs(fields, wanted):
    """`{key: {attr: value}}` where a stored table still shows grain keys instead of grain words."""
    want = {f["key"]: f for f in wanted}
    out = {}
    for field in fields or ():
        target = want.get(field.get("key")) if isinstance(field, dict) else None
        if target is None:
            continue
        if field["key"] == "grain" and target.get("options") and field.get("options") != target["options"]:
            out.setdefault("grain", {})["options"] = list(target["options"])
        if field["key"] in ("projects", "pdp_update") and (field.get("type") != target["type"] or "link" in field
                or (field.get("format") or {}) != (target.get("format") or {})):
            out[field["key"]] = {"type": target["type"], "format": dict(target.get("format") or {}), "link": None}
    return out


#: SKU fields whose label, description or options changed. A stored copy is rewritten once.
_RELABELLED = ("odoo_product", "match_state", "suggested_product")


def _relabel_repairs(fields):
    """`{key: {attr: value}}` where a stored SKU table still holds an old label, description or option."""
    want = {f["key"]: f for f in OWNED_FIELDS + TRACK_FIELDS if f["key"] in _RELABELLED}
    out = {}
    for field in fields or ():
        target = want.get(field.get("key")) if isinstance(field, dict) else None
        if target is None:
            continue
        fix = {attr: target[attr] for attr in ("label", "description") if field.get(attr) != target[attr]}
        if target.get("options"):
            # Options a person added stay after the wanted ones; legacy words become the new ones.
            extra = [o for o in field.get("options") or () if o not in target["options"]
                     and o not in LEGACY_MATCH_STATES]
            options = list(target["options"]) + extra
            if field.get("options") != options:
                fix["options"] = options
        if fix:
            out[field["key"]] = fix
    return out


def _legacy_cells(rows):
    """Row ids whose Link status cell still holds an old option word."""
    return [rid for rid, row in (rows or {}).items()
            if isinstance(row, dict) and row.get("match_state") in LEGACY_MATCH_STATES]


def _relabel(table):
    """The SKU table repair step: new labels, descriptions and options, and every stored
    Confirmed or Rejected cell rewritten to Linked or Wrong match. Keys never change."""
    repairs = _relabel_repairs(table.get("fields"))
    for field in table.get("fields") or []:
        field.update(repairs.get(field.get("key")) or {})
    rows = table.get("rows") or {}
    for rid in _legacy_cells(rows):
        rows[rid]["match_state"] = LEGACY_MATCH_STATES[rows[rid]["match_state"]]


def _kept_label(st, table_key, label):
    """The SKU table label to store: `label` over an earlier module label, else the stored one."""
    if table_key != TABLE_KEY:
        return label
    import core.user_tables as ut
    stored = (ut.get_definition(table_key, st=st) or {}).get("label")
    return label if not stored or stored in _PRIOR_TABLE_LABELS else stored


#: The core helper's field placement, kept under this name for its gate.
_insert_missing = module_tables._insert_missing


def ensure_table(st, username, *, table_key=None, label=None, fields=None, owned_keys=None):
    """Create or adopt module tables through `core.module_tables`. Returns the key.

    With no `table_key` it ensures every table in `table_specs` order and returns `TABLE_KEY`.
    Format, grain word, cost description and Link status (`_relabel`) repairs stay here."""
    if table_key is None:
        # module_tables persists only `fieldLimit`; user_tables.field_limit reads that key.
        specs = [{"key": s["key"], "label": _kept_label(st, s["key"], s["label"]),
                  "fields": _definition_fields(s["fields"], s["owned"]), "fieldLimit": PROFIT_MAX_FIELDS}
                 for s in table_specs()]
    else:
        specs = [{"key": table_key, "label": label or table_key, "fields": _definition_fields(fields, owned_keys)}]
    cost_description = next((field["description"] for field in _ECON_FIELDS if field["key"] == "cogs_per_unit"))

    def _stale(spec, have):
        wanted = spec["fields"]
        field_keys = [field["key"] for field in have.get("fields") or []]
        if _project_field_order(field_keys) != field_keys:
            return True
        if _format_repairs(have.get("fields"), wanted) or _grain_word_repairs(have.get("fields"), wanted):
            return True
        if spec["key"] == TABLE_KEY and (_relabel_repairs(have.get("fields")) or _legacy_cells(have.get("rows"))):
            return True
        return spec["key"] == TABLE_KEY and any(f.get("key") == "cogs_per_unit" and f.get("description") != cost_description
                                                for f in have.get("fields") or [])

    def _repair(spec, table):
        repairs = _format_repairs(table.get("fields"), spec["fields"])
        words = _grain_word_repairs(table.get("fields"), spec["fields"])
        for field in table.get("fields") or []:
            if field.get("key") in repairs:
                field["format"] = dict(repairs[field["key"]])
            field.update(words.get(field.get("key")) or {})
            if "link" in field and field["link"] is None:
                field.pop("link")
            if spec["key"] == TABLE_KEY and field.get("key") == "cogs_per_unit":
                field["description"] = cost_description
        if spec["key"] == TABLE_KEY:
            _relabel(table)
        fields_by_key = {field["key"]: field for field in table.get("fields") or []}
        table["fields"] = [fields_by_key[key] for key in _project_field_order(fields_by_key)]

    keys = module_tables.ensure_module_table(st, username, specs, owner=WRITER, stale=_stale, repair=_repair,
                                             error=TableRefused)
    return keys[0] if table_key is not None else TABLE_KEY


def _ensure_table_grants(st, keys):
    """Add the everyone view grant to each stored module table that lacks it; keep other entries."""
    module_tables.ensure_everyone_grant(st, keys, owner=WRITER)


def table_rows(st, table_key=TABLE_KEY):
    import core.user_tables as ut
    return dict((ut.get_one(table_key, st) or {}).get("rows") or {})


def typed_costs(rows):
    """`{sku: typed Amazon COGS}` for every SKU row whose typed value is a number of 0 or more."""
    out = {}
    for row in rows.values():
        sku = str(row.get("sku") or "").strip()
        text = str(row.get("amazon_cogs") or "").strip().replace(",", "").lstrip("$")
        try:
            value = float(text)
        except ValueError:
            continue
        if sku and math.isfinite(value) and value >= 0:
            out[sku] = value
    return out


def links(rows):
    """`{sku: {code, units_per_sku}}` from the owned columns."""
    out = {}
    for row in rows.values():
        sku = str(row.get("sku") or "").strip()
        if sku:
            out[sku] = {"code": odoo_code(row.get("odoo_product")),
                        "units_per_sku": units_per_sku(row.get("units_per_sku"))}
    return out


def _rid_order(rid):
    text = str(rid)
    return (0, int(text), text) if text.isdigit() else (1, 0, text)


def merge_duplicates(st):
    """Keep one row per SKU (R10): the oldest row takes empty owned cells from its copies,
    then the copies go. Returns how many rows were removed."""
    import core.user_tables as ut
    groups = {}
    for rid, row in table_rows(st).items():
        sku = str(row.get("sku") or "").strip()
        if sku:
            groups.setdefault(sku, []).append(str(rid))
    extra = {}
    for rids in groups.values():
        if len(rids) > 1:
            rids.sort(key=_rid_order)
            extra[rids[0]] = rids[1:]
    if not extra:
        return 0
    dropped = [rid for rids in extra.values() for rid in rids]

    def _merge(cur):
        table = cur.get(TABLE_KEY)
        if table is None:
            return cur
        rows = table.get("rows") or {}
        order = table.get("_rowCreationOrder") or {}
        for keep, copies in extra.items():
            row = rows.get(keep)
            if row is None:
                continue
            for rid in copies:
                copy = rows.pop(rid, None) or {}
                order.pop(rid, None)
                for key in OWNED_KEYS + TRACK_KEYS:
                    if not str(row.get(key) or "").strip() and str(copy.get(key) or "").strip():
                        row[key] = copy[key]
        return cur

    ut.update_with_activity(TABLE_KEY, _merge, st=st, by=WRITER, via=VIA,
                            row_ids=list(extra) + dropped, flush="sync")
    return len(dropped)


def write_rows(st, computed, *, table_key=TABLE_KEY, key_column="sku", label=TABLE_LABEL, period_keys=None):
    """Upsert computed cells by the key column through `core.module_tables`; owned cells are never touched.
    A stored row absent from `computed` keeps its row and loses its period figures."""
    period_keys = _PERIOD_KEYS if period_keys is None else tuple(period_keys)
    report = module_tables.write_module_rows(st, table_key, computed, key_column=key_column, writer=WRITER, via=VIA,
                                             label=label, clear_keys=period_keys, origin="Amazon", error=TableRefused)
    reason = "No Amazon economics for this row. Sync Amazon and refresh."
    wanted = {rid: {note: reason for note, figures in BLANK_REASONS.items()
                    if set(figures) & set(period_keys) and row.get(note) != reason}
              for rid, row in table_rows(st, table_key).items()
              if str(row.get(key_column) or "").strip() not in computed}
    wanted = {rid: values for rid, values in wanted.items() if values}
    for rid, row in table_rows(st, table_key).items():
        if row.get("history") != "View":
            wanted.setdefault(rid, {})["history"] = "View"
    if wanted:
        import core.user_tables as ut

        def _notes(cur):
            rows = ((cur or {}).get(table_key) or {}).get("rows") or {}
            for rid, values in wanted.items():
                if rid in rows:
                    rows[rid].update(values)
            return cur

        ut.update_with_activity(table_key, _notes, st=st, by=WRITER, via=VIA, row_ids=list(wanted))
    return report


# ---------------------------------------------------------------- settings

def read_settings(st):
    raw = {}
    try:
        raw = st.get(SETTINGS_KEY) or {}
    except Exception:                                                  # noqa: BLE001
        raw = {}
    raw = raw if isinstance(raw, dict) else {}
    period = raw.get("period") or PERIOD_DEFAULT
    try:
        period_bounds(period)
    except ValueError:
        period = PERIOD_DEFAULT
    try:
        thin = clean_thin(raw.get("thin"))
    except ValueError:
        thin = THIN_DEFAULT
    owner = str(raw.get("defaultOwner") or "").strip().lower() or None
    return {**raw, "period": period, "thin": thin, "defaultOwner": owner}


def write_settings(st, **values):
    def _up(cur):
        cur = dict(cur) if isinstance(cur, dict) else {}
        cur.update(values)
        return cur
    st.update(SETTINGS_KEY, _up, flush="sync")


# ---------------------------------------------------------------- default owner (R31)

#: Accounts that act for the platform, never for the business.
SERVICE_ACCOUNTS = ("admin", "automation", "scheduler", "qa-runner", "leadership")


def _accounts(tenant):
    """`[(username, record)]`: the tenant's active accounts, through the one tenant filter."""
    from core import users
    return users._tenant_accounts(tenant)


def _is_service(username, record):
    name = str(username or "").strip().lower()
    return (not name or name.startswith("qa") or name in SERVICE_ACCOUNTS
            or name.endswith("-admin") or bool(record.get("platform_admin")))


def owner_account(tenant=TENANT_ZERO):
    """The tenant's owner account: no record names one, so the earliest active Administrator
    that is a person. A person signs in with an email; earliest is the oldest password stamp."""
    people = [(name, rec) for name, rec in _accounts(tenant)
              if isinstance(rec, dict) and rec.get("role") == "admin" and not _is_service(name, rec)]
    if not people:
        return None
    people.sort(key=lambda item: ("@" not in item[0], not item[1].get("password_changed_at"),
                                  str(item[1].get("password_changed_at") or ""), item[0]))
    return str(people[0][0]).strip().lower()


def account_name(username, tenant=TENANT_ZERO):
    """The display name a `user` cell stores for `username`, or None if no active account."""
    want = str(username or "").strip().lower()
    for name, rec in _accounts(tenant):
        if str(name).strip().lower() == want and isinstance(rec, dict):
            return str(rec.get("name") or name)
    return None


def set_default_owner(st, username, tenant=TENANT_ZERO, by=""):
    """Point new owned items at `username`; refuses an account this tenant does not hold."""
    want = str(username or "").strip().lower()
    if not want or account_name(want, tenant) is None:
        raise ValueError("Choose an active account in this workspace.")
    write_settings(st, defaultOwner=want, defaultOwnerSetBy=by or WRITER)
    return want


def default_owner(st, tenant=TENANT_ZERO):
    """`(username, display name)` new owned items get; resolves and stores it on first use."""
    username = read_settings(st)["defaultOwner"]
    if not username:
        username = owner_account(tenant)
        if username:
            write_settings(st, defaultOwner=username, defaultOwnerSetBy=WRITER)
    return username, (account_name(username, tenant) if username else None)


# ---------------------------------------------------------------- seeded views

def seeded_views(template_key=TEMPLATE_KEY):
    from core import view_templates as vt
    return list((vt.get(template_key) or {}).get("views") or ())


def ensure_views(st, owner, *, table_key=TABLE_KEY, template_key=TEMPLATE_KEY):
    """Write the seeded views once, owned by `owner`, granted to everyone who can open the table.

    A view lives in one personal stratum and reaches others through a `*` view grant, the same
    residency every shared view has. A view a person deleted stays deleted: `viewsSeeded` in the
    settings records what was written."""
    from core import shares
    from core import view_templates as vt
    from core.table_store import TableStore
    done = set(read_settings(st).get("viewsSeeded") or ())
    ops = TableStore(vt.workspace_key(table_key), st)
    owner = str(owner or WRITER).strip().lower()
    made = []
    for view in seeded_views(template_key):

        if view["id"] in done:
            continue
        found = ops.find_view(view["id"])
        holder = found[0] if found else owner
        if not found:
            ops.save_view(owner, dict(view, createdBy=owner), actor=WRITER, origin={"client": VIA})
            made.append(view["id"])
        held = shares.grants("view", view["id"], st=st)
        if not any(e["user"] == shares.EVERYONE for e in held["entries"]):
            shares.set_grants("view", view["id"],
                              held["entries"] + [{"user": shares.EVERYONE, "role": "view"}],
                              owner=held["owner"] or holder, st=st)
        done.add(view["id"])
    added = set(read_settings(st).get("viewColumnsAdded") or ())
    for view in seeded_views(template_key):
        filter_mark = f"{view['id']}:verified-cost-filter"
        if view["id"].endswith("_cogs_missing") and filter_mark not in added:
            found = ops.find_view(view["id"])
            config = dict((found[1].get("config") or {}) if found else {})
            legacy = [{"colId": "odoo_product", "op": "isEmpty"},
                      {"colId": "cogs_per_unit", "op": "isEmpty"}]
            if found and config.get("filters") == legacy and config.get("filterConj") == "or":
                config.update(filters=list(view["config"]["filters"]), filterConj=view["config"]["filterConj"])
                ops.save_view(found[0], dict(found[1], config=config), actor=WRITER, origin={"client": VIA})
            added.add(filter_mark)
        for column in _VIEW_COLUMNS_ADDED:
            mark = f"{view['id']}:{column}"
            if mark in added or column not in view["config"]["visible"]:
                continue
            found = None if view["id"] in made else ops.find_view(view["id"])
            config = dict((found[1].get("config") or {}) if found else {})
            if found and column not in [*(config.get("order") or ()), *(config.get("visible") or ())]:
                before = _column_before(view["config"]["visible"], column)
                config.update({part: _insert_after(config[part], before, column) for part in ("order", "visible")
                           if isinstance(config.get(part), list)})
                ops.save_view(found[0], dict(found[1], config=config), actor=WRITER, origin={"client": VIA})
            added.add(mark)
        for column in _VIEW_COLUMNS_DROPPED:
            mark = f"{view['id']}:-{column}"
            if mark in added or column in view["config"]["visible"]:
                continue
            found = None if view["id"] in made else ops.find_view(view["id"])
            config = dict((found[1].get("config") or {}) if found else {})
            if found and column in (config.get("visible") or ()):
                config["visible"] = [c for c in config["visible"] if c != column]
                ops.save_view(found[0], dict(found[1], config=config), actor=WRITER, origin={"client": VIA})
            added.add(mark)
    write_settings(st, viewsSeeded=sorted(done), viewColumnsAdded=sorted(added))
    return made


#: Columns a seeded view already written gains once; a person who hides one later keeps it hidden.
#: The S85-T125 metric columns follow template order, so each lands after the column before it.
_VIEW_COLUMNS_ADDED = ("picture", "odoo_product", "cost_note", "ads_note", "tacos_note", "stock_note", "returns_note",
                       "cogs_source", "fees", "sponsored_ads", "net_proceeds", "sales_note", "cogs_per_unit",
                       "cogs_total", "odoo_channel_sales", "odoo_channel_profit", "odoo_channel_margin",
                       "odoo_margin_source", "ad_impressions", "ad_clicks", "ad_spend", "ad_sales", "ad_orders",
                       "cvr", "cpc", "roas", "fba_on_hand", "inbound_units", "return_units", "sessions",
                       "unit_session_pct", "buy_box_pct", "listing_note", "units_30d", "net_sales_30d",
                       "ad_spend_30d", "health_note")
#: Columns a seeded view already written loses once; a person who shows one again keeps it.
_VIEW_COLUMNS_DROPPED = ("suggested_product", "suggested_units", "match_rule", "match_state")


def _column_before(columns, column):
    index = list(columns).index(column)
    return columns[index - 1] if index else None


def _insert_after(columns, before, column):
    """`columns` with `column` right after `before`, or appended when `before` is absent."""
    out = [c for c in (columns or ()) if c != column]
    out.insert(out.index(before) + 1 if before in out else len(out), column)
    return out


#: Grain key of each App table.
GRAIN_KEYS = {TABLE_KEY: "sku", ASIN_KEY: "asin", PARENT_KEY: "parent_asin"}
#: Columns every stored View of a table keeps, in this order, right after its grain key.
VIEW_KEEP = {TABLE_KEY: ("projects",), ASIN_KEY: ("projects", "pdp_update"), PARENT_KEY: ("projects",)}
#: Settings member holding `table:owner:view:key` marks, one per pinned key a View was given.
VIEW_PINS_KEY = "viewPinsAdded"


def register_view_keep():
    """Register the kept columns of every App table with the View store."""
    from core import table_store
    for table_key, keys in VIEW_KEEP.items():
        table_store.register_view_keep(table_key, keys, after=GRAIN_KEYS[table_key])


register_view_keep()


def pin_mark(table_key, owner, view_id, key):
    return f"{table_key}:{owner}:{view_id}:{key}"


def pinned_view_config(table_key, owner, view_id, config, fields, marks):
    """`(config, new marks)`: the kept keys, then each unmarked pinned key that is a stored field, added once."""
    from core import table_store
    pins = _pinned_keys(GRAIN_KEYS[table_key])
    config, made = dict(table_store.kept_config(table_key, config)), set()
    if not any(isinstance(config.get(part), list) for part in ("visible", "order")):
        return config, made
    for index, key in enumerate(pins[1:], 1):
        mark = pin_mark(table_key, owner, view_id, key)
        if key not in fields or mark in marks:
            continue
        for part in ("visible", "order"):
            columns = config.get(part)
            if isinstance(columns, list) and key not in columns:
                before = next((pin for pin in reversed(pins[:index]) if pin in columns), None)
                config[part] = _insert_after(columns, before, key) if before else [key, *columns]
        made.add(mark)
    return config, made


def _stored_views(st, table_key):
    """`[(owner, view_id, view, recipient)]` for every personal View and every assigned View of one table."""
    from core import dependents
    from core.table_store import ASSIGNED_KEY
    out = [(owner, view_id, view, None) for owner, view_id, view in dependents.walk_views(st, table_key)]
    assigned = (dependents._table_doc(st, table_key, assignments=True).get(ASSIGNED_KEY) or {})
    for recipient, rows in ((assigned.get("views") or {}) if isinstance(assigned, dict) else {}).items():
        for view_id, row in (rows.items() if isinstance(rows, dict) else ()):
            if isinstance(row, dict) and isinstance(row.get("presentation"), dict):
                out.append((f"{ASSIGNED_KEY}/{recipient}", str(view_id),
                            {"config": row["presentation"]}, str(recipient)))
    return out


def reconcile_views(st, table_keys=None):
    """Give every stored View of the App tables its pinned and kept columns. Returns the Views saved.

    A pinned key is added once per View: a person who hides it later keeps it hidden. A second run
    writes nothing."""
    import core.user_tables as ut
    from core import view_templates as vt
    from core.table_store import TableStore
    marks = set(read_settings(st).get(VIEW_PINS_KEY) or ())
    made, saved = set(), 0
    for table_key in table_keys or GRAIN_KEYS:
        definition = ut.get_definition(table_key, st=st)
        if not isinstance(definition, dict):
            continue
        fields = {f.get("key") for f in definition.get("fields") or () if isinstance(f, dict)}
        ops = TableStore(vt.workspace_key(table_key), st)
        for owner, view_id, view, recipient in _stored_views(st, table_key):
            # save_view refuses these legacy shapes; nothing reads them as Views now.
            if view_id.startswith("sv_") or "permissions" in view or not isinstance(view.get("config"), dict):
                continue
            config, new = pinned_view_config(table_key, owner, view_id, view["config"], fields, marks)
            made |= new
            if config == view["config"]:
                continue
            if recipient is not None:
                ops.save_assigned_presentation(recipient, view_id, config)
            else:
                ops.save_view(owner, dict(view, id=view_id, config=config), actor=WRITER, origin={"client": VIA})
            saved += 1
    if made:
        write_settings(st, **{VIEW_PINS_KEY: sorted(marks | made)})
    return saved


# ---------------------------------------------------------------- refresh

def build_rows(con, period, row_links, thin=THIN_DEFAULT, cost_reader=None, today=None,
               *, history=None, receipts=None, cost_problem=None, typed=None):
    """`(computed cells by SKU, report)` for one period. Every SKU in the mirror is present.
    `typed` (`typed_costs`) fills COGS only for a SKU with no Odoo cost and no Odoo receipt (R43)."""
    bounds = period_bounds(period, today)
    econ = economics_by_sku(con, bounds["start"], bounds["end"])
    names = titles(con)
    codes = {link["code"] for link in row_links.values() if link.get("code")}
    if cost_reader is None:
        costs, problems = mirror_products(con, codes)
    else:
        costs, problems = cost_reader(codes) if codes else ({}, [])
    allocations, usage = {}, []
    if cost_reader is None:
        if receipts is None and cost_problem is None:
            try:
                receipts = receipt_costs(con, [row["id"] for row in costs.values()]) if costs else []
            except SourceUnavailable as exc:
                cost_problem = str(exc)
        if cost_problem:
            problems.append(cost_problem)
        elif costs:
            allocations, usage = fifo_costs(con, bounds["start"], bounds["end"], row_links, costs,
                                            receipts or [], (receipts or []) if history is None else history)
    margins, margin_source = odoo_channel_margins(con, bounds["start"], bounds["end"])
    history_by_product = {}
    for observation in ((receipts or []) if history is None else history):
        history_by_product.setdefault(observation["product_id"], []).append(observation)
    history_texts = {pid: _history_text(observations, pid) for pid, observations in history_by_product.items()}
    computed, linked, typed_used = {}, 0, 0
    for item in econ:
        item = dict(item, title=names.get(item["sku"]))
        link = row_links.get(item["sku"]) or {}
        found = costs.get(link.get("code") or "")
        if found is not None:
            linked += 1
        row = compute_row(item, None if found is None or cost_reader is None else found["cost"],
                          link.get("units_per_sku") or 1, thin)
        if found is not None:
            channel = margins.get(found["id"])
            row.update(odoo_channel_sales=channel["sales"] if channel else None,
                       odoo_channel_profit=channel["profit"] if channel else None,
                       odoo_channel_margin=channel["margin"] if channel else None,
                       odoo_margin_source=channel["source"] if channel else
                           ("No Odoo channel sales" if margin_source == "Confirmed Fisch and Royal sales" else margin_source),
                       cost_history=history_texts.get(found["id"]))
        if cost_reader is None:
            allocation = allocations.get(item["sku"], {})
            used = allocation.get("usage", [])
            units = allocation.get("units", 0.0)
            missing = allocation.get("missing", 0.0)
            row["cost_source"] = ("Receipt cost unavailable" if found else
                                  "Odoo product unavailable" if link.get("code") else "Odoo product not linked")
            if allocation:
                row["cost_receipt"] = ", ".join(dict.fromkeys(part["receipt"]["receipt"] for part in used)) or None
                row["cost_coverage"] = (f"{units - missing:g} of {units:g} Odoo units | FIFO by sale date and SKU | "
                                        f"Prior use: {allocation['prior_source']}")
                if allocation.get("returns"):
                    row["cost_source"] = "Returns need receipt link"
                elif allocation.get("incomplete_prior"):
                    row["cost_source"] = "Incomplete FIFO history"
                elif missing > 1e-8:
                    row["cost_source"] = "Incomplete receipt coverage"
                elif units > 0 and int(_num(item["units"])) > 0:
                    total = sum(part["purchase_used"] + part["landed_used"] for part in used)
                    row = {**row, **compute_row(item, total / int(item["units"]), 1, thin)}
                    sources = list(dict.fromkeys(part["receipt"]["source"] for part in used))
                    row["cost_source"] = ", ".join(sources)
                else:
                    row = {**row, **compute_row(item, 0, 1, thin)}
                    row.update(cogs_per_unit=None, cost_source="No units sold")
        typed_cost = (typed or {}).get(item["sku"])
        receipt_known = found is not None and (cost_reader is not None or found["id"] in history_by_product)
        use_typed = typed_cost is not None and row.get("cogs_total") is None and not receipt_known
        if use_typed:
            typed_used += 1
            row = {**row, **compute_row(item, typed_cost, 1, thin), "cost_source": TYPED_COST_SOURCE}
        if found is None:
            row["odoo_margin_source"] = LINK_NOTE if not link.get("code") else PRODUCT_MISSING_NOTE
        row["cost_note"] = cost_note(row, code=link.get("code"), found=found is not None or use_typed)
        source = COGS_TYPED if use_typed else COGS_RECEIPT if row.get("cogs_total") is not None else None
        computed[item["sku"]] = dict(cells(row, bounds["label"]), cogs_source=source)
    report = {"period": bounds, "thin": thin, "skus": len(computed), "linked": linked,
              "unlinked": len(computed) - linked, "typedCost": typed_used, "costProblems": problems,
              "_costUsage": usage}
    return computed, report


def refusal(checks, month):
    """One plain sentence naming the first failed validate() check, or None if all pass."""
    label = dt.date.fromisoformat(f"{month}-01").strftime("%B %Y")
    covered = (checks[0].get("covered") if checks else None) or {}
    where = f"over {covered['label']}" if covered.get("partial") and covered.get("label") else f"in {label}"
    sentences = (
        lambda c: (f"Not verified: Amazon net proceeds miss settlements by "
                   f"{c.get('gap') or 0:.1%} {where}." if math.isfinite(c.get("gap") or 0)
                   else f"Not verified: Amazon has no settlements in {label} to tie to."),
        lambda c: f"Not verified: the fee check cannot tell a wrong total from a right one in {label}.",
        lambda c: f"Not verified: {c.get('a')} settlement rows in {label} have no readable date.",
        lambda c: f"Not verified: SKU net proceeds do not add up to Amazon's total in {label}.",
        lambda c: "Not verified: the SKU list is incomplete.",
    )
    for index, check in enumerate(checks):
        if not check.get("ok"):
            if index == 0 and check.get("reason"):
                return check["reason"]
            if index < len(sentences):
                return sentences[index](check)
            return f"Not verified: the Amazon figures do not tie in {label}."
    return None


def _and(names):
    return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]


def withheld_parts(checks, month):
    """`{line, components, keys, month}` when only the settlement tie failed and sales or fees tied, else None.

    Each failed component blanks its own figures and every profit figure; the tied figures publish."""
    if not checks or checks[0].get("ok") or not all(c.get("ok") for c in checks[1:]):
        return None
    first = checks[0]
    if "covered" in first and (first.get("covered") or {}).get("start") is None:
        return None
    parts = {p.get("component"): bool(p.get("ok")) for p in first.get("components") or ()}
    if not (parts.get("product sales") or parts.get("order fees")):
        return None
    failed = list(dict.fromkeys([name for name, ok in parts.items() if not ok]
                                + list(first.get("failedComponents") or ())))
    keys = []
    for part, figures in _WITHHELD_BY_PART.items():  # an absent sales or order fee part counts as failed
        if not parts.get(part, part not in ("product sales", "order fees")) or part in failed:
            keys.extend(figures)
    keys = tuple(dict.fromkeys(keys + list(_WITHHELD_PROFIT)))
    label = dt.date.fromisoformat(f"{month}-01").strftime("%B %Y")
    line = (f"Not verified: {_and(failed)} in {label} {'does' if len(failed) == 1 else 'do'} not tie to "
            "Amazon settlements." if failed else refusal(checks, month))
    return {"line": line, "components": failed, "keys": keys, "month": month}


def _withhold(cells_by_key, withheld):
    """Rows with the figures `withheld` names blanked and explained by its line."""
    if not withheld:
        return cells_by_key
    keys = withheld["keys"]
    return {k: _explain(_blank(v, keys), keys, withheld["line"]) for k, v in cells_by_key.items()}


def refusal_line(sentence, covered):
    """The 409 line: the refusal, plus the day the rest settles when the settlement cycle gives one."""
    clear = (covered or {}).get("clear")
    if not sentence or not clear:
        return sentence
    return f"{sentence} The rest settles about {_day_label(dt.date.fromisoformat(clear))}."


def keep_figures(st, *, line, period, month, covered, by="", settling=None):
    """A refused refresh: the stored rows, period and verified range stay; only the refusal note is written.

    Saving the refused period here would label the kept figures with a period they do not cover."""
    stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
    write_settings(st, lastRefusal={"line": line, "period": period, "month": month, "at": stamp,
                                    "by": by or WRITER, "settling": settling})
    settings = read_settings(st)
    return {"tableKey": TABLE_KEY, "kept": True, "refusal": line, "refusedPeriod": period,
            "refusedAt": stamp, "verifiedMonth": month, "verified": None, "verifiedRange": covered,
            "period": period_bounds(settings["period"]), "skus": settings.get("skus"),
            "linked": settings.get("linked"), "settling": settling}


def apply_owned(st, bands, *, today, owner=None, skus=None):
    """Open, reopen and stamp owned items in one store write. Returns the counts."""
    import core.user_tables as ut
    counts = {}

    def _set(cur):
        counts.clear()
        counts.update(opened=0, reopened=0, stamped=0)
        table = cur.get(TABLE_KEY)
        if table is None:
            return cur
        for row in (table.get("rows") or {}).values():
            sku = str(row.get("sku") or "").strip()
            if skus is not None and sku not in skus:
                continue
            before = str(row.get("status") or "").strip()
            changes = owned_changes(row, bands.get(sku), today=today, owner=owner)
            if not changes:
                continue
            for key, value in changes.items():
                if value is None:
                    row.pop(key, None)
                else:
                    row[key] = value
            if changes.get("status") == "Open":
                counts["reopened" if before else "opened"] += 1
            else:
                counts["stamped"] += 1
        return cur

    ut.update_with_activity(TABLE_KEY, _set, st=st, by=WRITER, via=VIA, row_ids=None)
    return dict(counts)


# ---------------------------------------------------------------- metrics, rollups, projects

_FIELD_BY_KEY = {f["key"]: f for f in COMPUTED_FIELDS + ASIN_FIELDS + PARENT_FIELDS + PROJECT_FIELDS}


def _decimals(field):
    return (field.get("format") or {}).get("decimals")


def stored_cell(field, value):
    """A raw value as the stored cell string for its field type; None means blank."""
    if value is None or value == "" or field is None:
        return None if value in (None, "") else str(value)
    ftype = field.get("type")
    if ftype == "chart":
        return value if isinstance(value, str) else json.dumps(value, separators=(",", ":"))
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return str(value)
    if not math.isfinite(float(value)):
        return None
    if ftype == "pct":
        return f"{value * 100:.2f}"
    if ftype == "int":
        places = _decimals(field)
        return f"{float(value):.{places}f}" if places else str(int(round(value)))
    if ftype == "currency" or isinstance(value, float):
        return f"{float(value):.2f}"
    return str(value)


def raw_value(field, cell):
    """The raw value a stored cell holds: numbers as numbers, pct as a fraction."""
    if cell is None or cell == "":
        return None
    ftype = (field or {}).get("type")
    if ftype == "chart":
        try:
            return json.loads(cell) if isinstance(cell, str) else cell
        except ValueError:
            return None
    if ftype in ("pct", "int", "currency"):
        try:
            number = float(cell)
        except (TypeError, ValueError):
            return None
        if not math.isfinite(number):
            return None
        if ftype == "pct":
            return number / 100.0
        if ftype == "int" and not _decimals(field or {}) and number.is_integer():
            return int(number)
        return number
    return cell


def _raw_row(cells_by_key):
    return {key: raw_value(_FIELD_BY_KEY.get(key), value) for key, value in cells_by_key.items()}


def _metric_problem_types():
    own = getattr(M, "SourceUnavailable", None)
    return (SourceUnavailable,) + ((own,) if isinstance(own, type) and issubclass(own, Exception) else ())


def merge_metrics(computed, metrics):
    """SKU cells with the metric and score cells added; `metrics` holds raw values by SKU."""
    out = {}
    for sku, values in computed.items():
        raw = _raw_row(values)
        raw.update({k: v for k, v in (metrics.get(sku) or {}).items() if k in METRIC_KEYS})
        if not raw.get("asin") and (metrics.get(sku) or {}).get("asin"):
            raw["asin"] = metrics[sku]["asin"]
        raw.update(M.score_row(raw))
        raw.update(M.blank_notes(raw))
        merged = dict(values)
        for key in METRIC_KEYS + ("asin",):
            if key in raw:
                merged[key] = stored_cell(_FIELD_BY_KEY.get(key), raw[key])
        merged.setdefault("health_note", None)
        out[sku] = merged
    return out


def _blank(cells_by_key, keys, period=None):
    out = {**cells_by_key, **{k: None for k in keys if k in cells_by_key or k in _FIELD_BY_KEY}}
    if period is not None:
        out["period"] = period
    return out


def _explain(cells_by_key, keys, reason):
    """Cells with every reason column whose figures `keys` blanked set to `reason`."""
    blanked = set(keys)
    return {**cells_by_key, **{note: reason for note, figures in BLANK_REASONS.items()
                               if note in cells_by_key and blanked & set(figures)}}


def _grain_cost_note(flat, children):
    """Why a rollup row's COGS, profit or margin is blank, from its SKU rows."""
    if all(flat.get(k) is not None for k in ("cogs_total", "net_profit", "margin")):
        return ""
    costless = [c for c in children if c.get("net_profit") is None]
    if any(c.get("cost_note") == LINK_NOTE for c in costless):
        return GRAIN_LINK_NOTE
    if costless or flat.get("net_profit") is None:
        return GRAIN_COST_NOTE
    return M.NO_NET_SALES_NOTE


def _flatten(item):
    flat = {}
    for key, value in (item or {}).items():
        if key in ("sums", "ratios") and isinstance(value, dict):
            flat.update(value)
        else:
            flat[key] = value
    return flat


def grain_rows(rows, key, *, thin=THIN_DEFAULT, period_label="", fields=()):
    """`{asin or parent: cells}` from `M.rollup`, which sums first and recomputes every ratio.
    Band follows the rollup's margin and the period cell names the period."""
    keys = [f["key"] for f in fields]
    by_sku = {str(r.get("sku")): r for r in rows if r.get("sku") is not None}
    out = {}
    for item in M.rollup(rows, key=key):
        flat = _flatten(item)
        value = str(flat.get(key) or flat.get("key") or "").strip()
        if not value:
            continue
        flat[key] = value
        flat["band"] = band_for(flat.get("net_profit"), flat.get("margin"), thin)
        children = [by_sku[s] for s in str(flat.get("skus") or "").split(", ") if s in by_sku]
        flat["cost_note"] = _grain_cost_note(flat, children)
        flat["period"] = period_label
        out[value] = {k: stored_cell(_FIELD_BY_KEY.get(k), flat.get(k)) for k in keys
                      if k not in ("projects", "projects_label") + PDP_CELL_KEYS + _ASIN_SOURCE_KEYS}
    return out


def sku_pictures(computed, refs):
    """SKU cells with `picture` set to the stored ref of the row's ASIN, None when it has none."""
    return {sku: dict(values, picture=refs.get(str(values.get("asin") or "").strip()))
            for sku, values in computed.items()}


def grain_pictures(by_grain, refs):
    """Set `picture` on every ASIN and parent cell after the rollup; returns the counts.

    A parent uses its own stored picture, else the picture of its child ASIN with the most units
    sold in the period, ties by ASIN ascending. No picture leaves the cell None."""
    asins = by_grain.get("asin") or {}
    best = {}
    for asin, values in sorted(asins.items()):
        values["picture"] = refs.get(asin)
        parent = str(values.get("parent_asin") or "").strip()
        units = _num(values.get("units_sold"))
        if parent and values["picture"] and (parent not in best or units > best[parent][0]):
            best[parent] = (units, values["picture"])
    own = child = 0
    for parent, values in (by_grain.get("parent_asin") or {}).items():
        values["picture"] = refs.get(parent) or (best.get(parent) or (0, None))[1]
        own += bool(refs.get(parent))
        child += bool(values["picture"]) and not refs.get(parent)
    return {"asin": sum(1 for values in asins.values() if values["picture"]),
            "parent": own + child, "parentOwn": own, "parentChild": child}


def rollup_checks(computed, by_grain):
    """Each rollup table's units sold equal the SKU units sold, and it holds every distinct key."""
    checks = []
    for key, label, cells_by_key in (("asin", "ASIN", by_grain.get("asin") or {}),
                                     ("parent_asin", "parent ASIN", by_grain.get("parent_asin") or {})):
        grouped = [values for values in computed.values() if str(values.get(key) or "").strip()]
        skus = sum(int(_num(values.get("units_sold"))) for values in grouped)
        grains = sum(int(_num(values.get("units_sold"))) for values in cells_by_key.values())
        distinct = len({str(values.get(key)).strip() for values in grouped})
        checks.append({"check": f"amazon_profit: {label} table units sold equal the SKU table units sold",
                       "ok": skus == grains, "a": grains, "b": skus, "gap": abs(grains - skus)})
        checks.append({"check": f"amazon_profit: {label} table holds every distinct {label}, no cap",
                       "ok": len(cells_by_key) == distinct, "a": len(cells_by_key), "b": distinct,
                       "gap": abs(len(cells_by_key) - distinct)})
    return checks


#: Grain figure families tied per row to an independent SQL aggregate of the SKUs' Amazon rows (rule 8):
#: (figures, independent source, figure words, what a failed tie withholds on that grain table).
_TIE_FAMILIES = (
    (("units_sold", "net_sales", "fees", "sponsored_ads", "net_proceeds"), "Amazon economics", "sales figures",
     _UNVERIFIED_KEYS + ("return_rate", "unit_session_pct", "listing_health")),
    (("ad_spend",), "Amazon ad charges", "ad spend figures",
     ("ad_spend", "cpc", "acos", "roas", "tacos", "ads_health", "score", "priority", "ad_spend_30d")),
    (("ad_impressions", "ad_clicks", "ad_sales", "ad_orders"), "the Amazon Ads reports", "ads figures",
     M.ADS_FIGURES + ("ads_health", "score", "priority")),
    (("fba_on_hand", "inbound_units"), "Amazon inventory planning", "stock figures",
     ("fba_on_hand", "inbound_units", "days_of_cover", "stock_health", "score", "priority")),
    (("return_units",), "the Amazon returns reports", "returned units",
     ("return_units", "return_rate", "listing_health", "score", "priority")),
    (("sessions",), "the Amazon traffic report", "sessions",
     ("sessions", "unit_session_pct", "buy_box_pct", "listing_health", "score", "priority")),
    (("cogs_total", "net_profit"), "the SKU costs", "cost figures",
     ("cogs_total", "net_profit", "margin", "band", "profit_health", "score", "priority")),
)
_COUNT_FIGURES = frozenset(("units_sold", "ad_impressions", "ad_clicks", "ad_orders", "fba_on_hand",
                            "inbound_units", "return_units", "sessions"))


def _cent(value):
    return None if value is None else float(f"{float(value):.2f}")


def _sub_cent(value):
    """A raw sum with a part below one cent: two float sums of it may round to cents one cent apart."""
    return value is not None and abs(float(value) * 100 - round(float(value) * 100)) > 1e-6


def _sku_figures(con, start, end, skus):
    """`{figure: {sku: value or None}}` read straight from the mirror, rounded as a SKU cell stores it.
    A family whose source table is absent maps to None."""
    from modules import ranking_diagnostic, restock_planner
    out = {}
    cols = _require(con, ECONOMICS, _ECONOMICS_REQUIRED)
    ads = " + ".join(f'COALESCE(TRY_CAST("{c}" AS DOUBLE), 0)' for c in ads_columns(cols)) or "0"
    rows = con.execute(
        "SELECT msku, SUM(sales_net_units_sold), SUM(sales_net_product_sales_amount), SUM(fees_total_amount), "
        f"SUM({ads}) FROM {ECONOMICS} WHERE left(CAST(start_date AS VARCHAR), 10) BETWEEN ? AND ? "
        "AND msku IN (SELECT unnest(?)) GROUP BY msku", [start, end, skus]).fetchall()
    econ = {r[0]: [_num(v) for v in r[1:]] for r in rows}
    zero = [0.0, 0.0, 0.0, 0.0]
    out["units_sold"] = {s: int(econ.get(s, zero)[0]) for s in skus}
    out["net_sales"] = {s: _cent(econ.get(s, zero)[1]) for s in skus}
    out["fees"] = {s: _cent(econ.get(s, zero)[2]) for s in skus}
    out["sponsored_ads"] = {s: _cent(econ.get(s, zero)[3]) for s in skus}
    out["net_proceeds"] = {s: _cent(e[1] - e[2] - e[3]) for s, e in ((s, econ.get(s, zero)) for s in skus)}
    loose = {figure: {s for s in econ if _sub_cent(econ[s][index])}
             for index, figure in ((1, "net_sales"), (2, "fees"), (3, "sponsored_ads"))}
    loose["net_proceeds"] = {s for s in econ if _sub_cent(econ[s][1] - econ[s][2] - econ[s][3])}
    loose["ad_spend"] = loose["sponsored_ads"]
    union = M._ads_parts(con)
    adrows = {} if union is None else {r[0]: r[1:] for r in con.execute(
        f"SELECT sku, SUM(impressions), SUM(clicks), SUM(cost), SUM(sales), SUM(orders) FROM ({union}) a "
        "WHERE day BETWEEN CAST(? AS DATE) AND CAST(? AS DATE) AND sku IN (SELECT unnest(?)) GROUP BY sku",
        [start, end, skus]).fetchall()}
    for index, figure in ((0, "ad_impressions"), (1, "ad_clicks"), (3, "ad_sales"), (4, "ad_orders")):
        out[figure] = None if union is None else {
            s: (M._int(adrows[s][index]) if figure in _COUNT_FIGURES else _cent(M._f(adrows[s][index])))
            if s in adrows else None for s in skus}
    loose["ad_sales"] = {s for s in adrows if _sub_cent(M._f(adrows[s][3]))}
    if ads_columns(cols):
        out["ad_spend"] = {s: _cent(econ.get(s, zero)[3]) for s in skus}
    else:
        out["ad_spend"] = None if union is None else {s: _cent(M._f(adrows[s][2])) if s in adrows else None
                                                       for s in skus}
        loose["ad_spend"] = {s for s in adrows if _sub_cent(M._f(adrows[s][2]))}
    out["_loose"] = loose
    plan_cols = _columns(con, restock_planner.PLANNING)
    if {"sku", "available"} <= plan_cols:
        inbound = 'TRY_CAST("inbound_quantity" AS DOUBLE)' if "inbound_quantity" in plan_cols else "NULL"
        fnsku = "max(NULLIF(TRIM(CAST(\"fnsku\" AS VARCHAR)), ''))" if "fnsku" in plan_cols else "NULL"
        plan = {r[0]: r[1:] for r in con.execute(
            f'SELECT TRIM(CAST("sku" AS VARCHAR)), {fnsku}, SUM(TRY_CAST("available" AS DOUBLE)), SUM({inbound}) '
            f'FROM {restock_planner.PLANNING} WHERE {restock_planner._newest(plan_cols, restock_planner.PLANNING)} '
            'AND TRIM(CAST("sku" AS VARCHAR)) IN (SELECT unnest(?)) GROUP BY 1', [skus]).fetchall()}
        out["_pool"] = {s: (plan[s][0] if s in plan else None) or s for s in skus}
        out["fba_on_hand"] = {s: M._int(plan[s][1]) if s in plan else None for s in skus}
        out["inbound_units"] = {s: M._int(plan[s][2]) if s in plan else None for s in skus}
    else:
        out["fba_on_hand"] = out["inbound_units"] = None
    returns = M._returns_parts(con)
    if returns is None:
        out["return_units"] = None
    else:
        got = dict(con.execute(f"SELECT sku, SUM(units) FROM ({returns}) r WHERE day BETWEEN CAST(? AS DATE) "
                               "AND CAST(? AS DATE) AND sku IN (SELECT unnest(?)) GROUP BY sku",
                               [start, end, skus]).fetchall())
        out["return_units"] = {s: M._int(got.get(s) or 0) for s in skus}
    pricing = ranking_diagnostic._pricing(con)
    out["_traffic"] = None if pricing is None else {a: M._int((v or {}).get("sessions")) for a, v in pricing.items()}
    return out


def grain_ties(con, start, end, computed, by_grain):
    """Each ASIN and parent ASIN figure that holds a number ties per row to the sum of its SKUs' Amazon
    rows, read again from the mirror in SQL (rule 8). A blank cell is withheld and carries its reason."""
    skus = sorted(str(s) for s in computed)
    source = _sku_figures(con, start, end, skus) if skus else {}
    checks = []
    for grain, label in (("asin", "ASIN"), ("parent_asin", "Parent ASIN")):
        rows = by_grain.get(grain) or {}
        members = {}
        for sku in skus:
            value = str((computed[sku] or {}).get(grain) or "").strip()
            if value:
                members.setdefault(value, []).append(sku)
        for figures, words, what, _withheld in _TIE_FAMILIES:
            for figure in figures:
                compared = withheld = 0
                mismatched, worst = [], 0.0
                for key, cells_by_key in rows.items():
                    got = M._f(cells_by_key.get(figure))
                    if got is None:
                        withheld += 1
                        continue
                    compared += 1
                    want = _tie_expected(figure, members.get(key, []), computed, source)
                    gap = math.inf if want is None else abs(got - want)
                    # Half a cent for the row's own rounding, plus one cent per member SKU whose raw sum
                    # has a part below a cent: two float sums of it may round one cent apart.
                    loose = (source.get("_loose") or {}).get(figure) or set()
                    tolerance = (0.01 if figure in _COUNT_FIGURES else
                                 0.0051 + 0.0101 * sum(1 for sku in members.get(key, []) if sku in loose))
                    if not gap <= tolerance:
                        mismatched.append(key)
                    worst = max(worst, gap)
                ok = not mismatched
                checks.append({"check": f"amazon_profit: {label} {_FIELD_BY_KEY[figure]['label'].lower()} tie to "
                                        f"{words} per row", "ok": ok, "grain": grain, "figure": figure,
                               "compared": compared, "withheld": withheld, "mismatched": len(mismatched),
                               "keys": mismatched[:5], "rowsFailed": mismatched,
                               "gap": None if not compared else round(worst, 4),
                               "reason": None if ok else f"Not verified: {label} {what} do not tie to {words}."})
    return checks


def _tie_expected(figure, members, computed, source):
    """The independent value of one grain figure from its member SKUs, or None when no source holds it."""
    if figure in ("cogs_total", "net_profit"):
        values = [M._f((computed[s] or {}).get(figure)) for s in members]
        active = [s for s in members if M._active(_raw_row(computed[s] or {}))]
        if any(M._f((computed[s] or {}).get(figure)) is None for s in active):
            return None
        found = [v for v in values if v is not None]
        return _cent(sum(found)) if found else None
    if figure == "sessions":
        traffic = source.get("_traffic")
        if traffic is None:
            return None
        asins = dict.fromkeys(str((computed[s] or {}).get("asin") or "").strip() for s in members)
        found = [traffic.get(a) for a in asins if a and traffic.get(a) is not None]
        return float(sum(found)) if found else None
    per_sku = source.get(figure)
    if per_sku is None:
        return None
    if figure in ("fba_on_hand", "inbound_units"):
        pools = {}
        for sku in sorted(members):
            pools.setdefault(source["_pool"].get(sku) or sku, per_sku.get(sku))
        found = [v for v in pools.values() if v is not None]
    else:
        found = [per_sku.get(s) for s in members if per_sku.get(s) is not None]
    return float(sum(found)) if found else None


def _withhold_untied(by_grain, checks):
    """On each row whose tie failed, blank what that tie withholds and write the failed sentence as the reason."""
    withheld = {figure: keys for figures, _w, _what, keys in _TIE_FAMILIES for figure in figures}
    for check in checks:
        if check.get("ok") or check.get("grain") not in by_grain:
            continue
        keys, cells = withheld[check["figure"]], by_grain[check["grain"]]
        for row in check.get("rowsFailed") or ():
            if row in cells:
                cells[row] = _explain(_blank(cells[row], keys), keys, check["reason"])
    return by_grain


def _grain_period_keys(fields, key_column):
    return tuple(f["key"] for f in fields
                 if f["key"] not in (key_column, "picture", "parent_asin", "title", "projects", "projects_label", "history")
                 + COMPETITOR_KEYS + PDP_CELL_KEYS + _ASIN_SOURCE_KEYS)


def _listing_dates(con):
    """Read the newest Amazon lastUpdatedDate per ASIN from raw listing summaries."""
    if "summaries" not in _columns(con, "amzn_listing_items"):
        return {}
    rows = con.execute("""SELECT json_extract_string(s.value, '$.asin'),
        CAST(MAX(TRY_CAST(json_extract_string(s.value, '$.lastUpdatedDate') AS TIMESTAMPTZ))
             AT TIME ZONE 'UTC' AS DATE)
        FROM amzn_listing_items l, json_each(TRY_CAST(l.summaries AS JSON)) s GROUP BY 1""").fetchall()
    return {asin: date.isoformat() for asin, date in rows if asin and date is not None}


def _exposure_detail(exposure):
    """Format the recorded exposure multiple with the prototype's one-decimal rounding."""
    if not exposure or exposure["multiple"] is None:
        return None
    multiple = Decimal.from_float(float(exposure["multiple"])).quantize(Decimal("0.1"), rounding=ROUND_HALF_UP)
    return f"{multiple}x {exposure['base']} share"


def _asin_signal_cells(signal, history):
    """Store scalar cells and raw monthly bars for every reported historical month."""
    out = {key: stored_cell(_FIELD_BY_KEY[key], signal[key]) for key in ("trend_score", "funnel_score")}
    out.update({key + "_reason": value for key, value in signal["reasons"].items()
                if key in ("trend_score", "funnel_score", "exposure")})
    exposure = signal["exposure"]
    out["exposure"] = EXPOSURES[exposure["kind"]] if exposure else None
    out["exposure_label"] = _exposure_detail(exposure)
    for kind, key, _label, _now_type in SEARCH_TRENDS:
        trend = signal["trends"][kind]
        points = {point["month"]: point for point in trend["series"]}
        series = [points[month] for month in history]
        latest = series[-1] if series else {"value": None, "reason": signal["note"] or "No search report"}
        now = latest["value"] if kind == "search" else signal[kind]
        out.update({key: None if trend["change"] is None else str(trend["change"] * 100),
                    key + "_series": json.dumps(series, separators=(",", ":")),
                    key + "_now": (stored_cell(_FIELD_BY_KEY[key + "_now"], now) if kind == "search"
                                   else None if now is None else str(now * 100)),
                    key + "_reason": trend["reason"],
                    key + "_now_reason": (signal["note"] or latest["reason"] if kind == "search"
                                          else signal["reasons"][kind])})
    return out


def paint_asin_signals(st, con, *, today):
    """Refresh source signals and Amazon's date for every stored ASIN, independent of the profit period."""
    from modules import amazon_search_signals as signals
    asins = [str(row["asin"]).strip() for row in table_rows(st, ASIN_KEY).values() if row.get("asin")]
    result = signals.signals(con, asins, today=today)
    dates = _listing_dates(con)
    parts = _part_dates.cells(st, asins)
    computed = {asin: dict(_asin_signal_cells(signal, result["history"]), **parts[asin], pdp_last_updated=dates.get(asin),
                           pdp_last_updated_reason=None if asin in dates else "No listing lastUpdatedDate reported")
                for asin, signal in result["asins"].items()}
    return write_rows(st, computed, table_key=ASIN_KEY, key_column="asin", label=ASIN_LABEL, period_keys=())


def paint_asin_part_dates(st):
    """Refresh recorded part dates without profit validation, search reports or Odoo matching."""
    asins = [str(row['asin']).strip() for row in table_rows(st, ASIN_KEY).values() if row.get('asin')]
    if not asins:
        return {'rows': 0}
    return write_rows(st, _part_dates.cells(st, asins), table_key=ASIN_KEY,
                      key_column='asin', label=ASIN_LABEL, period_keys=())


def asin_signal_checks(st, con, *, today=None):
    """Tie stored signal cells to the signal reader's independently validated raw monthly inputs."""
    from modules import amazon_search_signals as signals
    rows = {str(row["asin"]).strip(): row for row in table_rows(st, ASIN_KEY).values() if row.get("asin")}
    result = signals.signals(con, rows, today=today)
    verified = signals.validate(con, result, today=today)
    differences = sum(any(rows[asin].get(key) != value for key, value in _asin_signal_cells(signal, result["history"]).items())
                      for asin, signal in result["asins"].items())
    return [{"check": "amazon_profit: stored ASIN search signals tie to raw monthly reports",
             "ok": verified["ok"] and not differences, "rows": len(rows), "differences": differences,
             "reason": verified["reason"]}]


def listing_date_checks(st, con):
    """Independently tie stored PDP dates to the newest raw summary timestamp per ASIN."""
    newest = {}
    available = "summaries" in _columns(con, "amzn_listing_items")
    if available:
        cursor = con.execute("SELECT summaries FROM amzn_listing_items")
        for batch in iter(lambda: cursor.fetchmany(2048), []):
            for (raw,) in batch:
                try:
                    summaries = json.loads(raw) if isinstance(raw, str) else raw
                except (TypeError, ValueError):
                    continue
                for summary in summaries if isinstance(summaries, list) else ():
                    if not isinstance(summary, dict) or not summary.get("asin"):
                        continue
                    try:
                        stamp = dt.datetime.fromisoformat(str(summary.get("lastUpdatedDate")).replace("Z", "+00:00"))
                    except ValueError:
                        continue
                    stamp = stamp.replace(tzinfo=stamp.tzinfo or dt.timezone.utc).astimezone(dt.timezone.utc)
                    asin = summary["asin"]
                    if asin not in newest or stamp > newest[asin]:
                        newest[asin] = stamp
    rows = list(table_rows(st, ASIN_KEY).values())
    differences = sum(row.get("pdp_last_updated") != (newest[row["asin"]].date().isoformat()
                      if row.get("asin") in newest else None) for row in rows)
    return [{"check": "amazon_profit: PDP last updated ties to newest listing lastUpdatedDate per ASIN",
             "ok": available and not differences, "rows": len(rows), "differences": differences,
             "reason": None if available else "Listing summaries are unavailable"}]


def _date(value):
    try:
        return dt.date.fromisoformat(str(value or "").strip()[:10])
    except ValueError:
        return None


def project_health(row, today):
    """Done, Overdue, Due this week or On track, from status and the deadline."""
    if str(row.get("status") or "").strip() == "Done":
        return "Done"
    deadline = _date(row.get("deadline_on"))
    if deadline is None:
        return "On track"
    if deadline < today:
        return "Overdue"
    return "Due this week" if (deadline - today).days <= DUE_SOON_DAYS else "On track"


def _figure(result, metric):
    found = next((f for f in result.get("figures") or () if f.get("id") == metric), None) or {}
    return (found.get("current") or {}).get("value"), (found.get("comparison") or {}).get("value"), found


#: `impact_state` reaches a screen, so a results token reads as words. Unknown tokens pass through.
IMPACT_STATE_WORDS = {
    "missing_grain_or_key": "Needs a grain and a key",
    "not_verified": "Not verified: the source totals did not tie",
    "unavailable": "Source unavailable. Sync Amazon.",
    "waiting_for_completion": "Completes first",
    "waiting_for_completed_day": "Waits for the first full day after completion",
    "no_prior_data": "No sales one year earlier to compare against",
    "partial_data": "Only part of the window has data",
}


def project_cells(rid, row, con, today):
    """Computed cells for one project; impact only for a Done project with a completion date."""
    from modules import sku_action_results as SR
    out = {k: None for k in PROJECT_COMPUTED_KEYS}
    out["health"] = project_health(row, today)
    completed = str(row.get("completed_on") or "").strip()[:10]
    if str(row.get("status") or "").strip() != "Done" or not completed:
        return out
    grain, key = M.grain_key(row.get("grain")), str(row.get("key") or "").strip()
    if not grain or not key:
        out["impact_state"] = IMPACT_STATE_WORDS["missing_grain_or_key"]
        return out
    action = {"id": str(rid), "grain": grain, "key": key, "status": "done", "completed_on": completed}
    try:
        result = SR.results(con, action, today=today)
    except SR.ValidationFailed:
        out["impact_state"] = IMPACT_STATE_WORDS["not_verified"]
        return out
    except (SR.SourceUnavailable, ValueError):
        out["impact_state"] = IMPACT_STATE_WORDS["unavailable"]
        return out
    except Exception as exc:                                           # noqa: BLE001
        # One project that cannot be measured must not stop the refresh of every table.
        _log(f"project {rid}: impact unavailable ({type(exc).__name__}: {exc})")
        out["impact_state"] = IMPACT_STATE_WORDS["unavailable"]
        return out

    sales_now, sales_prior, sales = _figure(result, "sales")
    units_now, units_prior, _units = _figure(result, "units")
    roas_now, roas_prior, _roas = _figure(result, "roas")
    raw = {"net_sales_since": sales_now, "net_sales_prior": sales_prior, "units_since": units_now,
           "units_prior": units_prior, "roas_since": roas_now, "roas_prior": roas_prior,
           "impact": None if sales_now is None or sales_prior is None else sales_now - sales_prior,
           "impact_units": None if units_now is None or units_prior is None else units_now - units_prior}
    out.update({k: stored_cell(_FIELD_BY_KEY[k], v) for k, v in raw.items()})
    if out["impact"] is None:
        state = result.get("state") or "unavailable"
        if state == "ready":
            state = (sales.get("comparison") or {}).get("status") or (sales.get("current") or {}).get("status") \
                or "unavailable"
        out["impact_state"] = state
    out["impact_state"] = IMPACT_STATE_WORDS.get(out["impact_state"], out["impact_state"])
    return out


def migrate_projects(st):
    """Copy each legacy project row once into the projects store."""
    from core import amazon_projects
    rows = table_rows(st, PROJECTS_KEY)
    return {"rows": len(rows), "copied": amazon_projects.move_rows(st, rows)}


def paint_project_cells(st, con):
    """Repaint project progress after refresh adds rows or updates their lineage."""
    from core import amazon_projects as AP
    import core.user_tables as ut
    tables = ((TABLE_KEY, ("sku", "asin", "parent_asin")), (ASIN_KEY, ("asin", "parent_asin")),
              (PARENT_KEY, ("parent_asin",)))
    source = {grains[0]: table_rows(st, key) for key, grains in tables}
    lineage = M.lineage_rows(con, source)
    planned = []
    for key, grains in tables:
        rows = source[grains[0]]
        chains = {rid: [AP.target(g, str(row[g]).strip()) for g in grains if str(row.get(g) or "").strip()]
                  for rid, row in lineage[grains[0]].items()}
        planned.append((key, rows, chains))
    pairs = sorted({pair for _key, _rows, chains in planned for chain in chains.values() for pair in chain})
    found = AP.projects_for(st, pairs) if pairs else {}
    counts = {}
    for key, rows, chains in planned:
        wanted = {}
        for rid, chain in chains.items():
            records = {p["id"]: p for pair in chain for p in found.get(pair, ())}
            counted = AP.summary(records.values())
            values = {"projects": stored_cell({"type": "pct"}, counted["average"] / 100)
                       if counted["total"] else None,
                      "projects_label": f"{counted['completed']} of {counted['total']} completed"
                       if counted["total"] else None}
            if any(rows[rid].get(k) != value for k, value in values.items()):
                wanted[rid] = values
        if not wanted:
            continue

        def _set(cur, key=key, wanted=wanted):
            saved = ((cur or {}).get(key) or {}).get("rows") or {}
            for rid, values in wanted.items():
                if rid in saved:
                    _apply_cells(saved[rid], values)
            return cur

        ut.update_with_activity(key, _set, st=st, by=WRITER, via=VIA, row_ids=list(wanted))
        counts[key] = len(wanted)
    return counts


def _evaluate_project_filter_tasks(st, *, today, by):
    """Evaluate saved task filters with their authors' permissions after project publication."""
    from importlib import import_module
    try:
        tasks = import_module("core.amazon_project_tasks")
        filters = import_module("modules.amazon_project_filters")
    except ModuleNotFoundError as exc:
        if exc.name not in ("core.amazon_project_tasks", "modules.amazon_project_filters"):
            raise
        _log(f"Project filter tasks need {exc.name}. Combine prerequisite: merge lane D's task evaluator and matcher.")
        return None
    return tasks.evaluate_filter_tasks(st, filters.matching_keys, today=today, by=by)


def update_projects(st, con, *, today, computed, period, period_label, filter_task_evaluator=None):
    """Publish independently verified project period totals and Impact."""
    from core import amazon_projects as AP
    from modules import sku_action_results as SR
    keys = ("net_sales", "net_profit", "units_sold")
    supplied = {}
    for sku, row in computed.items():
        stored = cells({key: row.get(key) for key in keys}, period_label)
        supplied[sku] = dict(row, **{key: stored[key] for key in keys})

    def impact_reader(action, *, today):
        try:
            return SR.results(con, action, today=today)
        except SR.ValidationFailed:
            return {"state": "not_verified"}
        except (SR.SourceUnavailable, ValueError):
            return {"state": "unavailable"}

    result = AP.update_projects(st, supplied, period=period, period_label=period_label,
                                today=today, impact_reader=impact_reader,
                                impact_state_words=IMPACT_STATE_WORDS)
    evaluator = _evaluate_project_filter_tasks if filter_task_evaluator is None else filter_task_evaluator
    evaluator(st, today=today, by=WRITER)
    return result


def write_competitor_cells(st, plan):
    """Write only the quote-owned cells and rows in a validated plan."""
    import core.user_tables as ut
    for grain, table_key in (("sku", TABLE_KEY), ("asin", ASIN_KEY), ("parent_asin", PARENT_KEY)):
        wanted = plan.get(grain) or {}
        if not wanted:
            continue

        def _set(cur, table_key=table_key, wanted=wanted):
            rows = ((cur or {}).get(table_key) or {}).get("rows") or {}
            for rid, values in wanted.items():
                if rid in rows:
                    _apply_cells(rows[rid], values)
            return cur

        ut.update_with_activity(table_key, _set, st=st, by=WRITER, via=VIA, row_ids=list(wanted))


def on_quotes(tenant_key, changed_asins):
    """Validate and repaint the competitor cells affected by published quotes."""
    from harness import amazon_store
    try:
        st = amazon_store._runtime_for(tenant_key)
        if st is None or not changed_asins:
            return {"state": "skipped"}
        tables = {"sku": table_rows(st, TABLE_KEY), "asin": table_rows(st, ASIN_KEY),
                  "parent_asin": table_rows(st, PARENT_KEY)}
        from harness import runtime as R
        con = R.mirror_cursor(st, require_ready=False)
        try:
            lineage = M.lineage_rows(con, tables, children=True)
        finally:
            con.close()
        plan = _rivals.cells(st, lineage, changed_asins)
        # A moved child must also clear its former parent's persisted rollup.
        hit = _rivals.affected(st, changed_asins)
        old = _rivals.family(tables["asin"])
        stale = {rid for rid, row in tables["parent_asin"].items()
                 if hit.intersection(old.get(_rivals._maybe_asin(row.get("parent_asin")), ()))} - set(plan["parent_asin"])
        if stale:
            full = _rivals.cells(st, lineage)
            plan["parent_asin"].update({rid: full["parent_asin"][rid] for rid in stale})
        plan["asin"] = {rid: values for rid, values in plan["asin"].items() if rid in tables["asin"]}
        checks = _rivals.validate(st, lineage, plan)
        failed = [c for c in checks if not c.get("ok")]
        if failed:
            _log("competitor cells not verified: " + ", ".join(str(c.get("check")) for c in failed))
            return {"state": "not_verified"}
        write_competitor_cells(st, plan)
        return {grain: len(rows) for grain, rows in plan.items()}
    except Exception as exc:
        _log(f"competitor cells unavailable ({type(exc).__name__})")
        return {"state": "failed"}


def refresh(st, con, *, period=None, thin=None, by="", cost_reader=None, today=None,
            tenant=TENANT_ZERO, validator=None):
    """Recompute every SKU for the period and store it; owned cells stay. Returns the report.

    It runs validate() first for `verification_month`, stepped back by `settled_month` while it settles.
    A failed settlement component publishes the tied figures and withholds the rest (`withheld_parts`).
    Any other failed tie writes no rows and no period (`keep_figures`): the report carries `refusal`."""
    settings = read_settings(st)
    period = str(period or settings["period"]).strip().lower()
    period_bounds(period, today)
    thin = settings["thin"] if thin is None else clean_thin(thin)
    day = today or _today()
    month, settling = verification_month(period, day), None
    try:
        month, settling = settled_month(con, month, economics_currency(con))
    except SourceUnavailable:
        pass  # validate() names the missing source
    checks = (validator or (lambda c, m: validate(month=m, con=c)))(con, month)
    sentence = refusal(checks, month)
    covered = next((c["covered"] for c in checks if isinstance(c.get("covered"), dict)), None)
    partial = withheld_parts(checks, month)
    if sentence and partial is None:  # the settlement check runs before every write
        with _LOCK:
            return keep_figures(st, line=refusal_line(sentence, covered), period=period, month=month,
                                covered=covered, by=by, settling=settling)
    verified = covered.get("sentence") if covered else None
    with _LOCK:
        ensure_table(st, by)
        merged = merge_duplicates(st)
        decisions = apply_decisions(st, by=by or WRITER)
        owner, owner_label = default_owner(st, tenant)
        for spec in table_specs():
            ensure_views(st, owner or by, table_key=spec["key"], template_key=spec["template"])
        reconcile_views(st)
        row_links = links(table_rows(st))
        receipts, history, cost_problem = None, [], None
        if cost_reader is None:
            history = read_cost_history(st)
            products, _problems = mirror_products(con, {link["code"] for link in row_links.values() if link["code"]})
            if products:
                try:
                    receipts = receipt_costs(con, [row["id"] for row in products.values()])
                except SourceUnavailable as exc:
                    cost_problem = str(exc)
                else:
                    history = append_cost_history(st, receipts)
        typed = typed_costs(table_rows(st))
        computed, report = build_rows(con, period, row_links, thin, cost_reader, today,
                                      history=history, receipts=receipts, cost_problem=cost_problem, typed=typed)
        usage = report.pop("_costUsage")
        if cost_reader is None:
            landed_checks = landed_cost_checks(con, usage, history)
            report["landedValidation"] = landed_checks
            if not all(check["ok"] for check in landed_checks):
                return dict(keep_figures(st, line="Not verified: receipt costs do not tie to Odoo landed cost lines.",
                                         period=period, month=month, covered=covered, by=by),
                            landedValidation=landed_checks)
        typed_checks = typed_cogs_checks(con, computed, typed, usage, report["period"])
        report["typedValidation"] = typed_checks
        if not all(check["ok"] for check in typed_checks):
            return dict(keep_figures(st, line=TYPED_REFUSAL, period=period, month=month, covered=covered, by=by),
                        typedValidation=typed_checks)
        bounds = report["period"]
        metrics, metric_problem = {}, None
        try:
            metrics = M.sku_metrics(con, start=bounds["start"], end=bounds["end"], skus=list(computed), today=day)
        except _metric_problem_types() as exc:
            metric_problem = str(exc)
        computed = _withhold(merge_metrics(computed, metrics), partial)
        metric_checks = [] if metric_problem else list(
            M.validate_metrics(con, start=bounds["start"], end=bounds["end"], computed=metrics) or [])
        metric_refusal = metric_problem or next(
            (f"Not verified: {c.get('check')}." for c in metric_checks if not c.get("ok")), None)
        if metric_refusal:
            computed = {sku: _explain(_blank(values, _METRIC_VALUE_KEYS), _METRIC_VALUE_KEYS, metric_refusal)
                        for sku, values in computed.items()}
        from harness import amazon_pictures
        refs = amazon_pictures.picture_refs(st) or {}
        computed = sku_pictures(computed, refs)
        report.update(write_rows(st, computed), merged=merged,
                      decisions={k: decisions[k] for k in ("confirmed", "rejected")})
        report["projects"] = update_projects(st, con, today=day, computed=computed,
                                              period=period, period_label=bounds["label"])
        report["projectValidation"] = report["projects"]["validation"]
        rows = [dict(_raw_row(values), sku=sku, velocity_30d=(metrics.get(sku) or {}).get("velocity_30d"),
                     fnsku=(metrics.get(sku) or {}).get("fnsku"))
                for sku, values in computed.items()]

        by_grain = {key: grain_rows(rows, key, thin=thin, period_label=bounds["label"], fields=fields)
                    for key, fields in (("asin", ASIN_FIELDS), ("parent_asin", PARENT_FIELDS))}
        report["pictures"] = dict(grain_pictures(by_grain, refs), stored=len(refs),
                                  sku=sum(1 for values in computed.values() if values.get("picture")))
        for key, cells_by_key in list(by_grain.items()):
            cells_by_key = _withhold(cells_by_key, partial)
            if metric_refusal:
                cells_by_key = {k: _explain(_blank(v, _METRIC_VALUE_KEYS), _METRIC_VALUE_KEYS, metric_refusal)
                                for k, v in cells_by_key.items()}
            by_grain[key] = cells_by_key
        tie = rollup_checks(computed, by_grain)
        if not all(check["ok"] for check in tie):
            failed = "Not verified: the rollup totals do not add up to the SKU totals."
            by_grain = {key: {k: _explain(_blank(v, _UNVERIFIED_KEYS, failed), _UNVERIFIED_KEYS, failed)
                              for k, v in cells_by_key.items()}
                        for key, cells_by_key in by_grain.items()}
        ties = grain_ties(con, bounds["start"], bounds["end"], computed, by_grain)
        by_grain = _withhold_untied(by_grain, ties)
        report["metricValidation"] = metric_checks + tie + ties
        report["metricRefusal"] = metric_refusal
        report["asin"] = write_rows(st, by_grain["asin"], table_key=ASIN_KEY, key_column="asin",
                                    label=ASIN_LABEL, period_keys=_grain_period_keys(ASIN_FIELDS, "asin"))
        report["parent"] = write_rows(st, by_grain["parent_asin"], table_key=PARENT_KEY,
                                      key_column="parent_asin", label=PARENT_LABEL,
                                      period_keys=_grain_period_keys(PARENT_FIELDS, "parent_asin"))
        report["asinSignals"] = paint_asin_signals(st, con, today=day)
        report["blankReasons"] = blank_check(stored_tables(st))
        bands = {sku: values.get("band") for sku, values in computed.items()}
        report["owned"] = apply_owned(st, bands, today=day, owner=owner_label)
        stamp = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
        write_settings(st, period=period, thin=thin, refreshedAt=stamp, refreshedBy=by or WRITER,
                       lastPeriod=report["period"], skus=report["skus"], linked=report["linked"],
                       verifiedMonth=month, refusal=None, verified=verified, verifiedRange=covered,
                       lastRefusal=None, withheld=partial, settling=settling)
    report.update(tableKey=TABLE_KEY, refreshedAt=stamp, verifiedMonth=month, refusal=None,
                  verified=verified, verifiedRange=covered, defaultOwner=owner,
                  withheld=partial, settling=settling)
    try:
        report["projectCells"] = paint_project_cells(st, con)
    except Exception as exc:
        _log(f"project cells unavailable ({type(exc).__name__})")
    report["dataEntry"] = data_entry_sync(st, con, by=by)
    return report


def data_entry_sync(st, con, *, by=""):
    """Rebuild Data Entry after a refresh. A failure there is reported and never fails the refresh."""
    from modules import amazon_data_entry
    try:
        return amazon_data_entry.sync(st, con, by=by)
    except Exception as exc:                                           # noqa: BLE001
        return {"error": f"Data Entry was not rebuilt: {exc}"}


def _stored_day(settings):
    """The `today` the stored figures were computed on, so a rolling window covers the same days."""
    end = (settings.get("lastPeriod") or {}).get("end")
    try:
        return dt.date.fromisoformat(end) + dt.timedelta(days=1) if end else None
    except (TypeError, ValueError):
        return None


def recompute_sku(st, con, sku, *, by="", cost_reader=None, today=None):
    """Recompute one SKU's cost and profit from its current Odoo link and write that row only.

    It keeps the stored period and window, so it needs no new settlement tie and a refused
    refresh never blocks it. The link door, the Link status cell hook and Data Entry call it.
    Returns `{sku, written, row}`, or `{sku, refusal}` when receipt costs do not tie."""
    import core.user_tables as ut
    sku = str(sku or "").strip()
    with _LOCK:
        settings = read_settings(st)
        day = today or _stored_day(settings) or _today()
        stored = {str(r.get("sku") or "").strip(): r for r in table_rows(st).values()}
        if not sku or sku not in stored:
            return {"sku": sku, "written": False, "row": None}
        row_links = links(table_rows(st))
        receipts, history, cost_problem = None, [], None
        if cost_reader is None:
            history = read_cost_history(st)
            products, _problems = mirror_products(con, {link["code"] for link in row_links.values() if link["code"]})
            if products:
                try:
                    receipts = receipt_costs(con, [row["id"] for row in products.values()])
                except SourceUnavailable as exc:
                    cost_problem = str(exc)
                else:
                    history = append_cost_history(st, receipts)
        # Every link goes in: FIFO shares receipts across SKUs on one Odoo product.
        typed = typed_costs(table_rows(st))
        computed, report = build_rows(con, settings["period"], row_links, settings["thin"], cost_reader, day,
                                      history=history, receipts=receipts, cost_problem=cost_problem, typed=typed)
        usage = report.pop("_costUsage")
        if cost_reader is None and not all(c["ok"] for c in landed_cost_checks(con, usage, history)):
            return {"sku": sku, "refusal": "Not verified: receipt costs do not tie to Odoo landed cost lines."}
        if not all(c["ok"] for c in typed_cogs_checks(con, computed, typed, usage, report["period"])):
            return {"sku": sku, "refusal": TYPED_REFUSAL}
        values = computed.get(sku)
        if values is None:
            return {"sku": sku, "written": False, "row": dict(stored[sku])}
        before = stored[sku]
        if any(before.get(k) not in (None, "") for k in _METRIC_VALUE_KEYS):
            # The stored metric inputs passed their checks at the last refresh; only the score moves.
            inputs = {k: raw_value(_FIELD_BY_KEY.get(k), before.get(k)) for k in METRIC_KEYS if k in before}
            values = merge_metrics({sku: values}, {sku: inputs})[sku]
        values = {k: v for k, v in values.items() if k not in _IDENTITY_KEYS or k == "title"}
        values = _withhold({sku: values}, settings.get("withheld"))[sku]
        after = {}

        def _set(cur):
            after.clear()
            table = (cur or {}).get(TABLE_KEY)
            if table is None:
                return cur
            for row in (table.get("rows") or {}).values():
                if str(row.get("sku") or "").strip() == sku:
                    _apply_cells(row, values)
                    after.update(row)
            return cur

        ut.update_with_activity(TABLE_KEY, _set, st=st, by=by or WRITER, via=VIA, row_ids=None)
        _recompute_stored_grains(st, after, settings, con)
        _owner, owner_label = default_owner(st, getattr(st, "key", TENANT_ZERO))
        apply_owned(st, {sku: after.get("band")}, today=today or _today(), owner=owner_label, skus={sku})
        after = next((row for row in table_rows(st).values() if row.get("sku") == sku), after)
        write_settings(st, linked=report["linked"])
    return {"sku": sku, "written": True, "row": dict(after)}


def _recompute_stored_grains(st, changed, settings, con=None):
    """Update the edited SKU's rollups from persisted cells after their sums tie.
    With `con`, each rewritten row also ties to the mirror; a failed figure stays withheld with its reason."""
    period_label = str(changed.get("period") or "")
    if not period_label:
        return
    source = {rid: row for rid, row in table_rows(st).items() if row.get("period") == period_label}
    rows = [_raw_row(row) for row in source.values()]
    plans = {grain: _withhold(grain_rows(rows, grain, thin=settings["thin"], period_label=period_label,
                                         fields=fields), settings.get("withheld"))
             for grain, fields in (("asin", ASIN_FIELDS), ("parent_asin", PARENT_FIELDS))}
    checks = rollup_checks({rid: row for rid, row in source.items()}, plans)
    if not all(check["ok"] for check in checks):
        _log("edited SKU rollups not verified")
        return
    bounds = settings.get("lastPeriod") or {}
    if con is not None and bounds.get("start") and bounds.get("end"):
        plans = {grain: {key: cells for key, cells in plans[grain].items()
                         if key == str(changed.get(grain) or "").strip()} for grain in plans}
        sku_cells = {str(r.get("sku")).strip(): r for r in source.values() if str(r.get("sku") or "").strip()}
        plans = _withhold_untied(plans, grain_ties(con, bounds["start"], bounds["end"], sku_cells, plans))
    for grain, table_key, fields in (("asin", ASIN_KEY, ASIN_FIELDS), ("parent_asin", PARENT_KEY, PARENT_FIELDS)):
        key = str(changed.get(grain) or "").strip()
        if key and key in plans[grain]:
            values = {k: v for k, v in plans[grain][key].items() if k not in _IDENTITY_KEYS or k == grain}
            write_rows(st, {key: values}, table_key=table_key, key_column=grain, period_keys=())


# ---------------------------------------------------------------- validation source

_SNAPSHOT = {}


def _mirror_has_economics(con):
    try:
        return bool(_columns(con, ECONOMICS))
    except Exception:                                                  # noqa: BLE001
        return False


def snapshot_cursor(tenant=TENANT_ZERO, tables=(ECONOMICS, SETTLEMENTS, LISTINGS, "amzn_orders",
                    "amzn_listing_items", "amzn_search_query_performance",
                    "amzn_ads_sp_advertised_products", "amzn_ads_sb_advertised_products",
                    "amzn_ads_sd_advertised_products")):
    """An in-memory DuckDB over the stored mirror snapshot. Downloads only; writes nothing back."""
    key = (tenant, tuple(tables))
    if key in _SNAPSHOT:
        return _SNAPSHOT[key].cursor()
    import duckdb
    from harness import runtime as R
    from harness import mirror_store
    rt = R.get_runtime(tenant)
    mirror = mirror_store.for_connector("amazon")
    raw = mirror._download(rt, "manifest.json")
    if raw is None:
        raise SourceUnavailable(f"{tenant} has no stored Amazon mirror.")
    manifest = json.loads(raw)
    if manifest.get("tenant") != tenant:
        raise SourceUnavailable("The stored Amazon mirror names another tenant.")
    folder = Path(tempfile.mkdtemp(prefix="amazon-profit-"))
    atexit.register(shutil.rmtree, folder, True)
    con = duckdb.connect()
    for name in tables:
        meta = (manifest.get("tables") or {}).get(name)
        if not isinstance(meta, dict):
            continue
        paths = []
        for index, part in enumerate(meta.get("parts") or [meta]):
            blob_key = part.get("key") or f"{name}.parquet"
            data = mirror._download(rt, blob_key)
            if data is None or (part.get("sha256") and hashlib.sha256(data).hexdigest() != part["sha256"]):
                raise SourceUnavailable(f"The stored {name} snapshot failed its checksum.")
            path = folder / f"{name}.{index:04d}.parquet"
            path.write_bytes(data)
            paths.append(str(path))
        if paths:
            listed = ", ".join("'" + p.replace("'", "''") + "'" for p in paths)
            con.execute(f"CREATE VIEW {name} AS SELECT * FROM read_parquet([{listed}], union_by_name=true)")
    _SNAPSHOT[key] = con
    return con.cursor()


def validation_cursor(tenant=TENANT_ZERO):
    """`(cursor, source)`: the local mirror when it holds economics, else the stored snapshot."""
    try:
        from harness import datastore as DS
        if Path(DS.DB_PATH).is_file():
            con = DS.ro_cursor()
            if _mirror_has_economics(con):
                return con, "local mirror"
    except Exception:                                                  # noqa: BLE001
        pass
    return snapshot_cursor(tenant), "stored snapshot"


# ---------------------------------------------------------------- validate

def _tie(a, b, tolerance=SETTLEMENT_TOLERANCE):
    gap = abs(a - b) / abs(b) if b else (0.0 if a == b else math.inf)
    return gap <= tolerance, gap


def landed_cost_checks(con, usage=None, history=None):
    """Tie allocated receipt costs to independent SQL sums of valuations and posted adjustment lines."""
    if not usage:
        return [{"check": "amazon_profit: no receipt COGS used", "ok": True,
                 "state": "unused", "verified": False, "a": 0, "b": 0, "gap": 0}]
    try:
        _require_odoo(con, _RECEIPT_COLUMNS)
    except SourceUnavailable as exc:
        return [{"check": "amazon_profit: receipt cost source unavailable", "ok": False,
                 "state": "unavailable", "reason": str(exc), "a": None, "b": None, "gap": None}]
    saved = {row["observation_id"]: row for row in history or []}
    base = {(int(pid), int(move)): (purchase, float(quantity), name, day)
            for pid, move, purchase, quantity, name, day in con.execute(
                f"SELECT v.product_id,m.id,SUM(v.value)/SUM(v.quantity),SUM(v.quantity),p.name, "
                f"{_RECEIPT_DATE} AS day FROM {_RECEIPT_FROM} "
                "WHERE m.state='done' AND src.usage='supplier' AND dst.usage='internal' AND v.quantity>0 "
                "GROUP BY v.product_id,m.id,p.name,day").fetchall()}
    lines = {(int(pid), int(move)): (float(amount), invalid)
             for pid, move, amount, invalid in con.execute(
                 "SELECT a.product_id,a.move_id,COALESCE(SUM(a.additional_landed_cost/NULLIF(a.quantity,0)),0), "
                 "count(*) FILTER (WHERE a.quantity IS NULL OR a.quantity<=0 OR a.additional_landed_cost IS NULL) "
                 "FROM stock_valuation_adjustment_lines a JOIN stock_landed_cost h ON h.id=a.cost_id "
                 "WHERE h.state='done' AND a.product_id IS NOT NULL AND a.move_id IS NOT NULL "
                 "GROUP BY a.product_id,a.move_id").fetchall()}
    mismatches, by_receipt = [], {}
    used_total, expected_total = 0.0, 0.0
    for part in usage:
        pid, move, units = part["product_id"], part["move_id"], part["units"]
        source = base.get((pid, move))
        landed, invalid = lines.get((pid, move), (0.0, 0))
        expected = landed * units
        stored = saved.get(part["observation_id"])
        purchase_ok = (source is not None and source[0] is not None
                       and abs(float(source[0]) * units - part["purchase_used"]) <= 0.005)
        history_ok = stored is not None and stored == part["receipt"]
        receipt_ok = (source is not None and stored is not None and source[2] == stored["receipt"]
                      and source[3] == stored["date"] and stored["date"] <= part["sale_date"])
        ok = (history_ok and receipt_ok and purchase_ok and invalid == 0 and math.isfinite(expected)
              and abs(part["landed_used"] - expected) <= 0.005)
        if not ok:
            mismatches.append({"sku": part["sku"], "product_id": pid, "move_id": move})
        used_total += part["landed_used"]
        expected_total += expected
        key = pid, move
        by_receipt[key] = by_receipt.get(key, 0.0) + part["units"]
    overdrawn = [key for key, used in by_receipt.items() if key not in base or used > base[key][1] + 1e-8]
    return [{"check": "amazon_profit: receipt COGS ties by receipt to stock_valuation_adjustment_lines",
             "ok": not mismatches, "state": "verified" if not mismatches else "failed",
             "a": round(used_total, 4), "b": round(expected_total, 4),
             "gap": round(abs(used_total - expected_total), 6), "mismatches": mismatches},
            {"check": "amazon_profit: seller SKUs share each receipt without duplicate allocation",
             "ok": not overdrawn, "a": len(overdrawn), "b": 0, "gap": len(overdrawn)}]


TYPED_REFUSAL = "Not verified: typed COGS does not tie to the stored typed values."


def typed_cogs_checks(con, computed, typed, usage=None, bounds=None):
    """Typed COGS stays out of the Odoo receipt tie and ties to stored typed values times mirror units."""
    typed = typed or {}
    typed_skus = sorted(sku for sku, values in computed.items() if values.get("cogs_source") == COGS_TYPED)
    in_tie = sorted({part.get("sku") for part in usage or ()} & set(typed_skus))
    units = {item["sku"]: int(_num(item.get("units")))
             for item in economics_by_sku(con, bounds["start"], bounds["end"])} if bounds else {}
    share = round(sum(_num(computed[sku].get("cogs_total")) for sku in typed_skus), 2)
    stored = round(sum(value * units.get(sku, 0) for sku, value in typed.items()
                       if (computed.get(sku) or {}).get("cogs_source") == COGS_TYPED), 2)
    unstored = [sku for sku in typed_skus if sku not in typed]
    tolerance = 0.005 * max(len(typed_skus), 1) + 1e-9
    return [{"check": "amazon_profit: typed COGS SKUs stay out of the Odoo receipt tie",
             "ok": not in_tie, "typed": typed_skus, "a": len(in_tie), "b": 0, "gap": len(in_tie)},
            {"check": "amazon_profit: typed COGS share ties to stored values",
             "ok": not unstored and abs(share - stored) <= tolerance, "typed": typed_skus,
             "a": share, "b": stored, "gap": round(abs(share - stored), 4), "unstored": unstored}]


def stored_tables(st):
    """`{table key: (field keys, rows)}` of the three stored Command Center tables."""
    import core.user_tables as ut
    out = {}
    for key in (TABLE_KEY, ASIN_KEY, PARENT_KEY):
        table = ut.get_one(key, st) or {}
        out[key] = ([f["key"] for f in table.get("fields") or []], list((table.get("rows") or {}).values()))
    return out


def stored_grain_checks(st, con):
    """The stored ASIN and parent tables tie per row to the mirror over the stored period, and every
    stored blank says why. Reads only."""
    tables = stored_tables(st)
    bounds = read_settings(st).get("lastPeriod") or {}
    if not bounds.get("start") or not bounds.get("end"):
        return [{"check": "amazon_profit: the stored tables name their period", "ok": False, "grain": None,
                 "reason": "Not verified: the stored Command Center has no period."}, blank_check(tables)]
    sku_cells = {str(r.get("sku")).strip(): r for r in tables[TABLE_KEY][1] if str(r.get("sku") or "").strip()}
    by_grain = {grain: {str(r.get(grain)).strip(): r for r in tables[key][1] if str(r.get(grain) or "").strip()}
                for grain, key in (("asin", ASIN_KEY), ("parent_asin", PARENT_KEY))}
    return grain_ties(con, bounds["start"], bounds["end"], sku_cells, by_grain) + [blank_check(tables)]


def validate(pre=None, month=None, con=None, *, cost_usage=None, cost_history=None, typed_rows=None,
             typed_values=None, typed_period=None, st=None, today=None):
    """Tie net proceeds components to independent Amazon sources within 2% over settled days.
    Receipt COGS ties to Odoo; typed COGS (`typed_rows`) is listed apart and ties to its stored values.
    With `st`, stored grain figures, search signals and listing dates tie to their sources."""
    month = month or last_complete_month()
    bounds = period_bounds(month)
    start, end = bounds["start"], bounds["end"]
    source = "given cursor"
    if con is None:
        con, source = validation_cursor()
    checks = []
    try:
        _require(con, ECONOMICS, _ECONOMICS_REQUIRED)
        currency = economics_currency(con)
        span = settlement_coverage(con, start, end, currency)
        settled = settlements_total(con, start, end, currency)
    except SourceUnavailable as exc:
        label = dt.date.fromisoformat(start).strftime("%B %Y")
        raise SourceUnavailable(f"Not verified: settlement components in {label}: {exc}") from None
    lo, hi = span["start"] or start, span["end"] or end
    proceeds = net_proceeds_total(con, lo, hi)
    aligned = settlement_components(con, lo, hi, currency)
    if span["start"] is None:
        aligned = dict(aligned, total=None, rows=0,
                       reason=f"Not verified: settlement components in {bounds['label']}: no settled days.")
    target = aligned["total"]
    ok, gap = _tie(proceeds, target) if target is not None else (False, math.inf)
    covered = {k: span[k] for k in ("start", "end", "label", "partial", "clear", "sentence")}
    checks.append({"check": f"amazon_profit {month}: net proceeds tie to settlements within 2% over "
                            f"{span['label'] or 'no settled days'} ({gap:.2%} apart, {source})",
                   "ok": ok and not aligned["reason"], "a": round(proceeds, 2),
                   "b": None if target is None else round(target, 2), "reason": aligned["reason"],
                   "components": aligned["parts"], "excluded": aligned.get("excluded", {}),
                   "failedComponents": aligned.get("failedComponents", []),
                   "gap": round(gap, 4), "covered": covered, "tolerance": SETTLEMENT_TOLERANCE})
    dropped = net_proceeds_total(con, lo, hi, drop_fees=True)
    control_ok, control_gap = _tie(dropped, target) if target is not None else (False, math.inf)
    checks.append({"check": f"amazon_profit {month}: NC net proceeds without fees miss settlements "
                            f"({control_gap:.2%} apart)",
                   "ok": not control_ok, "a": round(dropped, 2),
                   "b": None if target is None else round(target, 2),
                   "gap": round(control_gap, 4)})
    checks.append({"check": f"amazon_profit {month}: every {settled['currency'] or 'settlement'} "
                            "settlement row carries a readable date",
                   "ok": settled["undated"] == 0, "a": settled["undated"], "b": 0,
                   "gap": settled["undated"]})
    econ = economics_by_sku(con, start, end)
    ours = sum(compute_row(item)["net_proceeds"] for item in econ)
    reported = reported_net_proceeds(con, start, end)
    checks.append({"check": f"amazon_profit {month}: per SKU net proceeds sum to Amazon's reported total",
                   "ok": reported is not None and abs(ours - reported) <= 0.01,
                   "a": round(ours, 2), "b": None if reported is None else round(reported, 2),
                   "gap": None if reported is None else round(abs(ours - reported), 4)})
    distinct = con.execute(f"SELECT count(DISTINCT msku) FROM {ECONOMICS} "
                           "WHERE NULLIF(trim(msku), '') IS NOT NULL").fetchone()[0]
    checks.append({"check": f"amazon_profit: every SKU is present, no cap ({len(econ)} SKUs)",
                   "ok": len(econ) == distinct, "a": len(econ), "b": distinct,
                   "gap": abs(len(econ) - distinct)})
    checks.extend(landed_cost_checks(con, cost_usage, cost_history))
    if typed_rows is not None:
        checks.extend(typed_cogs_checks(con, typed_rows, typed_values, cost_usage, typed_period or bounds))
    if st is not None:
        checks.extend(stored_grain_checks(st, con))
        checks.extend(listing_date_checks(st, con))
        checks.extend(asin_signal_checks(st, con, today=today))
    return checks


# ---------------------------------------------------------------- semantic validator

def _v_amazon_sku_net_profit(date_from, date_to, team_id=None, **_kwargs):
    """Per SKU net proceeds (the profit's revenue side) against Amazon's reported total."""
    con, _source = validation_cursor()
    start, end = str(date_from)[:10], str(date_to)[:10]
    ours = sum(compute_row(item)["net_proceeds"] for item in economics_by_sku(con, start, end))
    reported = reported_net_proceeds(con, start, end)
    if reported is None:
        raise SourceUnavailable("amzn_economics lacks net_proceeds_total_amount.")
    return round(ours, 2), round(reported, 2)


PROFIT_VALIDATORS = {"amazon_sku_net_profit": _v_amazon_sku_net_profit}


def register_semantic_validators():
    """Register this module's validator until harness/semantic.py imports it directly."""
    from harness import semantic
    semantic._VALIDATORS.update(PROFIT_VALIDATORS)
    return tuple(PROFIT_VALIDATORS)


try:
    register_semantic_validators()
except Exception:                                                      # noqa: BLE001
    pass