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

# -----------------------------
# Environment hardening (HF Spaces, /.cache issue)
# -----------------------------
_home = os.environ.get("HOME", "")
if _home in ("", "/", None):
    repo_dir = os.getcwd()
    safe_home = repo_dir if os.access(repo_dir, os.W_OK) else "/tmp"
    os.environ["HOME"] = safe_home
    print(f"[startup] HOME not set or unwritable β€” setting HOME={safe_home}")

streamlit_dir = Path(os.environ["HOME"]) / ".streamlit"
try:
    streamlit_dir.mkdir(parents=True, exist_ok=True)
    print(f"[startup] ensured {streamlit_dir}")
except Exception as e:
    print(f"[startup] WARNING: could not create {streamlit_dir}: {e}")

# HF Spaces serves the app behind an iframe/proxy, which makes Streamlit's
# default XSRF Origin check reject the file-uploader's POST with 403 even
# though the websocket connection works fine. Disable it via config.toml.
_config_toml = streamlit_dir / "config.toml"
try:
    if not _config_toml.exists():
        _config_toml.write_text(
            "[server]\nenableXsrfProtection = false\nenableCORS = false\n",
            encoding="utf-8",
        )
        print(f"[startup] wrote {_config_toml}")
except Exception as e:
    print(f"[startup] WARNING: could not write {_config_toml}: {e}")

# -----------------------------
# Imports
# -----------------------------
import json
from io import BytesIO
import hashlib
from typing import Dict, Any, List, Optional
from datetime import datetime, timedelta
from copy import deepcopy

import streamlit as st
import pandas as pd
from PIL import Image

try:
    from pdf2image import convert_from_bytes
except Exception:
    convert_from_bytes = None

try:
    import fitz as _fitz  # PyMuPDF β€” fallback PDF renderer (no Poppler needed)
except Exception:
    _fitz = None


def _pdf_to_images(pdf_bytes: bytes, dpi: int = 300) -> list:
    """Convert PDF bytes to a list of PIL RGB images. Tries pdf2image first, PyMuPDF second."""
    if convert_from_bytes is not None:
        try:
            pages = convert_from_bytes(pdf_bytes, dpi=dpi)
            return [p.convert("RGB") for p in pages]
        except Exception:
            pass  # fall through to PyMuPDF
    if _fitz is not None:
        doc = _fitz.open(stream=pdf_bytes, filetype="pdf")
        pages = []
        scale = dpi / 72
        mat = _fitz.Matrix(scale, scale)
        for page in doc:
            pix = page.get_pixmap(matrix=mat)
            img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
            pages.append(img)
        doc.close()
        return pages
    raise RuntimeError("No PDF renderer available β€” install poppler (pdf2image) or PyMuPDF (pip install pymupdf).")

import requests
import base64
import re

# ── Pipeline integration setup ──────────────────────────────────────────────
import sys
from types import SimpleNamespace
from decimal import Decimal

_HERE_DIR = os.path.dirname(os.path.abspath(__file__))
# Works both locally (Matching Functions/ subfolder) and on HF Spaces (flat src/)
_MATCHING_DIR = (
    os.path.join(_HERE_DIR, "Matching Functions")
    if os.path.isdir(os.path.join(_HERE_DIR, "Matching Functions"))
    else _HERE_DIR
)

_pipeline_available = False
_pipeline_import_error = None
try:
    if _MATCHING_DIR not in sys.path:
        sys.path.insert(0, _MATCHING_DIR)
    from invoice_pipeline import run_invoice_pipeline
    from two_way_match import InvoiceHeader, InvoiceLine, POHeader, POLine
    from three_way_match import GRLineItem
    from contract_match import ContractInvoiceHeader, ContractRecord, RateCardItem
    _pipeline_available = True
except Exception as _e:
    _pipeline_import_error = str(_e)

POD_URL      = os.getenv("POD_URL", "https://0vpfyk7wnnc5vl-8000.proxy.runpod.net")
VLLM_API_KEY = os.getenv("VLLM_API_KEY", "9386aa7335c2072882ad367791f1dc863c63b4be88eda14c2dea0408f9d0105e")
MODEL_NAME   = "phase2-v1-merged"

MAX_PAGES_PER_REQUEST = 10
MAX_DIMENSION_PER_PAGE = 1024
MAX_TOTAL_PAYLOAD_MB   = 40.0

# -----------------------------
# Page config & CSS  (must be the FIRST st.* call)
# -----------------------------
st.set_page_config(page_title="Invoice Extractor (Qwen3-VL) - Batch Mode", layout="wide")

if not POD_URL or not VLLM_API_KEY:
    st.error("⚠️ API credentials not configured. Please set POD_URL and VLLM_API_KEY in Space settings.")
    st.stop()
st.title("Invoice Extraction")

st.markdown(
    """
    <style>
        .stApp { background-color: #ECECEC !important; }
        div.block-container { padding-top: 3rem; padding-bottom: 1rem; }

        /* Custom nav: a fixed toggle button + an overlay panel built from
           st.container(key=...), driven entirely by session_state β€” no JS,
           no fighting Streamlit's own sidebar collapse animation. */
        .st-key-sidebar_toggle_btn button {
            position: fixed !important;
            top: 10px !important;
            left: 10px !important;
            z-index: 1000001 !important;
            width: 38px !important;
            height: 38px !important;
            padding: 0 !important;
            border-radius: 6px !important;
            background: #F7F7F7 !important;
            border: 1px solid #ccc !important;
            font-size: 16px !important;
        }
        .st-key-nav_overlay_panel {
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            width: 220px !important;
            height: 100vh !important;
            background-color: #F7F7F7 !important;
            z-index: 999999 !important;
            box-shadow: 2px 0 12px rgba(0,0,0,0.25) !important;
            padding: 56px 14px 14px 14px !important;
            overflow-y: auto !important;
        }
        .st-key-nav_overlay_panel .stButton > button {
            background: transparent !important;
            border: none !important;
            box-shadow: none !important;
            text-align: center !important;
            font-size: 14px !important;
            font-weight: 500 !important;
            color: #333 !important;
            padding: 8px 10px !important;
            border-radius: 5px !important;
            width: 100% !important;
        }
        .st-key-nav_overlay_panel .stButton > button:hover {
            background: #E0E0E0 !important;
            color: #000 !important;
            border: none !important;
            box-shadow: none !important;
        }

        div[data-testid="stTabs"] > div > div { padding-bottom: 6px !important; }
        [data-testid="column"]:nth-of-type(2) { min-height: 780px; }
        [data-testid="stImage"] img { image-rendering: auto; }
    </style>
    <script>
        // Push a dummy state so there's always something to pop back to
        history.pushState(null, null, window.location.href);
        window.addEventListener('popstate', function(event) {
            history.pushState(null, null, window.location.href);
        });
    </script>
    """,
    unsafe_allow_html=True
)

DATA_EDITOR_HEIGHT = 380

# -----------------------------
# Helpers β€” numeric/date cleaning from code #1
# -----------------------------
def ensure_state(k: str, default):
    """Initialize a session_state key once, then let widgets bind to it via key=... (no value=...)."""
    if k not in st.session_state:
        st.session_state[k] = default

def parse_time_to_minutes(x) -> float:
    """
    Parse time format quantities to minutes.
    
    Examples:
        "0:35"  β†’ 35.0   (0 hours, 35 minutes = 35 minutes)
        "1:30"  β†’ 90.0   (1 hour, 30 minutes = 90 minutes)
        "2:15"  β†’ 135.0  (2 hours, 15 minutes = 135 minutes)
        "0:05"  β†’ 5.0    (5 minutes)
        "123"   β†’ 123.0  (regular number, not time format)
        "1.5"   β†’ 1.5    (regular decimal, not time format)
    """
    if x is None:
        return 0.0
    if isinstance(x, (int, float)):
        return float(x)
    
    s = str(x).strip()
    if s == "":
        return 0.0
    
    # Check if it's in time format (H:MM or HH:MM)
    time_pattern = r'^(\d+):(\d{1,2})$'
    match = re.match(time_pattern, s)
    
    if match:
        hours = int(match.group(1))
        minutes = int(match.group(2))
        total_minutes = (hours * 60) + minutes
        return float(total_minutes)
    
    # Not time format, treat as regular number
    return 0.0

def clean_quantity(x) -> float:
    """
    Parse quantity - handles both time format (H:MM) and regular numbers.
    
    Examples:
        "0:35"     β†’ 35.0   (time format: 35 minutes)
        "1:30"     β†’ 90.0   (time format: 90 minutes)
        "123"      β†’ 123.0  (regular number)
        "1,234.56" β†’ 1234.56 (US format with decimals)
        "1.234,56" β†’ 1234.56 (EUR format with decimals)
    """
    if x is None:
        return 0.0
    if isinstance(x, (int, float)):
        return float(x)
    
    s = str(x).strip()
    if s == "":
        return 0.0
    
    # First check if it's time format (H:MM or HH:MM)
    time_value = parse_time_to_minutes(s)
    if time_value > 0.0:
        return time_value
    
    # Not time format β€” period is always a decimal separator for quantities,
    # never a thousands separator (reuse clean_tax_percentage logic).
    return clean_tax_percentage(s)

def clean_tax_percentage(x) -> float:
    """
    Parse tax percentage - ALWAYS treats periods as decimals, never as thousands.
    
    Tax percentages are typically: 8.875, 19.5, 2.75, 0.0875, etc.
    We should NEVER interpret "8.875" as "8875"
    
    Examples:
        "8.875"    β†’ 8.875   (decimal percentage)
        "8,875"    β†’ 8.875   (European decimal)
        "19.5"     β†’ 19.5    (standard decimal)
        "2,75"     β†’ 2.75    (European decimal)
    """
    if x is None:
        return 0.0
    if isinstance(x, (int, float)):
        return float(x)
    
    s = str(x).strip()
    if s == "":
        return 0.0
    
    # Handle negative signs (could be leading or trailing)
    is_negative = False
    if s.startswith('-'):
        is_negative = True
        s = s[1:].strip()
    elif s.endswith('-'):
        is_negative = True
        s = s[:-1].strip()
    elif s.startswith('(') and s.endswith(')'):
        is_negative = True
        s = s[1:-1].strip()
    
    # Remove percent signs, currency symbols and spaces
    s = re.sub(r'[%€$Β£Β₯β‚Ή\s]', '', s)
    
    if s == "":
        return 0.0
    
    # Count occurrences
    comma_count = s.count(',')
    period_count = s.count('.')
    
    # For tax percentages, logic is simpler:
    # - If both comma and period exist, the LAST one is decimal separator
    # - If only comma exists, it's decimal separator (European style)
    # - If only period exists, it's ALWAYS decimal separator (no thousands logic)
    
    if comma_count > 0 and period_count > 0:
        # Both present - LAST one is decimal
        last_comma = s.rfind(',')
        last_period = s.rfind('.')
        
        if last_comma > last_period:
            # European: 1.234,56 β†’ comma is decimal
            s = s.replace('.', '').replace(',', '.')
        else:
            # US: 1,234.56 β†’ period is decimal
            s = s.replace(',', '')
    
    elif comma_count > 0:
        # Only comma - treat as European decimal separator
        s = s.replace(',', '.')
    
    # If only period(s) exist, keep as-is (always decimal for tax percentages)
    
    # Clean any remaining non-numeric characters except period and minus
    s = re.sub(r'[^\d.]', '', s)
    
    if s == "" or s == ".":
        return 0.0
    
    try:
        result = float(s)
        return -result if is_negative else result
    except ValueError:
        return 0.0

def clean_float(x, currency=None) -> float:
    """
    Parse a number string handling both US and European formats.
    Use this for MONETARY AMOUNTS only, NOT for tax percentages.
    US Format:      1,234,567.89  (comma = thousands, period = decimal)
    European:       1.234.567,89  (period = thousands, comma = decimal)
    Currency-aware for ambiguous cases (3 digits after comma):
        - EUR: "10,000" β†’ 10.0 (European decimal)
        - USD/other: "10,000" β†’ 10000 (thousands separator)
    Examples:
        "1,234.56"    β†’ 1234.56  (US)
        "1.234,56"    β†’ 1234.56  (European)
        "3.000,2234"  β†’ 3000.2234 (European with 4 decimal places)
        "261,49"      β†’ 261.49   (European decimal only)
        "39,22-"      β†’ -39.22   (European with trailing minus)
    """
    if x is None:
        return 0.0
    if isinstance(x, (int, float)):
        return float(x)
    
    s = str(x).strip()
    if s == "":
        return 0.0
    
    # Handle negative signs (could be leading or trailing)
    is_negative = False
    if s.startswith('-'):
        is_negative = True
        s = s[1:].strip()
    elif s.endswith('-'):
        is_negative = True
        s = s[:-1].strip()
    elif s.startswith('(') and s.endswith(')'):
        # Accounting format: (123.45) means negative
        is_negative = True
        s = s[1:-1].strip()
    
    # Remove currency symbols and spaces
    s = re.sub(r'[€$Β£Β₯β‚Ή\s]', '', s)
    
    if s == "":
        return 0.0
    
    # Count occurrences
    comma_count = s.count(',')
    period_count = s.count('.')
    
    # Find positions of last comma and last period
    last_comma = s.rfind(',')
    last_period = s.rfind('.')
    
    # Determine format based on which separator comes last
    if comma_count > 0 and period_count > 0:
        # Both separators present - the LAST one is the decimal separator
        if last_comma > last_period:
            # European format: 1.234,56 β†’ comma is decimal
            # Remove periods (thousands), replace comma with period
            s = s.replace('.', '').replace(',', '.')
        else:
            # US format: 1,234.56 β†’ period is decimal
            # Remove commas (thousands)
            s = s.replace(',', '')
    
    elif comma_count > 0 and period_count == 0:
        # Only commas present
        # Check what comes after the LAST comma
        after_last_comma = s[last_comma + 1:] if last_comma < len(s) - 1 else ""

        if comma_count == 1 and len(after_last_comma) == 3 and after_last_comma.isdigit():
            # AMBIGUOUS CASE: Single comma with exactly 3 digits after
            # Could be US thousands ("10,000" = 10000) or European decimal ("10,000" = 10.0)
            # Use currency to decide:
            if currency and currency.upper() == 'EUR':
                # European: treat comma as decimal separator
                # "10,000" β†’ 10.000 β†’ 10.0
                s = s.replace(',', '.')
            else:
                # USD/other: treat comma as thousands separator
                # "10,000" β†’ 10000
                s = s.replace(',', '')
        elif comma_count == 1 and len(after_last_comma) <= 4 and after_last_comma.isdigit():
            # Single comma with 1, 2, or 4 digits after β†’ European decimal
            # "261,49" β†’ 261.49, "1234,5678" β†’ 1234.5678
            s = s.replace(',', '.')
        elif len(after_last_comma) == 3 and comma_count >= 1:
            # Multiple commas with 3 digits after last β†’ thousands separator
            # "1,234,567" β†’ 1234567
            s = s.replace(',', '')
        else:
            # Multiple commas β†’ thousands separator
            # "1,234,567" β†’ 1234567
            s = s.replace(',', '')
    
    elif period_count > 0 and comma_count == 0:
        # Only periods present
        # Check what comes after the LAST period
        after_last_period = s[last_period + 1:] if last_period < len(s) - 1 else ""
        
        if period_count > 1:
            # Multiple periods β†’ definitely thousands separator (European: "1.234.567")
            s = s.replace('.', '')
        elif len(after_last_period) == 3 and after_last_period.isdigit():
            # Single period with exactly 3 digits after
            before_period = s[:last_period]
            # Only treat as thousands if there are 2+ digits before period
            # "10.000" or "123.000" β†’ thousands
            # "8.875" or "9.123" β†’ decimal
            if before_period.isdigit() and len(before_period) >= 2 and len(before_period) <= 3:
                s = s.replace('.', '')  # European thousands: "10.000" β†’ 10000
            # Otherwise keep as decimal: "8.875" β†’ 8.875
        # Otherwise keep as is (standard decimal like "1.50", "123.45")
    
    # Clean any remaining non-numeric characters except period and minus
    s = re.sub(r'[^\d.]', '', s)
    
    if s == "" or s == ".":
        return 0.0
    
    try:
        result = float(s)
        return -result if is_negative else result
    except ValueError:
        return 0.0

DECIMAL_DISPLAY_PLACES = 3
TAX_RATE_CLOSE_CALL_TOLERANCE = 0.01
SUMMARY_NUMERIC_FIELDS = {
    "Subtotal",
    "Tax Percentage",
    "Total Tax",
    "Discount Rate",
    "Total Discount Amount",
    "Total Amount",
}
TAX_RATE_FIELDS = {"Tax Percentage", "Tax Rate Per Item"}
ITEM_NUMERIC_FIELDS = {
    "Quantity",
    "Unit Price",
    "Amount",
    "Discount Rate Per Item",
    "Discount Amount Per Item",
    "Tax Rate Per Item",
    "Tax Amount Per Item",
    "Line Total",
    "Tax",
    "line_total",
}
EDITOR_NUMERIC_COLUMNS = [
    "Quantity",
    "Unit Price",
    "Amount",
    "Discount Rate Per Item",
    "Discount Amount Per Item",
    "Tax Rate Per Item",
    "Tax Amount Per Item",
    "Line Total",
]

def is_blank_numeric_value(value) -> bool:
    if value is None:
        return True
    try:
        if bool(pd.isna(value)):
            return True
    except (TypeError, ValueError):
        pass
    return isinstance(value, str) and value.strip() == ""

def limit_decimal_places(value, places: int = DECIMAL_DISPLAY_PLACES):
    """Round numeric display/export values to at most `places` decimals."""
    if is_blank_numeric_value(value):
        return ""
    rounded = round(clean_float(value), places)
    if rounded == 0:
        return 0.0
    return rounded

def normalize_tax_rate_close_call(value):
    """Snap near-whole tax rates like 19.99/20.002/20.01 to 20."""
    if is_blank_numeric_value(value):
        return ""
    rate = clean_tax_percentage(value)
    if is_blank_numeric_value(rate):
        return ""
    nearest_whole = round(rate)
    if abs(rate - nearest_whole) <= TAX_RATE_CLOSE_CALL_TOLERANCE + 1e-9:
        return float(nearest_whole)
    return limit_decimal_places(rate)

def editable_numeric_value(field: str, value):
    if field in TAX_RATE_FIELDS:
        normalized = normalize_tax_rate_close_call(value)
    else:
        normalized = limit_decimal_places(value)
    if normalized == "":
        return 0.0
    return float(normalized)

def coerce_numeric_items_df(df: pd.DataFrame) -> pd.DataFrame:
    """Keep editable item numeric columns numeric before save/export."""
    out = df.copy() if isinstance(df, pd.DataFrame) else pd.DataFrame()
    for col in EDITOR_NUMERIC_COLUMNS:
        if col not in out.columns:
            out[col] = 0.0
        if col in TAX_RATE_FIELDS:
            out[col] = out[col].apply(normalize_tax_rate_close_call)
        else:
            out[col] = out[col].apply(limit_decimal_places)
        out[col] = pd.to_numeric(out[col], errors="coerce").fillna(0.0).astype(float)
    return out

def editor_dataframes_equal(left: pd.DataFrame, right: pd.DataFrame) -> bool:
    """Stable equality check for deciding whether to commit data_editor output."""
    if not isinstance(left, pd.DataFrame) or not isinstance(right, pd.DataFrame):
        return False
    left_norm = left.reset_index(drop=True).fillna("").astype(str)
    right_norm = right.reset_index(drop=True).fillna("").astype(str)
    return left_norm.equals(right_norm)

def apply_data_editor_state(base_df: pd.DataFrame, editor_state) -> pd.DataFrame:
    """Apply Streamlit data_editor edited/added/deleted row state to a base df."""
    if isinstance(editor_state, pd.DataFrame):
        return coerce_numeric_items_df(editor_state)
    if not isinstance(editor_state, dict):
        return coerce_numeric_items_df(base_df)

    out = base_df.copy() if isinstance(base_df, pd.DataFrame) else pd.DataFrame()

    for row_idx, updates in (editor_state.get("edited_rows") or {}).items():
        try:
            idx = int(row_idx)
        except (TypeError, ValueError):
            continue
        if idx < 0 or idx >= len(out) or not isinstance(updates, dict):
            continue
        for col, value in updates.items():
            if col in out.columns:
                out.at[out.index[idx], col] = value

    deleted_rows = sorted(
        [int(i) for i in (editor_state.get("deleted_rows") or []) if str(i).lstrip("-").isdigit()],
        reverse=True,
    )
    if deleted_rows:
        drop_labels = [out.index[i] for i in deleted_rows if 0 <= i < len(out)]
        out = out.drop(index=drop_labels)

    added_rows = editor_state.get("added_rows") or []
    if added_rows:
        out = pd.concat([out, pd.DataFrame(added_rows)], ignore_index=True)

    return coerce_numeric_items_df(out.reset_index(drop=True))

def commit_data_editor_state(items_state_key: str, editor_key: str, selected_hash: str) -> None:
    """Commit data_editor deltas to durable session state before rerun."""
    committed = apply_data_editor_state(
        st.session_state.get(items_state_key, pd.DataFrame()),
        st.session_state.get(editor_key),
    )
    st.session_state[items_state_key] = committed
    live_edited_data = deepcopy(st.session_state.batch_results[selected_hash].get("edited_data", {}) or {})
    live_edited_data["Itemized Data"] = committed.to_dict("records")
    st.session_state.batch_results[selected_hash]["edited_data"] = live_edited_data

def limit_invoice_decimals(data: dict) -> dict:
    """Apply the 3-decimal display cap only to known numeric invoice fields."""
    for field in SUMMARY_NUMERIC_FIELDS:
        if field in data:
            if field in TAX_RATE_FIELDS:
                data[field] = normalize_tax_rate_close_call(data.get(field))
            else:
                data[field] = limit_decimal_places(data.get(field))

    for item in data.get("Itemized Data", []) or []:
        if not isinstance(item, dict):
            continue
        for field in ITEM_NUMERIC_FIELDS:
            if field in item:
                if field in TAX_RATE_FIELDS:
                    item[field] = normalize_tax_rate_close_call(item.get(field))
                else:
                    item[field] = limit_decimal_places(item.get(field))
    return data

def normalize_date(date_str, currency=None) -> str:
    """
    Normalize various date formats:
    - Full dates (day-month-year) β†’ dd-MMM-yyyy (e.g., 01-Jan-2025)
    - Month-year only β†’ MMM-yyyy (e.g., Aug-2025)
    
    Currency-aware parsing:
    - If currency is USD and date is numeric format (11/09/2025, 11-09-2025), 
      treat as MM/DD/YYYY
    - For text formats (06-Nov-2025, December 6, 2025), parse normally
    
    Returns empty string if date cannot be parsed
    """
    if not date_str or date_str == "":
        return ""

    if isinstance(date_str, str):
        date_str = date_str.strip()
        if date_str == "":
            return ""
        
        # EXTRA CLEANING: Replace various unicode spaces and clean up
        # Non-breaking space, thin space, etc. β†’ regular space
        date_str = re.sub(r'[\u00A0\u2000-\u200B\u202F\u205F\u3000]', ' ', date_str)
        # Remove zero-width characters
        date_str = re.sub(r'[\u200B-\u200D\uFEFF]', '', date_str)
        # Normalize multiple spaces to single space
        date_str = re.sub(r'\s+', ' ', date_str).strip()

    # Clean ordinal suffixes FIRST (1st, 2nd, 3rd, 4th, 06th, etc.)
    cleaned_date = date_str
    if isinstance(date_str, str):
        # Handle ordinals: "06th December 2025" β†’ "06 December 2025"
        # Also handles: "December 6th, 2025" β†’ "December 6, 2025"
        cleaned_date = re.sub(r'(\d+)(st|nd|rd|th)\b', r'\1', date_str, flags=re.IGNORECASE)
        # Strip leading day-of-week names: "Friday 26 June 2026" β†’ "26 June 2026"
        cleaned_date = re.sub(
            r'^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday'
            r'|Mon|Tue|Wed|Thu|Fri|Sat|Sun)[,\s]+',
            '', cleaned_date, flags=re.IGNORECASE
        ).strip()

    # Check if date is NUMERIC format (contains only digits and separators)
    # Pattern: XX/XX/XXXX, XX-XX-XXXX, XX.XX.XXXX (with 2 or 4 digit year)
    is_numeric_format = bool(re.match(r'^\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}$', cleaned_date))
    
    # US FORMAT PRIORITY: If currency is USD and date is numeric, try MM/DD/YYYY first
    if currency and currency.upper() == 'USD' and is_numeric_format:
        us_formats = [
            "%m/%d/%Y",           # 01/15/2025
            "%m-%d-%Y",           # 01-15-2025
            "%m.%d.%Y",           # 01.15.2025
            "%m/%d/%y",           # 01/15/25
            "%m-%d-%y",           # 01-15-25
            "%m.%d.%y",           # 01.15.25
        ]
        for fmt in us_formats:
            try:
                parsed_date = datetime.strptime(cleaned_date, fmt)
                return parsed_date.strftime("%d-%b-%Y")
            except (ValueError, TypeError):
                continue

    # FULL DATE FORMATS (day-month-year) - standard parsing
    full_date_formats = [
        # ISO formats (4-digit year) - these are unambiguous
        "%Y-%m-%d",           # 2025-01-15
        "%Y/%m/%d",           # 2025/01/15
        "%Y.%m.%d",           # 2025.01.15
        "%Y %m %d",           # 2025 01 15
        "%Y%m%d",             # 20250115 (compact)
        
        # European formats with full month names (4-digit year) - UNAMBIGUOUS
        "%d %B, %Y",          # 15 December, 2025 (with comma)
        "%d %b, %Y",          # 15 Dec, 2025 (with comma)
        "%d %B %Y",           # 15 January 2025
        "%d %b %Y",           # 15 Jan 2025
        "%d-%B-%Y",           # 15-January-2025
        "%d-%b-%Y",           # 15-Jan-2025
        "%d.%B.%Y",           # 15.January.2025
        "%d.%b.%Y",           # 15.Jan.2025
        "%d/%B/%Y",           # 15/January/2025
        "%d/%b/%Y",           # 15/Jan/2025
        
        # US formats with full month names (4-digit year) - UNAMBIGUOUS
        "%B %d, %Y",          # January 15, 2025
        "%b %d, %Y",          # Jan 15, 2025
        "%B %d %Y",           # January 15 2025
        "%b %d %Y",           # Jan 15 2025
        "%B-%d-%Y",           # January-15-2025
        "%b-%d-%Y",           # Jan-15-2025
        "%B %d,%Y",           # January 15,2025 (no space after comma)
        "%b %d,%Y",           # Jan 15,2025
        
        # European formats - Day first (4-digit year)
        "%d-%m-%Y",           # 15-01-2025
        "%d/%m/%Y",           # 15/01/2025
        "%d.%m.%Y",           # 15.01.2025
        "%d %m %Y",           # 15 01 2025
        
        # US formats - Month first (4-digit year) - only if not USD or not numeric
        "%m-%d-%Y",           # 01-15-2025
        "%m/%d/%Y",           # 01/15/2025
        "%m.%d.%Y",           # 01.15.2025
        "%m %d %Y",           # 01 15 2025
        
        # European formats with 2-digit year - Day first
        "%d-%m-%y",           # 15-01-25
        "%d/%m/%y",           # 15/01/25
        "%d.%m.%y",           # 15.01.25
        "%d %m %y",           # 15 01 25
        
        # US formats with 2-digit year - Month first
        "%m-%d-%y",           # 01-15-25
        "%m/%d/%y",           # 01/15/25
        "%m.%d.%y",           # 01.15.25
        "%m %d %y",           # 01 15 25
        
        # ISO with 2-digit year
        "%y-%m-%d",           # 25-01-15
        "%y/%m/%d",           # 25/01/15
        "%y.%m.%d",           # 25.01.15
        "%y %m %d",           # 25 01 15
        
        # Compact formats with 2-digit year
        "%y%m%d",             # 250115
        "%d%m%y",             # 150125
        "%m%d%y",             # 011525
        
        # European formats with abbreviated month (2-digit year) - UNAMBIGUOUS
        "%d %B, %y",          # 15 December, 25 (with comma)
        "%d %b, %y",          # 15 Dec, 25 (with comma)
        "%d-%b-%y",           # 15-Jan-25
        "%d/%b/%y",           # 15/Jan/25
        "%d.%b.%y",           # 15.Jan.25
        "%d %b %y",           # 15 Jan 25
        "%d-%B-%y",           # 15-January-25
        "%d/%B/%y",           # 15/January/25
        
        # US formats with abbreviated month (2-digit year) - UNAMBIGUOUS
        "%b %d, %y",          # Jan 15, 25
        "%b %d %y",           # Jan 15 25
        "%B %d, %y",          # January 15, 25
        "%B %d %y",           # January 15 25
        "%b-%d-%y",           # Jan-15-25
        "%B-%d-%y",           # January-15-25
        
        # Compact 8-digit formats
        "%d%m%Y",             # 15012025
        "%m%d%Y",             # 01152025
        "%Y%d%m",             # 20251501
    ]

    # Try full date formats β†’ output as dd-MMM-yyyy
    for fmt in full_date_formats:
        try:
            parsed_date = datetime.strptime(cleaned_date, fmt)
            return parsed_date.strftime("%d-%b-%Y")
        except (ValueError, TypeError):
            continue

    # DAY-MONTH ONLY (no year) β€” infer current year: "8 July" β†’ "08-Jul-<year>"
    _cur_year = datetime.now().year
    for _fmt in ("%d %B", "%d %b", "%B %d", "%b %d"):
        try:
            parsed_date = datetime.strptime(cleaned_date, _fmt).replace(year=_cur_year)
            return parsed_date.strftime("%d-%b-%Y")
        except (ValueError, TypeError):
            continue

    # MONTH-YEAR ONLY FORMATS - output as MMM-yyyy
    month_year_formats = [
        # Full month name with year
        "%B %Y",              # August 2025
        "%b %Y",              # Aug 2025
        "%B, %Y",             # August, 2025
        "%b, %Y",             # Aug, 2025
        "%B-%Y",              # August-2025
        "%b-%Y",              # Aug-2025
        "%B/%Y",              # August/2025
        "%b/%Y",              # Aug/2025
        
        # Numeric month-year (4-digit year)
        "%m/%Y",              # 08/2025
        "%m-%Y",              # 08-2025
        "%m.%Y",              # 08.2025
        "%m %Y",              # 08 2025
        "%Y-%m",              # 2025-08
        "%Y/%m",              # 2025/08
        "%Y.%m",              # 2025.08
        "%Y %m",              # 2025 08
        
        # Numeric month-year (2-digit year)
        "%m/%y",              # 08/25
        "%m-%y",              # 08-25
        "%m.%y",              # 08.25
        "%m %y",              # 08 25
        "%y-%m",              # 25-08
        "%y/%m",              # 25/08
        
        # Full month name with 2-digit year
        "%B %y",              # August 25
        "%b %y",              # Aug 25
        "%B-%y",              # August-25
        "%b-%y",              # Aug-25
    ]

    # Try month-year formats β†’ output as MMM-yyyy (no day)
    for fmt in month_year_formats:
        try:
            parsed_date = datetime.strptime(cleaned_date, fmt)
            return parsed_date.strftime("%b-%Y")  # Aug-2025 format
        except (ValueError, TypeError):
            continue

    # If no format matched, return empty string
    return ""

def parse_date_to_object(date_str, currency=None):
    """
    Parse a date string to a datetime.date object for date_input widget
    Currency-aware: If USD and numeric format, treat as MM/DD/YYYY
    Returns None if date cannot be parsed
    """
    if not date_str or date_str == "":
        return None

    if isinstance(date_str, str):
        date_str = date_str.strip()
        if date_str == "":
            return None
        
        # EXTRA CLEANING: Replace various unicode spaces and clean up
        date_str = re.sub(r'[\u00A0\u2000-\u200B\u202F\u205F\u3000]', ' ', date_str)
        date_str = re.sub(r'[\u200B-\u200D\uFEFF]', '', date_str)
        date_str = re.sub(r'\s+', ' ', date_str).strip()

    # Clean ordinal suffixes FIRST (1st, 2nd, 3rd, 4th, 06th, etc.)
    cleaned_date = str(date_str)
    if isinstance(date_str, str):
        cleaned_date = re.sub(r'(\d+)(st|nd|rd|th)\b', r'\1', date_str, flags=re.IGNORECASE)

    # Check if date is NUMERIC format (contains only digits and separators)
    is_numeric_format = bool(re.match(r'^\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}$', cleaned_date))
    
    # US FORMAT PRIORITY: If currency is USD and date is numeric, try MM/DD/YYYY first
    if currency and currency.upper() == 'USD' and is_numeric_format:
        us_formats = [
            "%m/%d/%Y",           # 01/15/2025
            "%m-%d-%Y",           # 01-15-2025
            "%m.%d.%Y",           # 01.15.2025
            "%m/%d/%y",           # 01/15/25
            "%m-%d-%y",           # 01-15-25
            "%m.%d.%y",           # 01.15.25
        ]
        for fmt in us_formats:
            try:
                parsed_date = datetime.strptime(cleaned_date, fmt)
                return parsed_date.date()
            except (ValueError, TypeError):
                continue

    # Standard formats
    formats = [
        # ISO formats (4-digit year)
        "%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d", "%Y %m %d", "%Y%m%d",
        
        # Text month formats with comma - MUST BE FIRST for "06 December, 2025"
        "%d %B, %Y", "%d %b, %Y",          # 06 December, 2025 / 06 Dec, 2025
        
        # Text month formats - UNAMBIGUOUS
        "%d %B %Y", "%d %b %Y", "%d-%B-%Y", "%d-%b-%Y",
        "%d.%B.%Y", "%d.%b.%Y", "%d/%B/%Y", "%d/%b/%Y",
        "%B %d, %Y", "%b %d, %Y", "%B %d %Y", "%b %d %Y",
        "%B-%d-%Y", "%b-%d-%Y", "%B %d,%Y", "%b %d,%Y",
        
        # European formats - Day first
        "%d-%m-%Y", "%d/%m/%Y", "%d.%m.%Y", "%d %m %Y",
        "%d-%m-%y", "%d/%m/%y", "%d.%m.%y", "%d %m %y",
        
        # US formats - Month first
        "%m-%d-%Y", "%m/%d/%Y", "%m.%d.%Y", "%m %d %Y",
        "%m-%d-%y", "%m/%d/%y", "%m.%d.%y", "%m %d %y",
        
        # ISO with 2-digit year
        "%y-%m-%d", "%y/%m/%d", "%y.%m.%d", "%y %m %d",
        
        # Compact formats
        "%y%m%d", "%d%m%y", "%m%d%y", "%d%m%Y", "%m%d%Y", "%Y%d%m",
        
        # Text month with 2-digit year (with comma)
        "%d %B, %y", "%d %b, %y",          # 06 December, 25 / 06 Dec, 25
        "%d-%b-%y", "%d/%b/%y", "%d.%b.%y", "%d %b %y",
        "%d-%B-%y", "%d/%B/%y",
        "%b %d, %y", "%b %d %y", "%B %d, %y", "%B %d %y",
        "%b-%d-%y", "%B-%d-%y",
        
        # Month-year only
        "%B %Y", "%b %Y", "%B, %Y", "%b, %Y",
        "%B-%Y", "%b-%Y", "%B/%Y", "%b/%Y",
        "%m/%Y", "%m-%Y", "%m.%Y", "%m %Y",
        "%Y-%m", "%Y/%m", "%Y.%m", "%Y %m",
        "%m/%y", "%m-%y", "%m.%y", "%m %y",
        "%y-%m", "%y/%m",
        "%B %y", "%b %y", "%B-%y", "%b-%y",
    ]

    for fmt in formats:
        try:
            parsed_date = datetime.strptime(cleaned_date, fmt)
            return parsed_date.date()
        except (ValueError, TypeError):
            continue

    return None


# =============================================================================
# vLLM Inference β€” MULTI-IMAGE SINGLE REQUEST
# =============================================================================
def _encode_page(page: Image.Image, page_idx: int, max_dim: int = MAX_DIMENSION_PER_PAGE):
    orig_w, orig_h = page.size
    api_img = page.copy()
    if orig_w > max_dim or orig_h > max_dim:
        ratio    = min(max_dim / orig_w, max_dim / orig_h)
        new_size = (int(orig_w * ratio), int(orig_h * ratio))
        api_img  = api_img.resize(new_size, Image.Resampling.LANCZOS)
    else:
        new_size = (orig_w, orig_h)
    buf = BytesIO()
    api_img.save(buf, format="PNG", optimize=True)
    b64      = base64.b64encode(buf.getvalue()).decode("utf-8")
    data_url = f"data:image/png;base64,{b64}"
    return data_url, (orig_w, orig_h), new_size


def run_inference_vllm(images: List[Image.Image]) -> str | None:
    EXTRACTION_PROMPT = """Extract structured data from the provided invoice image(s). Return a single JSON object with three sections: header, items, summary.
## Output Schema
Return this exact structure. Use empty string "" for any field not found.
json
{
  "header": {
    "invoice_no": "",
    "po_no": "",
    "invoice_date": "",
    "payment_terms": "",
    "due_date": "",
    "sender_name": "",
    "sender_addr": "",
    "tax_id": "",
    "rcpt_name": "",
    "rcpt_addr": "",
    "bank_iban": "",
    "bank_name": "",
    "bank_acc_no": "",
    "bank_routing": "",
    "bank_swift": "",
    "bank_acc_name": "",
    "bank_branch": ""
  },
  "items": [
    {
      "service_name": "",
      "service_start_date": "",
      "service_end_date": "",
      "descriptions": "",
      "SKU": "",
      "quantity": "",
      "unit_price": "",
      "amount": "",
      "discount_rate_per_item": "",
      "discount_amount_per_item": "",
      "tax_rate_per_item": "",
      "tax_amount_per_item": "",
      "line_total": ""
    }
  ],
  "summary": {
    "subtotal": "",
    "tax_rate": "",
    "tax_amount": "",
    "discount_rate": "",
    "total_discount_amount": "",
    "total_amount": "",
    "currency": ""
  }
}
## Core Rules
1. EXTRACT ONLY WHAT IS EXPLICITLY VISIBLE. Never compute, derive, infer totals, or fill missing values via arithmetic. The following format normalizations and explicit-data operations ARE permitted:
   - Bracketed amounts β†’ negative: (100.00) β†’ "-100.00".
   - Date ranges β†’ expanded to full start/end dates using the invoice year.
   - Language normalization of payment terms β†’ English.
   - Summing multiple tax AMOUNTS shown separately into one combined amount.
   - Summing multiple discount AMOUNTS shown separately into one combined amount.
   - Default quantity to "1.00" when unit_price and amount are both shown and equal, with no quantity printed.
   - Setting tax to "0.00" when "No VAT" / "VAT Exempt" is explicitly stated, OR when a tax rate is shown but tax amount is blank AND subtotal equals total as printed.
2. Return "" for any field not present or not clearly identifiable.
3. PRESERVE ORIGINAL FORMATTING for numbers (commas, decimals) and dates (except for date-range expansion noted above). For tax_rate and discount_rate, preserve exactly as printed including any % symbol.
4. STRIP CURRENCY SYMBOLS from all amount/price fields. Place currency code (USD, EUR, GBP, INR, etc.) only in summary.currency. If multiple currencies appear, use the currency of total_amount. If no currency is shown anywhere on the invoice, set summary.currency to "".
5. MULTI-PAGE: Merge all pages into one JSON object. Extract every line item as printed β€” do not deduplicate. Only skip a row if it is clearly a continuation header (e.g., the row repeats the table column titles like "Description / Qty / Price").
6. NO DUPLICATION ACROSS SCHEMA SECTIONS: If a value appears in the line items area of the invoice, place it only in the items array of the schema. If it appears in the summary/totals area (the section at the bottom showing subtotal, tax, discount, and total β€” separate from the itemized table), place it only in the summary object of the schema. Do not copy the same value into both unless the invoice explicitly prints it in both areas.
7. OUTPUT ONLY THE JSON. No preamble, no markdown fences, no explanation.
8. INCLUDE ALL LINE ITEMS, even those with a zero amount, zero quantity, or negative amount. Never skip a line item because its value is 0 or negative. This applies equally to credit notes and adjustments. Negative quantities, if printed, are extracted as-is (preserve the negative sign).
9. NO LINE ITEMS: If the invoice shows no individual line items (e.g., a flat-fee invoice with only a total), return an empty array: "items": [].
10. CONFLICTING VALUES: If the invoice shows two different totals (e.g., "Total" and "Amount Due"), prefer the value labeled as the final payable amount ("Amount Due", "Balance Due", "Total Payable", "Grand Total").
## Field Rules
### Sender & Recipient
1.sender_name: The invoicing company/person. Prefer company name over person name.
2.sender_addr: The full address of the invoicing entity, wherever it appears on the invoice.
3.tax_id: Always the SENDER's tax ID / VAT number. Never the recipient's.
4.rcpt_name: The name of the recipient, customer, or entity being billed.
5.rcpt_addr: The address of the recipient, customer, or entity being billed.
### PO Number
1.po_no: Extract if a single PO number is shown. If the same PO number appears multiple times on the invoice (e.g., header and footer), extract it once. If multiple DISTINCT PO numbers are present, return "".
### Bank Details
1.Prefer the bank account matching the invoice currency (USD invoice β†’ USD account).
2.If no currency-matching account exists, extract the only available account.
3.If multiple non-matching accounts exist with no currency-matching account, return "" for all bank fields.
4.bank_acc_name: The name of the account holder. It may also appear in phrases such as β€œCheques should be payable to” or β€œRemittance should be payable to.” Extract the mentioned company/entity name as the bank_acc_name.
### Dates
5.Preserve the original date format exactly as printed.
6.Date range exception: When a service period is shown as a range (e.g., "Feb 1-3"), expand to two full dates: service_start_date: "Feb 1 2026", service_end_date: "Feb 3 2026". Use the invoice year if the range omits a year.
7.due_date: If multiple due dates, extract only the first. If payment terms are "due on receipt" / "due on presentation" / "immediate", set due_date = invoice_date.
8.payment_terms: Normalize to English ("30 jours" β†’ "30 days", "60 gg df" β†’ "60 days").
### Descriptions
1.service_name: A short label, product name, or service title (e.g., "Consulting", "Web Hosting", "Premium Plan").
2.descriptions: The full detailed description text of the line item.
3.If the line item shows both a short label and a longer expanded text β†’ put the short label in service_name and the longer text in descriptions.
4.If only one text is available for the line item β†’ place it in descriptions and leave service_name as "".
5.If a SKU/code appears together with descriptive text (e.g., "SKU-12345 β€” Premium Web Hosting") β†’ put the SKU in SKU, the descriptive portion in descriptions, and leave service_name as "" unless a separate short label also exists.
6.Do not extract handwritten annotations or stamps unless they are clearly legible and printed-quality. When in doubt, extract only the printed text.
### Amounts, Tax & Discounts
1.Preserve original number formatting (commas, decimals) exactly as printed. Do not reinterpret decimal separators β€” preserve as written (European 1.234,56 stays 1.234,56; US 1,234.56 stays 1,234.56).
2.Bracketed amounts are negative: (100.00) β†’ "-100.00".
3."No VAT" / "VAT Exempt" β†’ set relevant tax field to "0.00".
4.Tax rate shown but tax amount blank AND subtotal equals total as printed β†’ tax amount = "0.00".
5.Tax-inclusive pricing: If the invoice states "all prices include VAT" or "tax-inclusive pricing", extract amount as printed without separating tax. Extract summary.tax_amount, summary.tax_rate, tax_rate_per_item, and tax_amount_per_item exactly as printed on the invoice β€” do not attempt to back-calculate.
6.Summing multiple values:
  - Multiple tax AMOUNTS shown separately β†’ sum into one combined amount in the appropriate field.
  - Multiple DISCOUNT AMOUNTS shown separately β†’ sum into one combined amount in the appropriate field.
  - Multiple tax RATES (e.g., 5% CGST + 12% SGST) β†’ do NOT sum. Concatenate as printed (e.g., "5% + 12%") or extract the dominant rate as printed. Never produce a summed rate like "17%".
7.0Gross vs. Net amount columns: If both gross and net per-line amounts are shown, use the NET (pre-tax) amount as amount.
8.Discount/tax as a line item: If discount or tax appears as a row in the line items table β€” identified by labels such as "Discount", "Rebate", "Tax", "VAT", "Adjustment", or by being a negative-value row with no quantity/unit price β€” create a separate entry in the items array. Populate ONLY descriptions, the relevant discount/tax fields (discount_rate_per_item, discount_amount_per_item, tax_rate_per_item, tax_amount_per_item), and line_total. Leave quantity, unit_price, and amount as "".
9.Discount/tax in the totals/summary area: Place only in the summary object of the schema. Do not duplicate into the items array.
### Quantity & Unit Price
1.If unit_price and amount are shown and equal but no quantity is printed β†’ quantity: "1.00".
2.If the invoice uses alternate labels for quantity (e.g., impressions, units, hours, sessions, clicks) and unit price (e.g., CPM, rate, cost per unit), map them to quantity and unit_price respectively.
3.If both a standard quantity and an alternate metric are shown, extract the standard quantity.
4.Negative quantities (e.g., on credit notes) are preserved as-is with the negative sign.
### Line Total
line_total: Extract ONLY if ALL these conditions are met:
  1. The invoice explicitly prints a dedicated line total column or value for the row.
  2. The invoice has NO separate per-line tax column or per-line tax amount anywhere.
  3. The invoice has NO separate per-line discount column or per-line discount amount anywhere.
If any per-line tax or discount column exists anywhere on the invoice β†’ set line_total to "" for ALL rows.
If no line total column exists on the invoice β†’ line_total = ""."""

    if not images:
        st.error("No images provided to run_inference_vllm.")
        return None

    if len(images) > MAX_PAGES_PER_REQUEST:
        st.warning(
            f"Invoice has {len(images)} pages β€” only the first "
            f"{MAX_PAGES_PER_REQUEST} will be sent per the request limit."
        )
        images = images[:MAX_PAGES_PER_REQUEST]

    try:
        image_content_blocks: List[dict] = []
        total_b64_bytes = 0
        resize_info     = []

        for idx, page in enumerate(images):
            data_url, orig_size, new_size = _encode_page(page, idx)
            total_b64_bytes += len(data_url)
            if orig_size != new_size:
                resize_info.append(
                    f"Page {idx+1}: {orig_size[0]}Γ—{orig_size[1]} β†’ {new_size[0]}Γ—{new_size[1]}"
                )
            image_content_blocks.append({"type": "image_url", "image_url": {"url": data_url}})

        if resize_info:
            st.info("Resized for API payload:\n" + "\n".join(resize_info))

        total_payload_mb = total_b64_bytes / (1024 * 1024)
        if total_payload_mb > MAX_TOTAL_PAYLOAD_MB:
            st.warning(
                f"Large multi-page payload ({total_payload_mb:.1f} MB across "
                f"{len(images)} page(s)). This may be slow or time-out."
            )
        else:
            st.info(f"Sending {len(images)} page(s) in one request (payload β‰ˆ {total_payload_mb:.2f} MB).")

        user_content = image_content_blocks + [
            {
                "type": "text",
                "text": (
                    f"The {len(images)} image(s) above are all pages of the same invoice "
                    f"(page 1 through page {len(images)}).\n"
                    "Extract invoice data from ALL pages combined into a single JSON object."
                )
            }
        ]

        payload = {
            "model": MODEL_NAME,
            "messages": [
                {"role": "system", "content": EXTRACTION_PROMPT},
                {"role": "user",   "content": user_content}
            ],
            "temperature": 0,
            "max_tokens":  10000
        }

        headers = {
            "Authorization": f"Bearer {VLLM_API_KEY}",
            "Content-Type":  "application/json"
        }

        response = requests.post(
            f"{POD_URL}/v1/chat/completions",
            headers=headers,
            json=payload,
            timeout=600
        )

        if response.status_code == 200:
            result = response.json()
            return result["choices"][0]["message"]["content"]
        else:
            st.error(f"❌ API Error {response.status_code}")
            try:
                st.json(response.json())
            except Exception:
                st.code(response.text)
            return None

    except Exception as e:
        st.error(f"Error calling vLLM: {str(e)}")
        return None


# -----------------------------
# JSON Parser + postprocessing mapper from code #1
# -----------------------------
def parse_vllm_json(raw_json_text):
    """Parse vLLM JSON output into:
    1) raw_data: untouched parsed JSON object
    2) mapped_data: cleaned structured format for validation
    """
    try:
        text_to_parse = raw_json_text.strip()

        if text_to_parse.startswith("```json"):
            text_to_parse = text_to_parse[7:]
        elif text_to_parse.startswith("```"):
            text_to_parse = text_to_parse[3:]
        if text_to_parse.endswith("```"):
            text_to_parse = text_to_parse[:-3]
        text_to_parse = text_to_parse.strip()

        raw_data = json.loads(text_to_parse)

        # Support both flat output and nested output
        header = raw_data.get("header", raw_data)
        summary = raw_data.get("summary", raw_data)
        items = raw_data.get("items", [])

        currency = summary.get("currency", header.get("currency", ""))

        def clean_amount(value):
            return clean_float(value, currency)

        mapped = {
            "Invoice Number": header.get("invoice_no", ""),
            "PO Number": header.get("po_no", ""),
            "Invoice Date": normalize_date(header.get("invoice_date", ""), currency),
            "Payment Terms": header.get("payment_terms", ""),
            "Due Date": normalize_date(header.get("due_date", ""), currency),
            "test_due_date_origin": str(header.get("test_due_date_origin", "") or "").strip(),
            "test_entity_country": str(header.get("test_entity_country", "") or "").strip(),
            "Sender Name": header.get("sender_name", ""),
            "Sender Address": header.get("sender_addr", ""),
            "Tax ID": header.get("tax_id", ""),
            "Sender": {
                "Name": header.get("sender_name", ""),
                "Address": header.get("sender_addr", "")
            },
            "Recipient Name": header.get("rcpt_name", ""),
            "Recipient Address": header.get("rcpt_addr", ""),
            "Recipient": {
                "Name": header.get("rcpt_name", ""),
                "Address": header.get("rcpt_addr", "")
            },
            "Bank Details": {
                "bank_iban": header.get("bank_iban", ""),
                "bank_name": header.get("bank_name", ""),
                "bank_account_number": header.get("bank_acc_no", ""),
                "bank_routing": header.get("bank_routing", ""),
                "bank_swift": header.get("bank_swift", ""),
                "bank_acc_name": header.get("bank_acc_name", ""),
                "bank_branch": header.get("bank_branch", "")
            },
            "Subtotal": clean_amount(summary.get("subtotal", "0")),
            "Tax Percentage": clean_tax_percentage(summary.get("tax_rate", "0")),
            "Total Tax": clean_amount(summary.get("tax_amount", "0")),
            "Discount Rate": clean_float(summary.get("discount_rate", "0"), currency),
            "Total Discount Amount": clean_amount(summary.get("total_discount_amount", "0")),
            "Total Amount": clean_amount(summary.get("total_amount", "0")),
            "Currency": currency,
            "Itemized Data": []
        }

        for item in items:
            raw_tax = item.get("tax_amount_per_item", item.get("tax", ""))
            raw_line_total = item.get("line_total", item.get("Line_total", ""))
            tax_amount = clean_amount(raw_tax) if raw_tax != "" else 0.0
            line_total = clean_amount(raw_line_total) if raw_line_total != "" else ""

            mapped["Itemized Data"].append({
                "Service Name": item.get("service_name", "") or item.get("Service_name", ""),
                "Service Start Date": item.get("service_start_date", ""),
                "Service End Date": item.get("service_end_date", ""),
                "Description": item.get("descriptions", ""),
                "SKU": item.get("SKU", ""),
                "GL Account": str(item.get("gl_account", "") or "").strip(),
                "Region Code Hint": str(item.get("region_code_hint", "") or "").strip(),
                "Quantity": clean_quantity(item.get("quantity", "0")),
                "Unit Price": clean_amount(item.get("unit_price", "0")),
                "Amount": clean_amount(item.get("amount", "0")),
                "Discount Rate Per Item": clean_float(item.get("discount_rate_per_item", "0"), currency),
                "Discount Amount Per Item": clean_amount(item.get("discount_amount_per_item", "0")),
                "Tax Rate Per Item": clean_tax_percentage(item.get("tax_rate_per_item", "0")),
                "Tax Amount Per Item": tax_amount,
                "Tax_Raw": raw_tax,
                "Tax": tax_amount,
                "Line Total": line_total,
                "line_total": raw_line_total
            })

        return raw_data, mapped

    except Exception as e:
        st.error(f"JSON parse error: {str(e)}")
        return None, None




# -----------------------------
# Postprocessing logic from code #1
# -----------------------------
def validate_and_calculate_taxes(structured_data):
    """
    Validate and, when needed, calculate per-item tax values.
    Supports both the legacy item keys:
      - Tax
      - Line Total
    and the new item keys:
      - Tax Amount Per Item
      - Tax Rate Per Item
      - Discount Amount Per Item
      - Discount Rate Per Item
      - line_total
    """

    subtotal = structured_data.get("Subtotal", 0.0)
    total_amount = structured_data.get("Total Amount", 0.0)
    model_tax_rate = structured_data.get("Tax Percentage", 0.0)
    model_tax_amount = structured_data.get("Total Tax", 0.0)
    items = structured_data.get("Itemized Data", [])

    def get_raw_tax_value(item):
        if not isinstance(item, dict):
            return ""
        raw = item.get("Tax_Raw", "")
        if raw != "":
            return raw
        val = item.get("Tax Amount Per Item", item.get("Tax", ""))
        return "" if val in ("", None) else val

    def set_item_tax_value(item, value):
        item["Tax Amount Per Item"] = value
        item["Tax"] = value

    def set_item_line_total(item, value):
        item["Line Total"] = value
        item["line_total"] = value

    if subtotal >= total_amount or subtotal <= 0:
        structured_data["tax_validated"] = False
        structured_data["tax_skip_reason"] = "No tax detected"
        return structured_data

    if model_tax_rate > 0 and model_tax_amount == 0.0:
        structured_data["tax_validated"] = False
        structured_data["tax_skip_reason"] = "Tax rate exists but tax amount is 0"
        return structured_data

    taxable_items = []
    non_taxable_items = []

    for item in items:
        amount = item.get("Amount", 0.0)
        raw_tax_value = get_raw_tax_value(item)

        if amount == 0.0:
            set_item_tax_value(item, 0.0)
            set_item_line_total(item, 0.0)
            non_taxable_items.append(item)
            continue

        is_empty = False
        is_explicitly_zero = False

        if isinstance(raw_tax_value, str):
            cleaned = raw_tax_value.strip()
            if cleaned == "":
                is_empty = True
            else:
                try:
                    cleaned_value = float(re.sub(r"[^\d\.-]", "", cleaned) or "0")
                    if cleaned_value == 0.0:
                        is_explicitly_zero = True
                except (ValueError, TypeError):
                    pass
        elif raw_tax_value is None or raw_tax_value == "":
            is_empty = True
        elif raw_tax_value == 0 or raw_tax_value == 0.0:
            is_explicitly_zero = True

        if is_empty or is_explicitly_zero:
            set_item_tax_value(item, 0.0)
            set_item_line_total(item, amount)
            non_taxable_items.append(item)
            continue

        taxable_items.append(item)

    authoritative_rate = None
    authority_source = None

    if taxable_items:
        total_taxable_amount = sum(item.get("Amount", 0.0) for item in taxable_items)
        if total_taxable_amount <= 0:
            structured_data["tax_validated"] = False
            structured_data["tax_skip_reason"] = "No taxable items with valid amounts"
            return structured_data

        if model_tax_rate > 0:
            expected_tax_from_rate = total_taxable_amount * (model_tax_rate / 100)
            expected_total_from_rate = subtotal + expected_tax_from_rate
            error_from_rate = abs(expected_total_from_rate - total_amount)
        else:
            error_from_rate = float("inf")

        if model_tax_amount > 0:
            calculated_rate_from_amount = (model_tax_amount / total_taxable_amount) * 100
            expected_total_from_amount = subtotal + model_tax_amount
            error_from_amount = abs(expected_total_from_amount - total_amount)
        else:
            error_from_amount = float("inf")

        if model_tax_rate > 0 or model_tax_amount > 0:
            if error_from_rate <= error_from_amount:
                authoritative_rate = round(model_tax_rate, 4)
                authority_source = "tax_rate"
            else:
                authoritative_rate = round(calculated_rate_from_amount, 4)
                authority_source = "tax_amount"
        else:
            structured_data["tax_validated"] = False
            structured_data["tax_skip_reason"] = "No tax rate or amount provided"
            return structured_data
    else:
        structured_data["tax_validated"] = False
        structured_data["tax_skip_reason"] = "No taxable items found"
        return structured_data

    calculated_total_tax = 0.0
    if authoritative_rate is not None:
        for item in taxable_items:
            amount = item.get("Amount", 0.0)
            # Keep the model's extracted tax amount β€” taxable_items are items
            # where the model already provided a non-empty, non-zero tax value.
            existing_tax = round(float(clean_float(item.get("Tax Amount Per Item", 0.0))), 2)
            calculated_total_tax += existing_tax
            set_item_line_total(item, round(amount + existing_tax, 2))

    if not model_tax_rate:  # only fill Tax Percentage if model left it empty
        structured_data["Tax Percentage"] = authoritative_rate
    structured_data["Total Tax"] = round(calculated_total_tax, 2)
    structured_data["Total Amount"] = round(subtotal + calculated_total_tax, 2)
    structured_data["tax_validated"] = True
    structured_data["tax_authority_source"] = authority_source
    structured_data["original_tax_rate"] = model_tax_rate
    structured_data["original_tax_amount"] = model_tax_amount

    return structured_data

from copy import deepcopy

def recalc_display_totals_from_items(invoice_data):
    """
    UI/download-only recalculation.
    subtotal = sum(Amount)
    Line Total = Amount + Discount Amount Per Item + Tax Amount Per Item
    """
    data = deepcopy(invoice_data or {})
    items = data.get("Itemized Data", []) or []

    subtotal = 0.0
    for item in items:
        if not isinstance(item, dict):
            continue

        amount = clean_float(item.get("Amount", 0))
        discount = clean_float(item.get("Discount Amount Per Item", 0))
        tax = clean_float(item.get("Tax Amount Per Item", 0))

        item["Line Total"] = round(amount - abs(discount) + tax, 2)
        subtotal += amount

    data["Subtotal"] = round(subtotal, 2)
    return data

from datetime import datetime, timedelta
import re
def derive_due_date_ui(invoice_date_str, payment_terms, due_date_str):
    """
    UI-only due date post-processing.
    Rules:
    1) If due date already exists, keep it as-is.
    2) If only due date is missing and payment terms exist, derive due date from payment terms.
    3) For immediate/receipt/presentation terms, due date = invoice date.
    4) Never modifies raw model output.
    """

    # Rule 1: if due date is already present, do not touch it
    if due_date_str is not None and str(due_date_str).strip() != "":
        return due_date_str

    # Rule 2: if payment terms are missing, no derivation
    if payment_terms is None or str(payment_terms).strip() == "":
        return ""

    # Parse invoice date using your existing parser
    invoice_date_obj = parse_date_to_object(invoice_date_str)
    if not invoice_date_obj:
        return ""

    terms = str(payment_terms).lower().strip()

    # Immediate / payable-on-receipt style terms
    immediate_phrases = [
        "due upon receipt",
        "upon receipt",
        "immediate",
        "immediately",
        "due on presentation",
        "payable on receipt",
        "payment on receipt",
        "cash on delivery",
        "cod",
        "on receipt",
    ]

    if any(phrase in terms for phrase in immediate_phrases):
        return invoice_date_obj.strftime("%d-%b-%Y")

    # Extract day count from common term patterns
    day_patterns = [
        r"\bnet\s*(\d+)\b",              # Net 30
        r"\bwithin\s*(\d+)\s*days?\b",   # within 30 days
        r"\bdue\s*(\d+)\s*days?\b",      # due 30 days
        r"\b(\d+)\s*days?\b",            # 30 days
        r"\b(\d+)\s*d\b",                # 30d
    ]

    for pattern in day_patterns:
        match = re.search(pattern, terms)
        if match:
            days = int(match.group(1))
            calculated = invoice_date_obj + timedelta(days=days)
            return calculated.strftime("%d-%b-%Y")

    return ""

from copy import deepcopy

def build_display_data_from_raw(raw_data: dict, mapped_data: dict) -> dict:
    """
    UI-only post-processing based on RAW model output.
    - Does not modify raw_data
    - Fills only if the raw field is truly empty
    - Treats 0 / "0" / "0.0" as real values, not blank
    """
    data = deepcopy(mapped_data or {})
    raw_data = raw_data or {}

    def is_blank_raw(v):
        return v is None or (isinstance(v, str) and v.strip() == "")

    def num(v):
        try:
            if v is None or (isinstance(v, str) and v.strip() == ""):
                return None
            return float(clean_float(v))
        except Exception:
            return None

    header = raw_data.get("header", raw_data)
    summary = raw_data.get("summary", raw_data)
    raw_items = raw_data.get("items", []) or []
    display_items = deepcopy(data.get("Itemized Data", []) or [])

    if is_blank_raw(data.get("Invoice Number")):
        data["Invoice Number"] = (
            header.get("invoice_no")
            or raw_data.get("invoice_no")
            or raw_data.get("invoice_no".lower())
            or data.get("Invoice Number", "")
        )

    if is_blank_raw(data.get("PO Number")):
        data["PO Number"] = header.get("po_no") or raw_data.get("po_no") or data.get("PO Number", "")

    # ---- Header-level ----
    if is_blank_raw(header.get("due_date")):
        if is_blank_raw(data.get("Due Date")):
            derived_due = derive_due_date_ui(
                data.get("Invoice Date", ""),
                data.get("Payment Terms", ""),
                ""
            )
            if not is_blank_raw(derived_due):
                data["Due Date"] = derived_due

    # ---- Line items ----
    for idx, raw_item in enumerate(raw_items):
        if idx >= len(display_items):
            display_items.append({})

        item = display_items[idx]
        raw_item = raw_item or {}

        qty = num(item.get("Quantity"))
        unit_price = num(item.get("Unit Price"))
        amount = num(item.get("Amount"))
        disc_rate = num(item.get("Discount Rate Per Item"))
        disc_amt = num(item.get("Discount Amount Per Item"))
        tax_rate = num(item.get("Tax Rate Per Item"))
        tax_amt = num(item.get("Tax Amount Per Item"))

        # Fill only when RAW field is blank
        if is_blank_raw(raw_item.get("amount")) and qty is not None and unit_price is not None:
            item["Amount"] = round(qty * unit_price, 2)
            amount = num(item.get("Amount"))

        if is_blank_raw(raw_item.get("quantity")) and amount is not None and unit_price not in (None, 0):
            item["Quantity"] = round(amount / unit_price, 6)
            qty = num(item.get("Quantity"))

        if is_blank_raw(raw_item.get("unit_price")) and amount is not None and qty not in (None, 0):
            item["Unit Price"] = round(amount / qty, 6)
            unit_price = num(item.get("Unit Price"))

        # Discount
        if is_blank_raw(raw_item.get("discount_amount_per_item")) and disc_rate is not None and amount is not None:
            item["Discount Amount Per Item"] = round(amount * (disc_rate / 100.0), 2)
            disc_amt = num(item.get("Discount Amount Per Item"))

        if is_blank_raw(raw_item.get("discount_rate_per_item")) and disc_amt is not None and amount not in (None, 0):
            item["Discount Rate Per Item"] = round((disc_amt / amount) * 100.0, 4)
            disc_rate = num(item.get("Discount Rate Per Item"))

        # Tax
        taxable_base = None if amount is None else amount - abs(disc_amt if disc_amt is not None else 0.0)

        if is_blank_raw(raw_item.get("tax_amount_per_item")) and taxable_base is not None and tax_rate is not None:
            item["Tax Amount Per Item"] = round(taxable_base * (tax_rate / 100.0), 2)
            tax_amt = num(item.get("Tax Amount Per Item"))

        if is_blank_raw(raw_item.get("tax_rate_per_item")) and taxable_base not in (None, 0) and tax_amt is not None:
            _cr = round((tax_amt / taxable_base) * 100.0, 4)
            _nw = round(_cr)
            item["Tax Rate Per Item"] = float(_nw) if abs(_cr - _nw) <= 0.05 else _cr

        # Line total
        if is_blank_raw(raw_item.get("line_total")):
            amount = num(item.get("Amount"))
            disc_amt = num(item.get("Discount Amount Per Item")) or 0.0
            tax_amt = num(item.get("Tax Amount Per Item")) or 0.0
            if amount is not None:
                item["Line Total"] = round(amount - abs(disc_amt) + tax_amt, 2)

    data["Itemized Data"] = display_items

    # ---- Summary ----
    amounts = []
    discount_amounts = []
    tax_amounts = []
    taxable_bases = []

    for item in display_items:
        if not isinstance(item, dict):
            continue
        a = num(item.get("Amount"))
        d = num(item.get("Discount Amount Per Item")) or 0.0
        t = num(item.get("Tax Amount Per Item")) or 0.0

        if a is not None:
            amounts.append(a)
            taxable_bases.append(a - d)

        if num(item.get("Discount Amount Per Item")) is not None:
            discount_amounts.append(d)

        if num(item.get("Tax Amount Per Item")) is not None:
            tax_amounts.append(t)

    subtotal_calc = round(sum(amounts), 2) if amounts else None
    total_discount_calc = round(sum(discount_amounts), 2) if discount_amounts else None
    total_tax_calc = round(sum(tax_amounts), 2) if tax_amounts else None
    taxable_base_total = round(sum(taxable_bases), 2) if taxable_bases else None

    if is_blank_raw(summary.get("subtotal")) and subtotal_calc is not None:
        data["Subtotal"] = subtotal_calc

    if is_blank_raw(summary.get("total_discount_amount")) and total_discount_calc is not None:
        data["Total Discount Amount"] = total_discount_calc

    if is_blank_raw(summary.get("tax_amount")) and total_tax_calc is not None:
        data["Total Tax"] = total_tax_calc

    if is_blank_raw(summary.get("discount_rate")):
        subtotal_for_rate = num(data.get("Subtotal"))
        total_discount_for_rate = num(data.get("Total Discount Amount"))
        if subtotal_for_rate not in (None, 0) and total_discount_for_rate is not None:
            data["Discount Rate"] = round((total_discount_for_rate / subtotal_for_rate) * 100.0, 4)

    if is_blank_raw(summary.get("tax_rate")):
        total_tax_for_rate = num(data.get("Total Tax"))
        if taxable_base_total not in (None, 0) and total_tax_for_rate is not None:
            data["Tax Percentage"] = round((total_tax_for_rate / taxable_base_total) * 100.0, 4)

    if is_blank_raw(summary.get("total_amount")):
        subtotal_for_total = num(data.get("Subtotal"))
        total_discount_for_total = num(data.get("Total Discount Amount")) or 0.0
        total_tax_for_total = num(data.get("Total Tax")) or 0.0
        if subtotal_for_total is not None:
            data["Total Amount"] = round(subtotal_for_total - total_discount_for_total + total_tax_for_total, 2)

    return data

from decimal import Decimal
import pandas as pd

def fill_line_item_missing_fields_ui(df: pd.DataFrame, raw_items: list = None, summary_total_discount_amount=0.0) -> pd.DataFrame:
    """
    UI-only line-item post-processing.
    Fills ONLY empty fields. Never overwrites existing values.
    """
    def is_raw_blank(raw_item: dict, field: str) -> bool:
        v = raw_item.get(field, None)
        if v is None:
            return True
        if isinstance(v, str) and v.strip() == "":
            return True
        return False
    out = df.copy()
    summary_discount_present = not (
        summary_total_discount_amount is None
        or str(summary_total_discount_amount).strip() == ""
        or clean_float(summary_total_discount_amount) == 0.0
    )

    def is_blank(v):
        if v is None:
            return True
        try:
            return pd.isna(v) or str(v).strip() == ""
        except Exception:
            return False

    def is_missing_numeric(v):
        if v is None:
            return True
    
        try:
            if pd.isna(v):
                return True
        except Exception:
            pass
    
        if str(v).strip() == "":
            return True
    
        try:
            return clean_float(v) == 0.0
        except Exception:
            return False

    def num(v):
        if is_blank(v):
            return None
        try:
            return float(clean_float(v))
        except Exception:
            return None

    for idx in out.index:
        raw_item = raw_items[idx] if raw_items and idx < len(raw_items) else {}
        amount = num(out.at[idx, "Amount"]) if "Amount" in out.columns else None
        quantity = num(out.at[idx, "Quantity"]) if "Quantity" in out.columns else None
        unit_price = num(out.at[idx, "Unit Price"]) if "Unit Price" in out.columns else None
        disc_amt = num(out.at[idx, "Discount Amount Per Item"]) if "Discount Amount Per Item" in out.columns else None
        disc_rate = num(out.at[idx, "Discount Rate Per Item"]) if "Discount Rate Per Item" in out.columns else None
        tax_rate = num(out.at[idx, "Tax Rate Per Item"]) if "Tax Rate Per Item" in out.columns else None
        tax_amt = num(out.at[idx, "Tax Amount Per Item"]) if "Tax Amount Per Item" in out.columns else None
        line_total = num(out.at[idx, "Line Total"]) if "Line Total" in out.columns else None

        # amount = quantity Γ— unit_price
        if "Amount" in out.columns and is_raw_blank(raw_item, "amount"):
            if quantity is not None and unit_price not in (None, 0):
                amount = round(quantity * unit_price, 2)
                out.at[idx, "Amount"] = amount

        # quantity = amount Γ· unit_price
        if "Quantity" in out.columns and is_raw_blank(raw_item, "quantity"):
            if amount is not None and unit_price not in (None, 0):
                quantity = round(amount / unit_price, 6)
                out.at[idx, "Quantity"] = quantity

        # unit_price = amount Γ· quantity
        if "Unit Price" in out.columns and is_raw_blank(raw_item, "unit_price"):
            if amount is not None and quantity not in (None, 0):
                unit_price = round(amount / quantity, 6)
                out.at[idx, "Unit Price"] = unit_price

        # refresh numbers after possible fills
        amount = num(out.at[idx, "Amount"]) if "Amount" in out.columns else amount
        quantity = num(out.at[idx, "Quantity"]) if "Quantity" in out.columns else quantity
        unit_price = num(out.at[idx, "Unit Price"]) if "Unit Price" in out.columns else unit_price

        # discount_amount_per_item = amount Γ— discount_rate_per_item Γ· 100
        if "Discount Amount Per Item" in out.columns and is_blank(out.at[idx, "Discount Amount Per Item"]):
            if disc_rate is not None and amount is not None:
                disc_amt = round(amount * (disc_rate / 100.0), 2)
                out.at[idx, "Discount Amount Per Item"] = disc_amt
            elif not summary_discount_present:
                # no discount signal -> no discount
                disc_amt = 0.0
                out.at[idx, "Discount Amount Per Item"] = 0.0

        # discount_rate_per_item = (discount_amount_per_item Γ· amount) Γ— 100
        if "Discount Rate Per Item" in out.columns and is_raw_blank(raw_item, "discount_rate_per_item"):
            if disc_amt is not None and amount not in (None, 0):
                disc_rate = round((disc_amt / amount) * 100.0, 4)
                out.at[idx, "Discount Rate Per Item"] = disc_rate

        # taxable_base = amount βˆ’ discount_amount_per_item
        amount = num(out.at[idx, "Amount"]) if "Amount" in out.columns else amount
        disc_amt = num(out.at[idx, "Discount Amount Per Item"]) if "Discount Amount Per Item" in out.columns else disc_amt
        taxable_base = None if amount is None else amount - abs(disc_amt if disc_amt is not None else 0.0)
        # tax_amount_per_item = taxable_base Γ— tax_rate_per_item Γ· 100
        # Only compute when rate is non-zero β€” a zero rate means no tax, and writing 0
        # here would destroy any value already set by distribute_summary_tax_and_discount.
        if "Tax Amount Per Item" in out.columns and is_raw_blank(raw_item, "tax_amount_per_item"):
            if taxable_base is not None and tax_rate is not None and tax_rate != 0:
                tax_amt = round(taxable_base * (tax_rate / 100.0), 2)
                out.at[idx, "Tax Amount Per Item"] = tax_amt

        # tax_rate_per_item = (tax_amount_per_item Γ· taxable_base) Γ— 100
        if "Tax Rate Per Item" in out.columns and is_raw_blank(raw_item, "tax_rate_per_item"):
            tax_amt = num(out.at[idx, "Tax Amount Per Item"])
            if taxable_base not in (None, 0) and tax_amt is not None:
                _cr = round((tax_amt / taxable_base) * 100.0, 4)
                _nw = round(_cr)
                tax_rate = float(_nw) if abs(_cr - _nw) <= 0.05 else _cr
                out.at[idx, "Tax Rate Per Item"] = tax_rate
        # refresh tax_rate after possible back-calculation
        tax_rate = num(out.at[idx, "Tax Rate Per Item"]) if "Tax Rate Per Item" in out.columns else tax_rate

        # Line Total only if blank
        if "Line Total" in out.columns and is_raw_blank(raw_item, "line_total"):
            amount = num(out.at[idx, "Amount"])
            disc_amt = num(out.at[idx, "Discount Amount Per Item"]) or 0.0
            tax_amt = num(out.at[idx, "Tax Amount Per Item"]) or 0.0
            if amount is not None:
                out.at[idx, "Line Total"] = round(amount - abs(disc_amt) + tax_amt, 2)

    return out

def detect_and_reclassify_pseudo_lines(display_data: dict, raw_parsed_data: dict) -> dict:
    """
    Detects pseudo-lines based on field patterns, not description.
    
    Pseudo-line conditions:
    1. quantity is 0 or 1, AND unit_price is blank, AND amount is blank
    2. discount fields (rate or amount) OR tax fields (rate or amount) is filled, along with line_total
    3. Promotes value to summary, removes pseudo-line from line items
    """
    from copy import deepcopy

    data = deepcopy(display_data)
    items = data.get("Itemized Data", []) or []
    raw_items = (raw_parsed_data or {}).get("items", []) or []

    def is_blank_val(v):
        if v is None:
            return True
        if isinstance(v, str) and v.strip() == "":
            return True
        try:
            return clean_float(v) == 0.0
        except (ValueError, TypeError):
            return True

    def has_value(v):
        return not is_blank_val(v)

    real_items = []
    for idx, item in enumerate(items):
        raw_item = raw_items[idx] if idx < len(raw_items) else {}

        # Condition 1: quantity is 0 or 1, unit_price blank, amount blank
        qty = item.get("Quantity")
        unit_price = item.get("Unit Price")
        amount = item.get("Amount")

        try:
            qty_val = float(qty) if qty is not None else 0.0
        except (ValueError, TypeError):
            qty_val = 0.0

        qty_ok = qty_val in (0.0, 1.0)
        unit_price_blank = raw_item.get("unit_price", "") in ("", None) or str(raw_item.get("unit_price", "")).strip() == ""
        amount_blank = raw_item.get("amount", "") in ("", None) or str(raw_item.get("amount", "")).strip() == ""

        if not (qty_ok and unit_price_blank and amount_blank):
            real_items.append(item)
            continue

        # Condition 2: discount or tax fields filled along with line_total
        disc_rate = item.get("Discount Rate Per Item")
        disc_amt = item.get("Discount Amount Per Item")
        tax_rate = item.get("Tax Rate Per Item")
        tax_amt = item.get("Tax Amount Per Item")

        raw_disc_amt = raw_item.get("discount_amount_per_item", "")
        raw_disc_rate = raw_item.get("discount_rate_per_item", "")
        raw_tax_amt = raw_item.get("tax_amount_per_item", "")
        raw_tax_rate = raw_item.get("tax_rate_per_item", "")

        def raw_has_value(v):
            if v is None or str(v).strip() == "":
                return False
            try:
                return clean_float(v) != 0.0
            except (ValueError, TypeError):
                return False

        has_discount = raw_has_value(raw_disc_amt) or raw_has_value(raw_disc_rate)
        has_tax = raw_has_value(raw_tax_amt) or raw_has_value(raw_tax_rate)

        if not (has_discount or has_tax):
            real_items.append(item)
            continue

        # It's a pseudo-line β€” promote to summary
        # Condition 3: route to correct summary field, don't override existing

        if has_discount:
            existing_disc = clean_float(data.get("Total Discount Amount", 0))
            if existing_disc == 0.0:
                if raw_has_value(raw_disc_amt):
                    pseudo_disc = clean_float(disc_amt)
                elif raw_has_value(raw_disc_rate) and has_value(item.get("Line Total")):
                    pseudo_disc = clean_float(item.get("Line Total"))
                else:
                    pseudo_disc = 0.0
                if pseudo_disc != 0.0:
                    data["Total Discount Amount"] = pseudo_disc

        if has_tax:
            existing_tax = clean_float(data.get("Total Tax", 0))
            if existing_tax == 0.0:
                if raw_has_value(raw_tax_amt):
                    pseudo_tax = clean_float(tax_amt)
                elif raw_has_value(raw_tax_rate) and has_value(item.get("Line Total")):
                    pseudo_tax = clean_float(item.get("Line Total"))
                else:
                    pseudo_tax = 0.0
                if pseudo_tax != 0.0:
                    data["Total Tax"] = pseudo_tax
    if len(real_items) < len(items):
        total_amount = clean_float(data.get("Total Amount", 0))
        sum_line_totals = sum(clean_float(item.get("Line Total", 0)) for item in items)

        if abs(sum_line_totals - total_amount) < 0.01:
            for item in real_items:
                amount = clean_float(item.get("Amount", 0))
                if amount != 0:
                    # Clear line total so distribute_summary_tax_and_discount recalculates it
                    item["Line Total"] = ""
                    item["line_total"] = ""
    data["Itemized Data"] = real_items
    return data

def distribute_summary_tax_and_discount(display_data: dict, raw_parsed_data: dict) -> dict:
    """
    UI-only post-processing: proportionally distributes summary-level tax_amount
    and total_discount_amount down to line items β€” only when per-line values are missing.
    Rules:
    - NULL (blank) tax_rate_per_item β†’ line is included in taxable pool
    - 0 tax_rate_per_item β†’ line is excluded, tax_amount_per_item set to 0 explicitly
    - Negative-amount lines (credit notes) β†’ included with signed allocation
    - Residue after rounding β†’ added to line with largest abs(taxable_base)
    - Anomaly: summary_tax > 0 but total_taxable_base == 0 β†’ flag for review
    - Discount: same logic, weight = line.amount
    """
    
    from decimal import Decimal, ROUND_HALF_UP
    from copy import deepcopy
    
    data = deepcopy(display_data)
    items = data.get("Itemized Data", []) or []
    if not items:
        return data

    raw_items = (raw_parsed_data or {}).get("items", []) or []

    summary_tax = Decimal(str(clean_float(data.get("Total Tax", 0))))
    summary_discount = Decimal(str(clean_float(data.get("Total Discount Amount", 0))))

    def is_raw_blank(raw_item: dict, field: str) -> bool:
        """True if the model returned blank/null for this field."""
        v = raw_item.get(field, None)
        if v is None:
            return True
        if isinstance(v, str) and v.strip() == "":
            return True
        return False

    def is_raw_explicitly_zero(raw_item: dict, field: str) -> bool:
        """True if the model explicitly returned 0 for this field."""
        v = raw_item.get(field, None)
        if v is None:
            return False
        if isinstance(v, str) and v.strip() == "":
            return False
        try:
            return clean_float(v) == 0.0
        except (ValueError, TypeError):
            return False

    # DISCOUNT DISTRIBUTION
    if summary_discount != Decimal("0"):
        # Identify lines where discount_amount_per_item is blank in raw output
        dist_candidates = []
        for idx, item in enumerate(items):
            raw_item = raw_items[idx] if idx < len(raw_items) else {}
            if is_raw_blank(raw_item, "discount_amount_per_item"):
                amount = Decimal(str(clean_float(item.get("Amount", 0))))
                dist_candidates.append((idx, amount))

        total_weight = sum(abs(a) for _, a in dist_candidates)

        if total_weight > Decimal("0"):
            allocated = Decimal("0")
            residue_idx = None
            largest_weight = Decimal("0")

            for idx, amount in dist_candidates:
                weight = abs(amount)
                share = (summary_discount * amount / total_weight).quantize(
                    Decimal("0.01"), rounding=ROUND_HALF_UP
                )
                items[idx]["Discount Amount Per Item"] = float(share)
                allocated += share

                if weight > largest_weight:
                    largest_weight = weight
                    residue_idx = idx

            # Residue correction
            residue = summary_discount - allocated
            if residue != Decimal("0") and residue_idx is not None:
                current = Decimal(str(clean_float(items[residue_idx].get("Discount Amount Per Item", 0))))
                items[residue_idx]["Discount Amount Per Item"] = float(current + residue)
    
    # TAX DISTRIBUTION
    if summary_tax == Decimal("0"):
        # Still recalculate line totals even if no tax
        for item in items:
            if not isinstance(item, dict):
                continue
            amount = float(item.get("Amount", 0) or 0)
            disc = abs(float(item.get("Discount Amount Per Item", 0) or 0))
            tax = float(item.get("Tax Amount Per Item", 0) or 0)
            if amount != 0:
                item["Line Total"] = round(amount - disc + tax, 2)
        data["Itemized Data"] = items
        return data

    # Mark confirmed-zero-tax lines first (tax_rate_per_item == 0 in raw)
    for idx, item in enumerate(items):
        raw_item = raw_items[idx] if idx < len(raw_items) else {}
        if is_raw_explicitly_zero(raw_item, "tax_rate_per_item"):
            items[idx]["Tax Amount Per Item"] = 0.0

    # Build taxable pool using raw model output exclusively.
    # Only lines where the model gave NOTHING for tax (both rate and amount blank)
    # are eligible for distribution. If the model provided either field β€” even just
    # a rate β€” that line is already handled (rate-based computation or is a VAT
    # pseudo-line); adding distributed tax on top would be wrong.
    # Exclusion rules:
    #   - tax_amount_per_item non-blank in raw β†’ model gave explicit amount, keep it
    #   - tax_rate_per_item  non-blank in raw β†’ model gave a rate (0%, 20%, etc.),
    #     rate-based path handles it, distribution must not touch this line
    taxable_pool = []
    for idx, item in enumerate(items):
        raw_item = raw_items[idx] if idx < len(raw_items) else {}

        if not is_raw_blank(raw_item, "tax_amount_per_item"):
            # Model gave a tax amount for this line β€” keep it as-is
            continue
        if not is_raw_blank(raw_item, "tax_rate_per_item"):
            # Model gave a tax rate β€” rate-based computation or pseudo-line, skip distribution
            continue

        amount = Decimal(str(clean_float(item.get("Amount", 0))))
        disc = Decimal(str(clean_float(item.get("Discount Amount Per Item", 0))))
        taxable_base = amount - abs(disc)
        taxable_pool.append((idx, taxable_base))

    # Total taxable base using abs() for weight calculation
    total_taxable_base = sum(abs(base) for _, base in taxable_pool)

    # Anomaly guard
    if total_taxable_base == Decimal("0"):
        data["_tax_distribution_anomaly"] = (
            "summary_tax > 0 but total_taxable_base == 0 β€” review required"
        )
        data["Itemized Data"] = items
        return data

    # Proportional distribution
    allocated = Decimal("0")
    residue_idx = None
    largest_abs_base = Decimal("0")

    for idx, taxable_base in taxable_pool:
        # Weight = abs(base), but share is signed
        share = (summary_tax * taxable_base / total_taxable_base).quantize(
            Decimal("0.01"), rounding=ROUND_HALF_UP
        )
        items[idx]["Tax Amount Per Item"] = float(share)
        allocated += share

        if abs(taxable_base) > largest_abs_base:
            largest_abs_base = abs(taxable_base)
            residue_idx = idx

    # Residue correction β€” guarantees SUM == summary_tax exactly
    residue = summary_tax - allocated
    if residue != Decimal("0") and residue_idx is not None:
        current = Decimal(str(clean_float(items[residue_idx].get("Tax Amount Per Item", 0))))
        items[residue_idx]["Tax Amount Per Item"] = float(current + residue)

    for item in items:
        if not isinstance(item, dict):
            continue
        amount = float(item.get("Amount", 0) or 0)
        disc = abs(float(item.get("Discount Amount Per Item", 0) or 0))
        tax = float(item.get("Tax Amount Per Item", 0) or 0)
        if amount != 0:
            item["Line Total"] = round(amount - disc + tax, 2)

    data["Itemized Data"] = items
    return data
    

def prepare_processed_invoice_data(raw_parsed_data: dict, edited_data: dict) -> dict:
    """Apply code #1's UI/download postprocessing sequence to a mapped invoice."""
    processed = build_display_data_from_raw(raw_parsed_data or {}, edited_data or {})
    processed = detect_and_reclassify_pseudo_lines(processed, raw_parsed_data or {})
    processed = distribute_summary_tax_and_discount(processed, raw_parsed_data or {})

    items_df = pd.DataFrame(processed.get("Itemized Data", []) or [])
    if not items_df.empty:
        items_df = fill_line_item_missing_fields_ui(
            items_df,
            raw_items=(raw_parsed_data or {}).get("items", []),
            summary_total_discount_amount=processed.get("Total Discount Amount", 0.0),
        )
        processed["Itemized Data"] = items_df.to_dict("records")

    items_list = processed.get("Itemized Data", []) or []
    total_amount_sum = sum(clean_float(i.get("Amount", 0)) for i in items_list if isinstance(i, dict))
    total_tax_sum = sum(clean_float(i.get("Tax Amount Per Item", 0)) for i in items_list if isinstance(i, dict))
    total_disc_sum = sum(clean_float(i.get("Discount Amount Per Item", 0)) for i in items_list if isinstance(i, dict))
    taxable_base = total_amount_sum - abs(total_disc_sum)

    _raw_summary = (raw_parsed_data or {}).get("summary", raw_parsed_data or {})
    _raw_tax_rate = _raw_summary.get("tax_rate", None)
    _raw_tax_rate_blank = _raw_tax_rate is None or (isinstance(_raw_tax_rate, str) and _raw_tax_rate.strip() == "")

    if _raw_tax_rate_blank:
        if taxable_base > 0 and total_tax_sum != 0:
            processed["Tax Percentage"] = round((total_tax_sum / taxable_base) * 100, 4)
        elif clean_float(processed.get("Tax Percentage", 0)) == 0:
            tax_rates = [
                clean_float(i.get("Tax Rate Per Item", 0))
                for i in items_list
                if isinstance(i, dict) and clean_float(i.get("Tax Rate Per Item", 0)) != 0
            ]
            if tax_rates:
                processed["Tax Percentage"] = round(sum(tax_rates) / len(tax_rates), 4)

    if total_amount_sum > 0 and total_disc_sum != 0:
        processed["Discount Rate"] = round((abs(total_disc_sum) / total_amount_sum) * 100, 4)

    return limit_invoice_decimals(processed)

def display_data_for_result(result: dict) -> dict:
    """Use saved user edits as authoritative; otherwise run initial postprocessing."""
    result = result or {}
    edited = deepcopy(result.get("edited_data", {}) or {})
    if result.get("user_saved_edits"):
        return limit_invoice_decimals(edited)
    return prepare_processed_invoice_data(result.get("raw_parsed_data", {}), edited)

def flatten_invoice_to_rows(invoice_data) -> list:
    EXPECTED_BANK_FIELDS = [
        "bank_name", "bank_account_number", "bank_acc_name",
        "bank_iban", "bank_swift", "bank_routing", "bank_branch"
    ]

    def fmt_text(value):
        if value is None or str(value).strip() == "":
            return "NA"
        return str(value).strip()

    def fmt_amount(value):
        if value is None or (isinstance(value, str) and value.strip() == ""):
            return 0
        return limit_decimal_places(value)

    rows = []
    invoice_data = invoice_data or {}
    line_items = invoice_data.get("Itemized Data", []) or []

    bank_details = {}
    nested = invoice_data.get("Bank Details", {}) or {}
    if isinstance(nested, dict):
        for k, v in nested.items():
            key_name = k if str(k).startswith("bank_") else f"bank_{k}"
            bank_details[key_name] = v
    for k, v in invoice_data.items():
        if isinstance(k, str) and k.lower().startswith("bank_"):
            bank_details[k] = v
    for f in EXPECTED_BANK_FIELDS:
        bank_details.setdefault(f, "")

    def base_invoice_info():
        return {
            "Invoice Number":        fmt_text(invoice_data.get("Invoice Number", "")),
            "PO Number":             fmt_text(invoice_data.get("PO Number", "")),
            "Invoice Date":          fmt_text(invoice_data.get("Invoice Date", "")),
            "Payment Terms":         fmt_text(invoice_data.get("Payment Terms", "")),
            "Due Date":              fmt_text(invoice_data.get("Due Date", "")),
            "Currency":              fmt_text(invoice_data.get("Currency", "")),
            "Tax ID":                fmt_text(invoice_data.get("Tax ID", "")),
            "Subtotal":              fmt_amount(invoice_data.get("Subtotal", 0.0)),
            "Tax Percentage":        fmt_amount(invoice_data.get("Tax Percentage", 0.0)),
            "Total Tax":             fmt_amount(invoice_data.get("Total Tax", 0.0)),
            "Discount Rate":         fmt_amount(invoice_data.get("Discount Rate", 0.0)),
            "Total Discount Amount": fmt_amount(invoice_data.get("Total Discount Amount", 0.0)),
            "Total Amount":          fmt_amount(invoice_data.get("Total Amount", 0.0)),
            "Sender Name":           fmt_text(invoice_data.get("Sender Name", "") or (invoice_data.get("Sender", {}) or {}).get("Name", "")),
            "Sender Address":        fmt_text(invoice_data.get("Sender Address", "") or (invoice_data.get("Sender", {}) or {}).get("Address", "")),
            "Recipient Name":        fmt_text(invoice_data.get("Recipient Name", "") or (invoice_data.get("Recipient", {}) or {}).get("Name", "")),
            "Recipient Address":     fmt_text(invoice_data.get("Recipient Address", "") or (invoice_data.get("Recipient", {}) or {}).get("Address", "")),
        }

    def add_bank(row):
        for k in EXPECTED_BANK_FIELDS:
            row[k] = fmt_text(bank_details.get(k, ""))
        return row

    if not line_items:
        row = add_bank(base_invoice_info())
        row.update({
            "Item Description":       "NA",
            "Service Name":           "NA",
            "Service Start Date":     "NA",
            "Service End Date":       "NA",
            "SKU":                    "NA",
            "Item Quantity":          0,
            "Item Unit Price":        0,
            "Item Amount":            0,
            "Discount Rate Per Item": 0,
            "Discount Amount Per Item": 0,
            "Tax Rate Per Item":      0,
            "Tax Amount Per Item":    0,
            "Item Line Total":        0,
            "IO Number/Cost Centre":  "NA",
        })
        rows.append(row)
        return rows

    for item in line_items:
        if not isinstance(item, dict):
            item = {}
        row = add_bank(base_invoice_info())
        row.update({
            "Item Description":       fmt_text(item.get("Description", item.get("Item Description", ""))),
            "Service Name":           fmt_text(item.get("Service Name", "")),
            "Service Start Date":     fmt_text(item.get("Service Start Date", "")),
            "Service End Date":       fmt_text(item.get("Service End Date", "")),
            "SKU":                    fmt_text(item.get("SKU", "")),
            "Item Quantity":          fmt_amount(item.get("Quantity", item.get("Item Quantity", 0))),
            "Item Unit Price":        fmt_amount(item.get("Unit Price", item.get("Item Unit Price", 0))),
            "Item Amount":            fmt_amount(item.get("Amount", item.get("Item Amount", 0))),
            "Discount Rate Per Item": fmt_amount(item.get("Discount Rate Per Item", 0)),
            "Discount Amount Per Item": fmt_amount(item.get("Discount Amount Per Item", 0)),
            "Tax Rate Per Item":      fmt_amount(item.get("Tax Rate Per Item", 0)),
            "Tax Amount Per Item":    fmt_amount(item.get("Tax Amount Per Item", 0)),
            "Item Line Total":        fmt_amount(item.get("Line Total", item.get("Item Line Total", item.get("Amount", 0)))),
            "IO Number/Cost Centre":  fmt_text(item.get("IO Number/Cost Centre", "")),
        })
        rows.append(row)
    return rows


# -----------------------------
# JSONL conversion
# -----------------------------
def build_page_filenames(file_name: str, num_pages: int) -> list[str]:
    """
    Single page β†’ ["PI-2025-Dec-040.png"]
    Multi page  β†’ ["PI-2025-Dec-051_page1.png", "PI-2025-Dec-051_page2.png"]
    Always a list, always .png, single page keeps original name with no suffix.
    """
    stem = Path(file_name).stem
    if num_pages == 1:
        return [f"{stem}.png"]
    return [f"{stem}_page{i+1}.png" for i in range(num_pages)]


def convert_to_jsonl_record(edited_data, file_name="", num_pages: int = 1):
    ed       = edited_data or {}
    currency = ed.get("Currency", "")
    items    = ed.get("Itemized Data", []) or []
    bank     = ed.get("Bank Details", {}) or {}

    header = {
        "invoice_no":    ed.get("Invoice Number", ""),
        "po_no":         ed.get("PO Number", ""),
        "invoice_date":  ed.get("Invoice Date", ""),
        "payment_terms": ed.get("Payment Terms", ""),
        "due_date":      ed.get("Due Date", ""),
        "sender_name":   ed.get("Sender Name", "") or (ed.get("Sender", {}) or {}).get("Name", ""),
        "sender_addr":   ed.get("Sender Address", "") or (ed.get("Sender", {}) or {}).get("Address", ""),
        "tax_id":        ed.get("Tax ID", ""),
        "rcpt_name":     ed.get("Recipient Name", "") or (ed.get("Recipient", {}) or {}).get("Name", ""),
        "rcpt_addr":     ed.get("Recipient Address", "") or (ed.get("Recipient", {}) or {}).get("Address", ""),
        "bank_iban":     bank.get("bank_iban", ""),
        "bank_name":     bank.get("bank_name", ""),
        "bank_acc_no":   bank.get("bank_account_number", ""),
        "bank_routing":  bank.get("bank_routing", ""),
        "bank_swift":    bank.get("bank_swift", ""),
        "bank_acc_name": bank.get("bank_acc_name", ""),
        "bank_branch":   bank.get("bank_branch", ""),
    }

    jsonl_items = []
    for it in items:
        if not isinstance(it, dict):
            continue
        jsonl_items.append({
            "service_name":             it.get("Service Name", ""),
            "service_start_date":       it.get("Service Start Date", ""),
            "service_end_date":         it.get("Service End Date", ""),
            "descriptions":             it.get("Description", ""),
            "SKU":                      it.get("SKU", ""),
            "quantity":                 it.get("Quantity", ""),
            "unit_price":               it.get("Unit Price", ""),
            "amount":                   it.get("Amount", ""),
            "discount_rate_per_item":   it.get("Discount Rate Per Item", ""),
            "discount_amount_per_item": it.get("Discount Amount Per Item", ""),
            "tax_rate_per_item":        it.get("Tax Rate Per Item", ""),
            "tax_amount_per_item":      it.get("Tax Amount Per Item", ""),
            "line_total":               it.get("Line Total", ""),
        })

    summary = {
        "subtotal":              ed.get("Subtotal", ""),
        "tax_rate":              ed.get("Tax Percentage", ""),
        "tax_amount":            ed.get("Total Tax", ""),
        "discount_rate":         ed.get("Discount Rate", ""),
        "total_discount_amount": ed.get("Total Discount Amount", ""),
        "total_amount":          ed.get("Total Amount", ""),
        "currency":              currency,
    }

    return {
        "file_name": build_page_filenames(file_name, num_pages),
        "gt_parse": {
            "header":  header,
            "items":   jsonl_items,
            "summary": summary,
        }
    }


def build_excel_bytes(df):
    buf = BytesIO()
    with pd.ExcelWriter(buf, engine="openpyxl") as writer:
        df.to_excel(writer, index=False, sheet_name="Invoices")
        ws = writer.sheets["Invoices"]
        for col_cells in ws.columns:
            max_len    = 0
            col_letter = col_cells[0].column_letter
            for cell in col_cells:
                try:
                    if cell.value:
                        max_len = max(max_len, len(str(cell.value)))
                except Exception:
                    pass
            ws.column_dimensions[col_letter].width = min(max_len + 3, 50)
    return buf.getvalue()


# =============================================================================
# Extraction helper β€” inference + code #1 postprocessing
# =============================================================================
def _run_extraction(pages: List[Image.Image]) -> tuple[str | None, dict, dict]:
    raw_json = run_inference_vllm(pages)
    if not raw_json:
        return None, {}, {}

    raw_parsed_data, parsed_data = parse_vllm_json(raw_json)
    if not parsed_data:
        st.warning("Failed to parse JSON response from model.")
        return raw_json, raw_parsed_data or {}, {}

    mapped = validate_and_calculate_taxes(parsed_data)
    safe_mapped = mapped if isinstance(mapped, dict) else {}
    display_ready = prepare_processed_invoice_data(raw_parsed_data or {}, safe_mapped)
    return raw_json, raw_parsed_data or {}, display_ready if isinstance(display_ready, dict) else safe_mapped


# =============================================================================
# Pipeline integration helpers
# =============================================================================

def load_default_configs() -> dict:
    """Load default configs from disk; return Nones on failure (pipeline auto-loads)."""
    configs: dict = {"platform_configs": None, "matching_configs": None}
    _base = os.path.dirname(os.path.abspath(__file__))
    try:
        # Local: subfolder layout β€” HF Spaces: flat layout (same dir)
        _p = os.path.join(_base, "Invoice Validation Functions", "platform_configs.json")
        if not os.path.exists(_p):
            _p = os.path.join(_base, "platform_configs.json")
        with open(_p, encoding="utf-8") as _f:
            configs["platform_configs"] = json.load(_f)
    except Exception:
        pass
    try:
        _p = os.path.join(_base, "Matching Functions", "matching_configs.json")
        if not os.path.exists(_p):
            _p = os.path.join(_base, "matching_configs.json")
        with open(_p, encoding="utf-8") as _f:
            configs["matching_configs"] = json.load(_f)
    except Exception:
        pass
    return configs


def _safe_int(val, default: int = 0) -> int:
    """Convert a cell value (possibly NaN→"" after fillna) to int safely."""
    if val is None or val == "":
        return default
    try:
        return int(float(str(val)))
    except (ValueError, TypeError):
        return default


def parse_validation_master(xlsx_bytes: bytes) -> dict:
    """Parse Validation Master Excel β†’ master_data dict entries."""
    xls = pd.ExcelFile(BytesIO(xlsx_bytes))
    result: dict = {}

    if "Vendor Master" in xls.sheet_names:
        df = xls.parse("Vendor Master").fillna("")
        result["vendors"] = [
            SimpleNamespace(
                id=_safe_int(row.get("vendor_id"), 0),
                tenant_id=_safe_int(row.get("tenant_id"), 1),
                legal_name=str(row.get("legal_name", "")),
                vendor_name=str(row.get("vendor_name", "")),
                vendor_status=str(row.get("vendor_status", "active")),
                deleted_at=None if str(row.get("deleted_at", "")).strip() == "" else str(row.get("deleted_at", "")),
                billing_country=str(row.get("billing_country", "")),
                billing_state=None if str(row.get("billing_state", "")).strip() == "" else str(row.get("billing_state", "")),
                tax_registration_number=str(row.get("tax_registration_number", "")),
                payment_terms=_safe_int(row.get("payment_terms"), 30),
                exemption_status=str(row.get("exemption_status", "standard")),
            )
            for _, row in df.iterrows()
        ]

    if "Vendor Tax ID Master" in xls.sheet_names:
        df = xls.parse("Vendor Tax ID Master").fillna("")
        result["vendor_tax_ids"] = [
            SimpleNamespace(
                tenant_id=_safe_int(row.get("tenant_id"), 1),
                vendor_id=_safe_int(row.get("vendor_id"), 0),
                tax_id_canonical=str(row.get("tax_id_canonical", "")),
                tax_id_type=str(row.get("tax_id_type", "")),
                verified_at=str(row.get("verified_at", "")) or None,
                deleted_at=None if str(row.get("deleted_at", "")).strip() == "" else str(row.get("deleted_at", "")),
                effective_from=None,
                effective_to=None,
            )
            for _, row in df.iterrows()
        ]

    if "Vendor Bank Master" in xls.sheet_names:
        df = xls.parse("Vendor Bank Master").fillna("")
        result["vendor_bank_accounts"] = [
            SimpleNamespace(
                tenant_id=_safe_int(row.get("tenant_id"), 1),
                vendor_id=_safe_int(row.get("vendor_id"), 0),
                iban_canonical=str(row.get("iban_canonical", "")),
                acc_no_canonical=str(row.get("acc_no_canonical", "")),
                swift_bic=str(row.get("swift_bic", "")),
                bank_acc_name=str(row.get("bank_acc_name", "")),
                currency_code=str(row.get("currency_code", "")),
                bank_country=str(row.get("bank_country", "")),
                is_primary=bool(_safe_int(row.get("is_primary"), 1)),
                effective_from=None,
                effective_to=None,
                deleted_at=None if str(row.get("deleted_at", "")).strip() == "" else str(row.get("deleted_at", "")),
            )
            for _, row in df.iterrows()
        ]

    if "Tax Master" in xls.sheet_names:
        df = xls.parse("Tax Master").fillna("")
        result["tax_master_rows"] = [
            SimpleNamespace(
                id=_safe_int(row.get("id"), i + 1),
                tenant_id=_safe_int(row.get("tenant_id"), 1),
                is_active=bool(_safe_int(row.get("is_active"), 1)),
                deleted_at=None,
                country_code=str(row.get("country_code", "")),
                region_code=None if str(row.get("region_code", "")).strip() == "" else str(row.get("region_code", "")),
                tax_type=str(row.get("tax_type", "VAT")),
                tax_rate=float(row.get("tax_rate", 0.0)),
                tax_name=str(row.get("tax_name", "")),
                effective_from=None,
                effective_to=None,
            )
            for i, (_, row) in enumerate(df.iterrows())
        ]

    if "Currency Master" in xls.sheet_names:
        df = xls.parse("Currency Master").fillna("")
        result["currency_seed_map"] = {
            str(row.get("currency_code", "")): {"minor_unit_value": str(row.get("minor_unit_value", "0.01"))}
            for _, row in df.iterrows()
            if str(row.get("currency_code", "")).strip()
        }

    if "Entity" in xls.sheet_names:
        df = xls.parse("Entity").fillna("")
        if not df.empty:
            row = df.iloc[0]
            result["entity"] = SimpleNamespace(
                id=_safe_int(row.get("id"), 1),
                tenant_id=_safe_int(row.get("tenant_id"), 1),
                entity_id=_safe_int(row.get("entity_id"), 10),
                country_code=str(row.get("country_code", "")),
                vat_id=str(row.get("vat_id", "")),
                region_code=None if str(row.get("region_code", "")).strip() == "" else str(row.get("region_code", "")),
            )

    return result


def parse_po_master(xlsx_bytes: bytes) -> dict:
    """Parse PO Master Excel β†’ purchase_orders (for validation) + matching_pos + po_lines_map."""
    if not _pipeline_available:
        raise RuntimeError(f"Pipeline not loaded β€” cannot parse PO master: {_pipeline_import_error}")
    df = pd.read_excel(BytesIO(xlsx_bytes)).fillna("")
    val_pos: dict = {}       # po_id β†’ SimpleNamespace for validation layer
    match_pos: dict = {}     # po_id β†’ POHeader for matching layer
    canonical_map: dict = {} # po_id β†’ po_number_canonical
    po_lines_map: dict = {}  # po_id β†’ [POLine]

    for _, row in df.iterrows():
        po_id = _safe_int(row.get("po_id"), 0)
        raw_po_no = str(row.get("po_number", ""))
        po_canon = re.sub(r"[^A-Z0-9\-]", "", raw_po_no.upper())
        pt_raw = str(row.get("payment_terms", "")).strip()
        pt_val = _safe_int(pt_raw if pt_raw not in ("", "nan") else None, 30)

        if po_id not in val_pos:
            val_pos[po_id] = SimpleNamespace(
                id=po_id, tenant_id=1,
                po_number_canonical=po_canon,
                payment_terms=pt_val, deleted_at=None,
            )
            match_pos[po_id] = POHeader(
                id=po_id,
                vendor_id=_safe_int(row.get("vendor_id"), 0),
                currency=str(row.get("currency", "GBP")),
                status=str(row.get("po_status", "open")),
            )
            canonical_map[po_id] = po_canon
            po_lines_map[po_id] = []

        line_id = str(row.get("line_id", "")).strip()
        if line_id and line_id not in ("", "nan"):
            try:
                line_id_int = int(float(line_id))
            except (ValueError, TypeError):
                continue  # skip non-numeric line IDs silently
            desc = str(row.get("line_description", ""))
            sku = str(row.get("line_sku", ""))
            po_lines_map[po_id].append(POLine(
                id=line_id_int,
                description=desc,
                description_canonical=re.sub(r"[^A-Z0-9]", "", desc.upper()),
                sku=sku,
                sku_canonical=re.sub(r"[^A-Z0-9]", "", sku.upper()),
                gl_account=str(row.get("line_gl_account", "") or "").strip() or None,
                quantity=Decimal(str(clean_float(row.get("line_quantity", 0)))),
                invoiced_qty=Decimal(str(clean_float(row.get("line_invoiced_qty", 0)))),
                unit_price=Decimal(str(clean_float(row.get("line_unit_price", 0)))),
                item_type=str(row.get("line_item_type", "")) or None,
                status=str(row.get("line_status", "open")),
            ))

    return {
        "purchase_orders": list(val_pos.values()),
        "matching_pos": [(match_pos[pid], canonical_map[pid]) for pid in match_pos],
        "po_lines_map": po_lines_map,
    }


def parse_gr_master(xlsx_bytes: bytes) -> dict:
    """Parse GR Master Excel β†’ gr_rows list."""
    if not _pipeline_available:
        raise RuntimeError(f"Pipeline not loaded β€” cannot parse GR master: {_pipeline_import_error}")
    df = pd.read_excel(BytesIO(xlsx_bytes)).fillna("")
    gr_rows = []
    for _, row in df.iterrows():
        gr_date_raw = row.get("gr_date", "")
        if hasattr(gr_date_raw, "date") and callable(gr_date_raw.date):
            gr_date_val = gr_date_raw.date()
        elif str(gr_date_raw).strip():
            _d = parse_date_to_object(str(gr_date_raw))
            gr_date_val = _d.date() if hasattr(_d, "date") and callable(_d.date) else _d
        else:
            gr_date_val = None
        if gr_date_val is None:
            continue
        qty_acc_raw = str(row.get("quantity_accepted", "")).strip()
        qty_accepted = Decimal(str(clean_float(qty_acc_raw))) if qty_acc_raw and qty_acc_raw not in ("nan", "") else None
        gr_rows.append(GRLineItem(
            id=_safe_int(row.get("gr_id"), 0),
            po_line_id=_safe_int(row.get("po_line_id"), 0),
            gr_date=gr_date_val,
            inspection_status=str(row.get("inspection_status", "accepted")),
            quantity_received=Decimal(str(clean_float(row.get("quantity_received", 0)))),
            quantity_accepted=qty_accepted,
        ))
    return {"gr_rows": gr_rows}


def parse_contract_master(xlsx_bytes: bytes) -> dict:
    """Parse Contract Master Excel β†’ contracts list."""
    if not _pipeline_available:
        raise RuntimeError(f"Pipeline not loaded β€” cannot parse Contract master: {_pipeline_import_error}")
    df = pd.read_excel(BytesIO(xlsx_bytes)).fillna("")

    def _parse_date_col(val):
        if hasattr(val, "date") and callable(val.date):
            return val.date()
        v = str(val).strip()
        if not v or v in ("", "nan"):
            return None
        _d = parse_date_to_object(v)
        return _d.date() if hasattr(_d, "date") and callable(_d.date) else _d

    contracts_data: dict = {}  # cid β†’ (header_row, [rate_card_items])
    for _, row in df.iterrows():
        cid = _safe_int(row.get("contract_id"), 0)
        if cid not in contracts_data:
            contracts_data[cid] = (row, [])
        desc = str(row.get("rate_description", ""))
        if desc.strip() and desc.strip() != "nan":
            contracts_data[cid][1].append(RateCardItem(
                id=len(contracts_data[cid][1]) + 1,
                description=desc,
                description_canonical=re.sub(r"[^A-Z0-9]", "", desc.upper()),
                unit_price=(lambda v: None if not v or v.lower() == "nan"
                            else Decimal(str(clean_float(v))))(str(row.get("rate_unit_price", "")).strip()),
                item_type=str(row.get("rate_item_type", "services")),
            ))

    contracts = []
    for cid, (row, rate_items) in contracts_data.items():
        tv_raw = str(row.get("total_value", "")).strip()
        cb_raw = str(row.get("cumulative_billed_amount", "")).strip()
        contracts.append(ContractRecord(
            id=cid,
            tenant_id=_safe_int(row.get("tenant_id"), 1),
            vendor_id=_safe_int(row.get("vendor_id"), 0),
            entity_id=_safe_int(row.get("entity_id"), 0),
            currency=str(row.get("currency", "")),
            status=str(row.get("status", "active")),
            effective_from=_parse_date_col(row.get("effective_from", "")),
            effective_to=_parse_date_col(row.get("effective_to", "")),
            total_value=Decimal(str(clean_float(tv_raw))) if tv_raw and tv_raw not in ("nan", "") else None,
            cumulative_billed_amount=Decimal(str(clean_float(cb_raw))) if cb_raw and cb_raw not in ("nan", "") else None,
            rate_card_items=rate_items,
        ))
    return {"contracts": contracts}


def _canonicalize_str(s: str) -> str:
    return re.sub(r"[^A-Z0-9]", "", str(s).upper()) if s else ""


def _pre_resolve_vendor_id(edited_data: dict, master_data: dict):
    """Try to resolve vendor_id from master by tax_id or name match. Returns int or None."""
    tax_id_raw = str(edited_data.get("Tax ID", "") or "").strip()
    if tax_id_raw:
        canonical = re.sub(r"^[A-Z]{2}", "", tax_id_raw.upper()).strip()
        for vtid in master_data.get("vendor_tax_ids", []):
            if getattr(vtid, "tax_id_canonical", "") == canonical:
                return vtid.vendor_id
    sender_name = str(edited_data.get("Sender Name", "") or "").strip()
    if sender_name:
        s_canon = _canonicalize_str(sender_name)
        for v in master_data.get("vendors", []):
            v_canon = _canonicalize_str(getattr(v, "vendor_name", "") or "")
            if v_canon and v_canon == s_canon:
                return v.id
    return None


def build_and_run_pipeline(edited_data: dict, master_data: dict, pipeline_configs: dict) -> dict:
    """Build pipeline inputs from UI data + master data, then call run_invoice_pipeline."""
    if not _pipeline_available:
        return {
            "final_status": "exception",
            "error": f"Pipeline not loaded: {_pipeline_import_error}",
            "risk_flags": [], "advisory_flags": [],
            "match_result": None, "route": "error",
        }
    entity = master_data.get("entity")
    if entity is None:
        return {
            "final_status": "exception", "error": "Entity not found in master data",
            "risk_flags": [], "advisory_flags": [],
            "match_result": None, "route": "error",
        }
    _test_entity_country = str(edited_data.get("test_entity_country", "") or "").strip()
    if _test_entity_country:
        import copy as _copy
        entity = _copy.copy(entity)
        entity.country_code = _test_entity_country
    tenant_id = getattr(entity, "tenant_id", 1)
    entity_id = getattr(entity, "entity_id", 10)

    document = SimpleNamespace(
        id=0, tenant_id=tenant_id, entity_id=entity_id,
        status="validated", doc_type="invoice", tenant_timezone="UTC",
    )

    po_number_raw = str(edited_data.get("PO Number", "") or "").strip()
    po_number_canonical = re.sub(r"[^A-Z0-9\-]", "", po_number_raw.upper()) if po_number_raw else None

    sender_name = str(edited_data.get("Sender Name", "") or "")
    sender_tax_id = str(edited_data.get("Tax ID", "") or "")
    bank = edited_data.get("Bank Details", {}) or {}
    bank_iban = str(bank.get("bank_iban", "") or "")
    bank_iban_canonical = re.sub(r"\s+", "", bank_iban).upper() if bank_iban else ""

    invoice_date = parse_date_to_object(str(edited_data.get("Invoice Date", "") or ""))
    due_date     = parse_date_to_object(str(edited_data.get("Due Date", "") or ""))
    if hasattr(invoice_date, "date") and callable(invoice_date.date):
        invoice_date = invoice_date.date()
    if hasattr(due_date, "date") and callable(due_date.date):
        due_date = due_date.date()

    pt_raw = str(edited_data.get("Payment Terms", "") or "")
    pt_match = re.search(r"-?\d+", pt_raw)
    payment_terms = int(pt_match.group()) if pt_match else 0

    currency = str(edited_data.get("Currency", "") or "")

    _svc_raw = [it for it in (edited_data.get("Itemized Data", []) or []) if isinstance(it, dict)]
    _svc_starts, _svc_ends = [], []
    for _it in _svc_raw:
        for _key, _lst in [("Service Start Date", _svc_starts), ("Service End Date", _svc_ends)]:
            _d = parse_date_to_object(str(_it.get(_key, "") or ""))
            if _d:
                if hasattr(_d, "date") and callable(_d.date):
                    _d = _d.date()
                _lst.append(_d)
    svc_start = min(_svc_starts) if _svc_starts else None
    svc_end   = max(_svc_ends)   if _svc_ends   else None

    extracted_fields = SimpleNamespace(
        sender_name=sender_name,
        sender_name_canonical=_canonicalize_str(sender_name),
        sender_tax_id=sender_tax_id,
        sender_tax_id_canonical=sender_tax_id,
        bank_iban=bank_iban,
        bank_iban_canonical=bank_iban_canonical,
        bank_acc_no=str(bank.get("bank_account_number", "") or bank.get("bank_acc_no", "") or ""),
        bank_swift=str(bank.get("bank_swift", "") or ""),
        bank_acc_name=str(bank.get("bank_acc_name", "") or ""),
        invoice_date=invoice_date,
        due_date=due_date,
        due_date_origin=str(edited_data.get("test_due_date_origin", "") or "").strip() or "invoice",
        service_start_date=svc_start,
        service_end_date=svc_end,
        payment_terms=payment_terms,
        po_number_canonical=po_number_canonical,
        currency=currency,
        invoice_no=str(edited_data.get("Invoice Number", "") or ""),
        total_amount=Decimal(str(clean_float(edited_data.get("Total Amount", 0)))),
        subtotal=Decimal(str(clean_float(edited_data.get("Subtotal", 0)))),
        tax_amount=Decimal(str(clean_float(edited_data.get("Total Tax", 0)))),
        tax_rate=Decimal(str(clean_float(edited_data.get("Tax Percentage", 0)))),
    )

    line_items_raw = [it for it in (edited_data.get("Itemized Data", []) or []) if isinstance(it, dict)]
    line_items = [
        SimpleNamespace(
            line_number=i + 1,
            amount=Decimal(str(clean_float(it.get("Amount", 0)))),
            tax_rate_per_item=Decimal(str(clean_float(it.get("Tax Rate Per Item", 0)))),
            tax_amount_per_item=Decimal(str(clean_float(it.get("Tax Amount Per Item", 0)))),
            discount_amount_per_item=Decimal(str(clean_float(it.get("Discount Amount Per Item", 0))))
                if clean_float(it.get("Discount Amount Per Item", 0)) else None,
            region_code_hint=str(it.get("Region Code Hint", "")).strip() or None,
        )
        for i, it in enumerate(line_items_raw)
    ]

    resolved_vendor_id = _pre_resolve_vendor_id(edited_data, master_data)

    matching_invoice = InvoiceHeader(
        id=0, status="validated",
        vendor_id=resolved_vendor_id or 0,
        currency=currency,
        total_amount=Decimal(str(clean_float(edited_data.get("Subtotal", 0)))),
        invoice_date=invoice_date,
    )

    matching_inv_lines = [
        InvoiceLine(
            id=i + 1,
            description=str(it.get("Description", "") or ""),
            description_canonical=_canonicalize_str(str(it.get("Description", "") or "")),
            sku=str(it.get("SKU", "") or ""),
            sku_canonical=_canonicalize_str(str(it.get("SKU", "") or "")),
            gl_account=str(it.get("GL Account", "") or "").strip() or None,
            quantity=Decimal(str(clean_float(it.get("Quantity", 1)))),
            unit_price=Decimal(str(clean_float(it.get("Unit Price", 0)))),
            amount=Decimal(str(clean_float(it.get("Amount", 0)))),
        )
        for i, it in enumerate(line_items_raw)
    ]
    if not matching_inv_lines:
        matching_inv_lines = [InvoiceLine(
            id=1, description="", description_canonical="", sku="", sku_canonical="",
            quantity=Decimal("1"),
            unit_price=Decimal(str(clean_float(edited_data.get("Subtotal", 0)))),
            amount=Decimal(str(clean_float(edited_data.get("Subtotal", 0)))),
        )]

    # Extract service date range from line items β€” required by contract_match to avoid
    # billing_period_unverified hard exception on every contract-route invoice.
    # Must happen after line_items_raw is defined; update extracted_fields after.
    svc_start = None
    svc_end   = None
    for _it in line_items_raw:
        for _key, _is_start in [("Service Start Date", True), ("Service End Date", False)]:
            _raw = str(_it.get(_key, "") or "").strip()
            if not _raw:
                continue
            _d = parse_date_to_object(_raw)
            if _d is None:
                continue
            if hasattr(_d, "date") and callable(_d.date):
                _d = _d.date()
            if _is_start:
                svc_start = _d if svc_start is None else min(svc_start, _d)
            else:
                svc_end = _d if svc_end is None else max(svc_end, _d)

    extracted_fields.service_start_date = svc_start
    extracted_fields.service_end_date   = svc_end

    po = None
    po_lines: list = []
    if po_number_canonical:
        for match_ph, canon in master_data.get("matching_pos", []):
            if canon == po_number_canonical:
                po = match_ph
                po_lines = master_data.get("po_lines_map", {}).get(match_ph.id, [])
                break

    gr_rows: list = []
    if po_lines:
        po_line_ids = {getattr(pl, "id", None) for pl in po_lines}
        gr_rows = [gr for gr in master_data.get("gr_rows", [])
                   if getattr(gr, "po_line_id", None) in po_line_ids]

    contract_invoice = None
    if not po_number_canonical:
        contract_invoice = ContractInvoiceHeader(
            id=0, tenant_id=tenant_id, entity_id=entity_id,
            resolved_vendor_id=resolved_vendor_id,
            currency=currency, invoice_date=invoice_date,
            service_start_date=svc_start,
            service_end_date=svc_end,
            total_amount=Decimal(str(clean_float(edited_data.get("Total Amount", 0)))),
        )

    pc = (pipeline_configs or {}).get("platform_configs") or None
    mc = (pipeline_configs or {}).get("matching_configs") or None

    return run_invoice_pipeline(
        document=document,
        extracted_fields=extracted_fields,
        vendors=master_data.get("vendors", []),
        vendor_bank_accounts=master_data.get("vendor_bank_accounts", []),
        vendor_tax_ids=master_data.get("vendor_tax_ids", []),
        entity=entity,
        line_items=line_items,
        purchase_orders=master_data.get("purchase_orders", []),
        contracts=master_data.get("contracts", []),
        tax_master_rows=master_data.get("tax_master_rows", []),
        currency_seed_map=master_data.get("currency_seed_map", {}),
        platform_configs=pc,
        matching_invoice=matching_invoice,
        matching_inv_lines=matching_inv_lines,
        contract_invoice=contract_invoice,
        po=po,
        po_lines=po_lines or None,
        gr_rows=gr_rows or None,
        matching_configs=mc,
    )


# ── Flag display constants ────────────────────────────────────────────────────
_FIELD_FLAG_MAP: dict = {
    "Invoice Number": ["missing_invoice_number"],
    "PO Number":      ["po_not_found", "po_cancelled", "po_all_lines_closed", "po_closed", "missing_po_number"],
    "Invoice Date":   ["invoice_date_invalid", "invoice_in_future", "backdated_invoice", "missing_invoice_date",
                       "date_anomaly_invoice_future_dated", "date_anomaly_invoice_too_old",
                       "invoice_before_gr"],
    "Payment Terms":  ["payment_terms_mismatch", "vendor_payment_terms_unconfigured",
                       "date_anomaly_payment_terms_negative"],
    "Due Date":       ["due_date_missing", "due_date_before_invoice",
                       "date_anomaly_due_before_invoice", "due_date_not_derivable"],
    "Tax ID":         ["tax_id_mismatch", "unverified_tax_id", "missing_tax_id", "missing_tax_id_for_local_tax",
                       "tax_id_unverified_master", "tax_id_country_mismatch"],
    "Currency":       ["currency_mismatch", "invalid_currency"],
    "Subtotal":       ["subtotal_mismatch", "math_error_line_items"],
    "Tax Percentage": ["tax_rate_mismatch", "tax_rate_not_in_master",
                       "cross_country_tax", "us_sales_tax", "us_use_tax_possibly_owed",
                       "eu_reverse_charge", "uk_zero_rated", "uk_exempt",
                       "in_gst_jurisdiction_unresolved", "in_gst_jurisdiction_inferred",
                       "us_region_unresolved"],
    "Total Tax":      ["tax_amount_mismatch", "vendor_tax_exempt"],
    "Total Amount":   ["total_amount_mismatch", "po_ceiling_exhausted",
                       "exceeds_remaining_po_value_at_match"],
    "Sender Name":    ["unknown_vendor", "vendor_name_mismatch", "cannot_match_no_vendor",
                       "vendor_suggestion", "low_confidence_vendor_resolution", "vendor_blocked",
                       "vendor_withholding_applicable"],
    "Bank IBAN":      ["bank_iban_mismatch", "bank_iban_invalid_checksum", "bank_iban_accno_inconsistent",
                       "new_bank_details_no_master", "bank_non_primary_match",
                       "new_bank_field_type_no_master"],
    "Account Number": ["bank_account_mismatch", "bank_acc_no_mismatch",
                       "bank_currency_mismatch"],
    "Account Name":   ["bank_acc_name_mismatch"],
    "SWIFT":          ["bank_swift_mismatch"],
}

_FLAG_LABELS: dict = {
    "unknown_vendor":                        "Vendor not found in master data",
    "vendor_name_mismatch":                  "Vendor name does not match master",
    "tax_id_mismatch":                       "Tax ID does not match vendor master",
    "unverified_tax_id":                     "Tax ID is unverified",
    "bank_iban_mismatch":                    "IBAN does not match vendor master",
    "bank_account_mismatch":                 "Account number does not match vendor master",
    "bank_swift_mismatch":                   "SWIFT/BIC does not match vendor master",
    "invoice_date_invalid":                  "Invoice date is invalid",
    "invoice_in_future":                     "Invoice date is in the future",
    "backdated_invoice":                     "Invoice is too old",
    "due_date_missing":                      "Due date is missing",
    "due_date_before_invoice":               "Due date is before invoice date",
    "payment_terms_mismatch":                "Payment terms do not match vendor master",
    "tax_rate_mismatch":                     "Tax rate does not match tax master",
    "tax_amount_mismatch":                   "Tax amount does not match calculated value",
    "subtotal_mismatch":                     "Subtotal does not match line items",
    "total_amount_mismatch":                 "Total amount does not match subtotal + tax",
    "po_ceiling_exhausted":                  "PO ceiling has been exhausted",
    "po_not_found":                          "PO number not found in system",
    "po_cancelled":                          "PO is cancelled",
    "po_all_lines_closed":                   "All PO lines are closed or cancelled",
    "po_closed":                             "PO is closed",
    "currency_mismatch":                     "Currency does not match PO currency",
    "missing_invoice_number":                "Invoice number is missing",
    "missing_po_number":                     "PO number is missing",
    "missing_invoice_date":                  "Invoice date is missing",
    "missing_tax_id":                        "Tax ID is missing",
    "cannot_match_no_vendor":                "Cannot match: vendor could not be resolved",
    "date_anomaly_invoice_future_dated":     "Invoice date is in the future",
    "date_anomaly_invoice_too_old":          "Invoice is too old",
    "date_anomaly_due_before_invoice":       "Due date is before invoice date",
    "date_anomaly_payment_terms_negative":   "Payment terms cannot be negative",
    "date_anomaly_service_period_reversed":  "Service end date is before start date",
    "date_anomaly_service_end_after_invoice":"Service end date is after invoice date",
    "due_date_not_derivable":                "Due date is missing and cannot be derived",
    "math_error_line_items":                 "Line items do not sum to subtotal",
    "tax_rate_not_in_master":                "Tax rate not found in tax master",
    "missing_tax_id_for_local_tax":          "Tax ID required for this jurisdiction",
    "invalid_currency":                      "Currency not recognised",
    "incomplete_fields":                     "Required field is missing",
    "vendor_suggestion":                     "Possible vendor match β€” please verify",
    "low_confidence_vendor_resolution":      "Vendor matched with low confidence",
    "vendor_blocked":                        "Vendor is blocked",
    "tax_id_mismatch":                       "Tax ID does not match vendor master",
    "tax_id_unverified_master":              "Tax ID not verified in master",
    "tax_id_country_mismatch":               "Tax ID country does not match vendor country",
    "bank_iban_invalid_checksum":            "IBAN checksum is invalid",
    "bank_iban_accno_inconsistent":          "IBAN and account number are inconsistent",
    "new_bank_details_no_master":            "Bank details not found in vendor master",
    "bank_acc_no_mismatch":                  "Account number does not match vendor master",
    "bank_acc_name_mismatch":                "Account name does not match vendor master",
    "bank_currency_mismatch":                "Bank account currency does not match invoice",
    "bank_non_primary_match":                "Matched to a non-primary bank account",
    "vendor_payment_terms_unconfigured":     "Vendor has no payment terms configured in master",
    "payment_terms_mismatch":                "Payment terms do not match vendor master",
    "new_bank_field_type_no_master":         "Bank identifier type not found in master",
    "vendor_withholding_applicable":         "Vendor is subject to withholding tax β€” deduct before payment",
    "exceeds_remaining_po_value_at_match":   "Invoice total exceeds remaining PO value",
    "rate_card_match_no_price_compare":      "Rate card item matched but has no price β€” price comparison skipped",
    "eu_reverse_charge":                     "EU reverse charge β€” buyer accounts for VAT",
    "uk_zero_rated":                         "UK zero-rated supply β€” 0% VAT applies",
    "uk_exempt":                             "UK exempt supply β€” VAT cannot be charged",
    "cross_country_tax":                     "Tax applies across different countries",
    "us_sales_tax":                          "US sales tax applies",
    "us_use_tax_possibly_owed":              "US use tax may be owed on this purchase",
    "in_gst_jurisdiction_unresolved":        "Indian GST jurisdiction could not be determined",
    "in_gst_jurisdiction_inferred":          "Indian GST jurisdiction inferred from vendor location",
    "us_region_unresolved":                  "US state/region could not be determined for tax",
    "vendor_tax_exempt":                     "Vendor is tax-exempt β€” no tax should be charged",
    "item_type_unresolved":                  "Item type (goods/services) could not be resolved",
    "invoice_before_gr":                     "Invoice date precedes goods receipt date",
}


def _normalise_flags(pipeline_result: dict) -> tuple:
    if not pipeline_result:
        return [], []
    def _n(f, sev):
        if isinstance(f, dict):
            return {**f, "severity": sev}
        return {"code": str(f), "severity": sev}
    risk = [_n(f, "risk") for f in (pipeline_result.get("risk_flags") or [])]
    adv  = [_n(f, "advisory") for f in (pipeline_result.get("advisory_flags") or [])]
    return risk, adv


_FIELD_MISSING_KEY: dict = {
    "Invoice Number": "invoice_no",
    "Invoice Date":   "invoice_date",
    "Total Amount":   "total_amount",
    "Sender Name":    "sender_name",
    "Currency":       "currency",
    "Due Date":       "due_date",
    "Payment Terms":  "payment_terms",
}


def get_field_flags(pipeline_result, field_name: str) -> list:
    if not pipeline_result:
        return []
    codes = _FIELD_FLAG_MAP.get(field_name, [])
    risk, adv = _normalise_flags(pipeline_result)
    all_flags = risk + adv
    seen_codes: set = set()
    matched = []
    for f in all_flags:
        code = f.get("code", "")
        if code in codes and code not in seen_codes:
            seen_codes.add(code)
            matched.append(f)
    missing_key = _FIELD_MISSING_KEY.get(field_name)
    if missing_key and "incomplete_fields" not in seen_codes:
        for f in all_flags:
            if f.get("code") == "incomplete_fields":
                if missing_key in ((f.get("detail") or {}).get("missing_fields") or []):
                    matched.append(f)
                    break
    return matched


# Tax/match flag codes that carry no per-line detail but apply to every line
# in the invoice (e.g. vendor_tax_exempt fires when ALL lines have zero rate).
# Bank and vendor-level flags are intentionally excluded β€” they belong in the
# header Risk/Advisory Flags section only.
_LINE_TABLE_ALL_FLAGS = {
    # Tax flags β€” fired at invoice level, apply to all lines
    "vendor_tax_exempt",
    "eu_reverse_charge",
    "uk_zero_rated",
    "uk_exempt",
    "cross_country_tax",
    "us_sales_tax",
    "us_region_unresolved",
    "us_use_tax_possibly_owed",
    "in_gst_jurisdiction_inferred",
    "in_gst_jurisdiction_unresolved",
    # Service-period date flags β€” fired once per document (no line_number in detail)
    "date_anomaly_service_period_reversed",
    "date_anomaly_service_end_after_invoice",
}


def build_flags_column(pipeline_result, num_lines: int) -> list:
    if not pipeline_result or num_lines == 0:
        return [""] * num_lines
    result = [""] * num_lines

    def _add(idx, text):
        if 0 <= idx < num_lines:
            result[idx] = (result[idx] + ", " + text) if result[idx] else text

    def _add_all(text):
        for i in range(num_lines):
            result[i] = (result[i] + ", " + text) if result[i] else text

    # Match exceptions (no_match, qty_over_received, invoice_before_gr, etc.) are
    # already shown with human-readable text and zone colour in the Match Reason
    # column. Adding them here too would be redundant raw codes in Flags.

    seen_per_line: dict = {}  # idx -> set of codes already added
    for f in (pipeline_result.get("risk_flags") or []) + (pipeline_result.get("advisory_flags") or []):
        if not isinstance(f, dict):
            continue
        code = f.get("code", "")
        label = _FLAG_LABELS.get(code, code.replace("_", " ").title())
        ln = (f.get("detail") or {}).get("line_number")
        if ln is not None:
            try:
                idx = int(ln) - 1
            except (ValueError, TypeError):
                continue
            if code not in seen_per_line.setdefault(idx, set()):
                seen_per_line[idx].add(code)
                _add(idx, label)
        elif code in _LINE_TABLE_ALL_FLAGS:
            for i in range(num_lines):
                if code not in seen_per_line.setdefault(i, set()):
                    seen_per_line[i].add(code)
                    _add(i, label)

    return result


_ZONE_TEXT_CSS = {
    "green": "background-color: #c3e6cb; color: #155724",
    "amber": "background-color: #ffeeba; color: #856404",
    "red":   "background-color: #f5c6cb; color: #721c24",
}


def _apply_match_reason_style(df, zones):
    styles = pd.DataFrame("", index=df.index, columns=df.columns)
    if "Match Reason" in df.columns:
        col_pos = list(df.columns).index("Match Reason")
        for row_pos, zone in enumerate(zones):
            if row_pos < len(df):
                styles.iloc[row_pos, col_pos] = _ZONE_TEXT_CSS.get(zone, "")
    return styles


# Only structural match failures explain why a line received its zone.
# Advisory/risk-flag exceptions (e.g. rate_card_price_mismatch) are already
# shown in the Flags column and must not appear in Match Reason.
_MATCH_REASON_EXCEPTION_TYPES = {
    "no_match",
    "po_ceiling_exhausted",
    "qty_over_received",
    "gr_fully_consumed",
    "no_accepted_gr",
    "gr_inspection_rejected",
    "invoice_before_gr",
    "zero_price_po_line_at_match",
    "data_integrity_violation",
    "no_rate_card_match",
    "rate_card_price_mismatch",
}

# Header-level stub exceptions stored in header_exceptions (no line_id).
# Distributed to all lines when no per-line match result exists.
_MATCH_REASON_HEADER_EXCEPTION_TYPES = {
    "po_not_found",
    "po_cancelled",
    "po_closed",
    "po_all_lines_closed",
    "cannot_match_no_vendor",
    "cannot_match_no_contract",
    "no_rate_card_configured",
    "contract_not_found",
    "billing_period_unverified",
    "billing_period_outside_contract",
    "contract_currency_mismatch",
    "contract_budget_exceeded",
    "vendor_mismatch",
    "currency_mismatch",
    "ambiguous_active_contract",
    "cannot_match_missing_contract_invoice",
}


def _mr_exception_text(exc_type: str, exc, p_var=None, q_var=None) -> str:
    detail = getattr(exc, "exception_detail", None) or {}
    if exc_type == "no_match":
        return "No matching PO line found"
    if exc_type == "po_ceiling_exhausted":
        return "PO ceiling exhausted β€” total invoiced quantity exceeds available PO quantity"
    if exc_type == "qty_over_received":
        pct = detail.get("qty_over_pct") or (detail.get("subset_breakdown") or {}).get("qty_over_pct")
        if pct is not None:
            try:
                return f"Qty {float(pct):.1f}% over accepted GR quantity"
            except (ValueError, TypeError):
                pass
        return "Qty exceeds accepted GR quantity"
    if exc_type == "gr_fully_consumed":
        return "GR quantity fully consumed by prior invoices"
    if exc_type == "no_accepted_gr":
        return "No accepted goods receipt found"
    if exc_type == "gr_inspection_rejected":
        return "GR inspection rejected"
    if exc_type == "invoice_before_gr":
        return "Invoice date precedes goods receipt"
    if exc_type == "po_not_found":
        return "No matching purchase order found"
    if exc_type == "po_cancelled":
        return "Purchase order is cancelled"
    if exc_type == "po_closed":
        return "Purchase order is closed"
    if exc_type == "po_all_lines_closed":
        return "All PO lines are closed or cancelled"
    if exc_type == "cannot_match_no_vendor":
        return "Vendor could not be identified for matching"
    if exc_type == "no_rate_card_configured":
        return "No rate card configured for this vendor"
    if exc_type == "billing_period_unverified":
        return "Service period dates missing β€” cannot verify billing period"
    if exc_type == "billing_period_outside_contract":
        return "Service period is outside the contract window"
    if exc_type == "contract_currency_mismatch":
        return "Invoice currency does not match the contract"
    if exc_type == "contract_budget_exceeded":
        return "Invoice would exceed the contract budget"
    if exc_type == "cannot_match_no_contract":
        return "No contract found for this vendor"
    if exc_type == "contract_not_found":
        return "No active contract found for this vendor"
    if exc_type == "zero_price_po_line_at_match":
        return "PO line has zero unit price β€” cannot match"
    if exc_type == "vendor_mismatch":
        return "Vendor does not match purchase order"
    if exc_type == "currency_mismatch":
        return "Invoice currency does not match PO currency"
    if exc_type == "data_integrity_violation":
        return "Data integrity violation β€” GR quantity accepted is NULL"
    if exc_type == "no_rate_card_match":
        return "Invoice line could not be matched to any rate card item"
    if exc_type == "rate_card_price_mismatch":
        return "Line price exceeds rate card tolerance"
    if exc_type == "ambiguous_active_contract":
        return "Multiple active contracts found β€” cannot determine which applies"
    if exc_type == "cannot_match_missing_contract_invoice":
        return "Contract matching could not proceed β€” contract invoice data missing"
    return ""


def _mr_variance_text(zone: str, p_var, q_var) -> str:
    near = "near threshold" if zone == "amber" else "exceeds threshold"
    parts = []
    if p_var is not None and float(p_var) > 0:
        parts.append(f"Price variance {float(p_var):.1f}% ({near})")
    if q_var is not None and float(q_var) > 0:
        parts.append(f"Qty variance {float(q_var):.1f}% ({near})")
    if not parts:
        return f"Variance {near}"
    return "; ".join(parts)


# Advisory flags raised by the matching layer that describe why price/type
# comparison was skipped.  They have no MatchExceptionRecord so they are
# surfaced here rather than through the exception path.
_ADVISORY_MATCH_REASON: dict = {
    "item_type_unresolved":          "Item type (goods/services) could not be resolved β€” type check skipped",
    "rate_card_match_no_price_compare": "Rate card matched β€” price comparison skipped (no price configured)",
}


def build_match_reason_column(pipeline_result, num_lines: int) -> list:
    """Return list of (reason_text, zone) per line based on match results."""
    if not pipeline_result or num_lines == 0:
        return [("", "green")] * num_lines
    result = [("", "green")] * num_lines
    mr = pipeline_result.get("match_result")
    if mr is None:
        return result
    # Collect advisory-based match reason overrides (apply to every green line).
    _adv_codes = {
        (f.get("code") if isinstance(f, dict) else str(f))
        for f in (pipeline_result.get("advisory_flags") or [])
    }
    _adv_match_reason = " | ".join(
        text for code, text in _ADVISORY_MATCH_REASON.items() if code in _adv_codes
    ) or None

    line_result_map = {
        getattr(mlr, "invoice_line_id", None): mlr
        for mlr in (getattr(mr, "match_line_results", None) or [])
        if getattr(mlr, "invoice_line_id", None) is not None
    }
    exc_map: dict = {}
    for exc in (getattr(mr, "match_exceptions", None) or []):
        lid = getattr(exc, "line_id", None)
        if lid is not None and getattr(exc, "exception_type", "") in _MATCH_REASON_EXCEPTION_TYPES:
            exc_map.setdefault(lid, []).append(exc)

    # match_exceptions with no line_id that explain the result for every line.
    # Includes both structural per-line types (invoice_before_gr) and infrastructure
    # types (no_rate_card_configured, contract_not_found) that live in match_exceptions
    # rather than header_exceptions.
    _all_reason_types = _MATCH_REASON_EXCEPTION_TYPES | _MATCH_REASON_HEADER_EXCEPTION_TYPES
    global_match_excs = [
        exc for exc in (getattr(mr, "match_exceptions", None) or [])
        if getattr(exc, "line_id", None) is None
        and getattr(exc, "exception_type", "") in _all_reason_types
    ]

    # Stub-route header exceptions (po_not_found, cannot_match_no_vendor, etc.)
    # stored in header_exceptions β€” distribute to all lines when no per-line result exists.
    header_excs = [
        exc for exc in (getattr(mr, "header_exceptions", None) or [])
        if getattr(exc, "exception_type", "") in _MATCH_REASON_HEADER_EXCEPTION_TYPES
    ]

    for i in range(num_lines):
        line_id = i + 1
        mlr = line_result_map.get(line_id)
        excs = exc_map.get(line_id, [])
        if mlr is None and not excs:
            fallback = global_match_excs or header_excs
            if fallback:
                texts = [_mr_exception_text(getattr(e, "exception_type", ""), e) for e in fallback]
                result[i] = (" | ".join(t for t in texts if t), "red")
            continue
        if mlr is None:
            texts = [_mr_exception_text(getattr(e, "exception_type", ""), e) for e in excs]
            result[i] = (" | ".join(t for t in texts if t), "red")
            continue
        zone = getattr(mlr, "line_zone", "green") or "green"
        p_var = getattr(mlr, "price_var_pct", None)
        q_var = getattr(mlr, "qty_var_pct", None)
        # Per-line exceptions take priority; global exceptions (invoice_before_gr) override
        # a green zone since the 3-way check doesn't update line_zone for header-level issues.
        # Header exceptions (vendor_mismatch, currency_mismatch) override a per-line green
        # result when the match is structurally invalid at the header level.
        active_excs = excs or global_match_excs or header_excs
        if active_excs:
            exc_zone = zone if excs else "red"
            texts = [_mr_exception_text(getattr(e, "exception_type", ""), e, p_var, q_var) for e in active_excs]
            result[i] = (" | ".join(t for t in texts if t), exc_zone)
        elif zone == "green":
            result[i] = (_adv_match_reason or "Matched within tolerance", "green")
        else:
            result[i] = (_mr_variance_text(zone, p_var, q_var), zone)
    return result


def render_field_flag(flags: list) -> None:
    for f in flags:
        code = f.get("code", "")
        label = _FLAG_LABELS.get(code, code.replace("_", " ").title())
        if f.get("severity") == "advisory":
            st.markdown(
                f'<div style="background-color:#FFF3CD;color:#856404;border-radius:5px;padding:6px 10px;margin:2px 0;font-size:13px;">⚠️ {label}</div>',
                unsafe_allow_html=True,
            )
        else:
            st.markdown(
                f'<div style="background-color:#FFDADA;color:#8B0000;border-radius:5px;padding:6px 10px;margin:2px 0;font-size:13px;">🚩 {label}</div>',
                unsafe_allow_html=True,
            )


# Fields whose flags check mathematical consistency (not master-data validation).
_FIELD_AMOUNT_CHECK = {"Subtotal", "Total Tax", "Total Amount"}
# Fields whose flags check date consistency (not master-data validation).
_FIELD_DATE_CHECK = {"Due Date"}
# Fields only checked for presence (e.g. "missing_invoice_number") β€” no real
# validation logic exists for these, so no "βœ“ Validated" claim should be made.
_FIELD_PRESENCE_ONLY_CHECK = {"Invoice Number"}

# Fields whose underlying validator is skipped (not just flag-free) when the
# named step is absent β€” most commonly because resolved_vendor_id is None.
_FIELD_SKIP_STEP_MAP: dict = {
    "Tax ID":         {"tax_id_validation"},
    "Bank IBAN":      {"bank_validation"},
    "Account Number": {"bank_validation"},
    "Account Name":   {"bank_validation"},
    "SWIFT":          {"bank_validation"},
}


def _field_skip_reason(pipeline_result, field_name: str):
    steps = _FIELD_SKIP_STEP_MAP.get(field_name)
    if not steps:
        return None
    for s in (pipeline_result.get("skipped_steps") or []):
        if isinstance(s, dict) and s.get("step") in steps:
            return s.get("skip_reason", "")
    return None


def render_field_status(pipeline_result, field_name: str) -> None:
    """Show flag badges when issues found; green status badge when no issues."""
    flags = get_field_flags(pipeline_result, field_name)
    if pipeline_result and field_name in _FIELD_FLAG_MAP:
        if not flags:
            skip_reason = _field_skip_reason(pipeline_result, field_name)
            if skip_reason:
                st.markdown(
                    f'<div style="background-color:#E5E7EB;color:#374151;border-radius:5px;'
                    f'padding:4px 10px;margin:2px 0;font-size:12px;">⏭ Skipped β€” {skip_reason.replace("_", " ")}</div>',
                    unsafe_allow_html=True,
                )
            else:
                if field_name in _FIELD_AMOUNT_CHECK:
                    msg = "βœ“ Amounts Reconciled"
                elif field_name in _FIELD_DATE_CHECK or field_name in _FIELD_PRESENCE_ONLY_CHECK:
                    msg = ""
                else:
                    msg = "βœ“ Validated"
                if msg:
                    st.markdown(
                        f'<div style="background-color:#D1FAE5;color:#065F46;border-radius:5px;'
                        f'padding:4px 10px;margin:2px 0;font-size:12px;">{msg}</div>',
                        unsafe_allow_html=True,
                    )
    render_field_flag(flags)


def render_vendor_match(
    pipeline_result: dict,
    master_data: dict,
    selected_hash: str = "",
    edited_data: Optional[dict] = None,
    pipeline_configs: Optional[dict] = None,
) -> None:
    if not pipeline_result or not master_data:
        return
    vendors = master_data.get("vendors") or []
    resolved_id = pipeline_result.get("resolved_vendor_id")
    if resolved_id is None:
        suggestion = next(
            (f for f in (pipeline_result.get("advisory_flags") or [])
             if isinstance(f, dict) and f.get("code") == "vendor_suggestion"),
            None,
        )
        if not suggestion or suggestion.get("record_id") is None:
            return
        candidate = next(
            (v for v in vendors if getattr(v, "id", None) == suggestion["record_id"]),
            None,
        )
        if not candidate:
            return
        candidate_name = getattr(candidate, "vendor_name", "") or getattr(candidate, "legal_name", "") or ""
        if not candidate_name:
            return

        decision_key = f"vendor_suggestion_decision_{selected_hash}"
        decision = st.session_state.get(decision_key)

        if decision == "no":
            st.markdown(
                f'<div style="display:inline-block;background-color:#FEE2E2;color:#991B1B;border-radius:5px;padding:6px 10px;margin:2px 0;font-size:13px;">'
                f'βœ— Vendor suggestion ({candidate_name}) declined β€” vendor unresolved, downstream validation stopped.</div>',
                unsafe_allow_html=True,
            )
            return

        st.markdown(
            """
            <style>
            [class*="st-key-vendor_suggest_yes_"] button {
                background-color: #16A34A !important;
                color: white !important;
                border-color: #16A34A !important;
                padding: 2px 10px !important;
                font-size: 12px !important;
                min-height: 0 !important;
            }
            [class*="st-key-vendor_suggest_no_"] button {
                background-color: #DC2626 !important;
                color: white !important;
                border-color: #DC2626 !important;
                padding: 2px 10px !important;
                font-size: 12px !important;
                min-height: 0 !important;
            }
            </style>
            """,
            unsafe_allow_html=True,
        )
        col_msg, col_yes, col_no, _col_rest = st.columns([3, 1, 1, 5], gap="small")
        with col_msg:
            st.markdown(
                f'<div style="display:inline-block;background-color:#FEF3C7;color:#92400E;border-radius:5px;padding:0px 1px;margin:2px 0;font-size:13px;">'
                f'⚠ Did you mean: <b>{candidate_name}</b>?</div>',
                unsafe_allow_html=True,
            )
        with col_yes:
            if st.button("βœ“", key=f"vendor_suggest_yes_{selected_hash}"):
                new_edited_data = dict(edited_data or {})
                new_edited_data["Sender Name"] = candidate_name
                st.session_state.batch_results[selected_hash]["edited_data"] = new_edited_data
                st.session_state[f"Sender Name_{selected_hash}"] = candidate_name
                st.session_state.pop(decision_key, None)
                try:
                    _pr = build_and_run_pipeline(new_edited_data, master_data, pipeline_configs or {})
                except Exception as _e:
                    _pr = {
                        "final_status": "exception", "error": str(_e),
                        "risk_flags": [], "advisory_flags": [],
                        "match_result": None, "route": "error",
                    }
                st.session_state.batch_results[selected_hash]["pipeline_result"] = _pr
                st.rerun()
        with col_no:
            if st.button("βœ—", key=f"vendor_suggest_no_{selected_hash}"):
                st.session_state[decision_key] = "no"
                st.rerun()
        return
    vendor = next(
        (v for v in vendors if getattr(v, "id", None) == resolved_id),
        None,
    )
    if vendor:
        name = getattr(vendor, "vendor_name", "") or getattr(vendor, "legal_name", "") or ""
        if name:
            _risk_codes = {
                (f.get("code") if isinstance(f, dict) else str(f))
                for f in (pipeline_result.get("risk_flags") or [])
            }
            if "vendor_blocked" not in _risk_codes:
                st.markdown(
                    f'<div style="background-color:#D1FAE5;color:#065F46;border-radius:5px;padding:6px 10px;margin:2px 0;font-size:13px;">βœ“ Vendor validated as: {name}</div>',
                    unsafe_allow_html=True,
                )


def _effective_final_status(pipeline_result) -> str:
    """Return displayed final status driven by match zone: green→matched, amber→partial_match, red→exception."""
    status = (pipeline_result or {}).get("final_status", "")
    if status not in ("matched", "exception"):
        return status
    mr = (pipeline_result or {}).get("match_result")
    if mr is None:
        return status
    overall_zone = getattr(mr, "match_zone", None)
    if overall_zone == "red":
        return "exception"
    if overall_zone == "amber":
        return "partial_match"
    # overall_zone is green or unset β€” check individual line zones
    line_zones = {getattr(mlr, "line_zone", None) for mlr in (getattr(mr, "match_line_results", None) or [])}
    if "red" in line_zones:
        return "exception"
    if "amber" in line_zones:
        return "partial_match"
    return status


def render_status_badge(pipeline_result) -> None:
    if not pipeline_result:
        return
    final_status = _effective_final_status(pipeline_result)
    route = pipeline_result.get("route", "")
    def _flag_codes(lst):
        seen, codes = set(), set()
        for f in (lst or []):
            c = f.get("code") if isinstance(f, dict) else str(f)
            if c and c not in seen:
                seen.add(c); codes.add(c)
        return codes
    risk_count = len(_flag_codes(pipeline_result.get("risk_flags")))
    adv_count  = len(_flag_codes(pipeline_result.get("advisory_flags")))
    mr = pipeline_result.get("match_result")
    _mexc_types = {getattr(e, "exception_type", "") for e in (getattr(mr, "match_exceptions", None) or [])} if mr else set()
    _hexc_types = {getattr(e, "exception_type", "") for e in (getattr(mr, "header_exceptions", None) or [])} if mr else set()
    match_exc_count = len(_mexc_types | _hexc_types)
    color_map = {"matched": "#1a7a1a", "partial_match": "#b8860b", "exception": "#c0392b"}
    label_map = {"matched": "Matched", "partial_match": "Partial Match", "exception": "Exception"}
    color = color_map.get(final_status, "#666666")
    label = label_map.get(final_status, final_status.replace("_", " ").title() if final_status else "Pending")
    parts = []
    if risk_count:
        parts.append(f"{risk_count} risk flag{'s' if risk_count != 1 else ''}")
    if adv_count:
        parts.append(f"{adv_count} advisory")
        _seen_adv: set = set()
        for f in (pipeline_result.get("advisory_flags") or []):
            code = f.get("code") if isinstance(f, dict) else str(f)
            if code and code not in _seen_adv:
                _seen_adv.add(code)
                lbl = _FLAG_LABELS.get(code, "")
                if lbl:
                    parts.append(lbl)
    if match_exc_count:
        parts.append(f"{match_exc_count} match exception{'s' if match_exc_count != 1 else ''}")
    # Always surface zone-based variance reason when red/amber and actual variance exists
    if mr:
        overall_zone = getattr(mr, "match_zone", None)
        line_results = getattr(mr, "match_line_results", None) or []
        if overall_zone is None:
            line_zones = [getattr(mlr, "line_zone", None) for mlr in line_results]
            overall_zone = "red" if "red" in line_zones else ("amber" if "amber" in line_zones else None)
        if overall_zone in ("red", "amber"):
            suffix = "exceeds threshold" if overall_zone == "red" else "near threshold"
            has_price = any((getattr(mlr, "price_var_pct", None) or 0) > 0 for mlr in line_results)
            has_qty   = any((getattr(mlr, "qty_var_pct",   None) or 0) > 0 for mlr in line_results)
            # qty_over_received stores over-qty in exception_detail, not qty_var_pct
            if not has_qty:
                has_qty = any(
                    getattr(exc, "exception_type", "") == "qty_over_received"
                    for exc in (getattr(mr, "match_exceptions", None) or [])
                )
            variance_parts = []
            if has_price:
                variance_parts.append(f"price variance {suffix}")
            if has_qty:
                variance_parts.append(f"qty variance {suffix}")
            if variance_parts:
                parts.append(" & ".join(variance_parts))
        # Add human-readable reason for structural exceptions not covered by variance note
        _all_excs = list(getattr(mr, "match_exceptions", None) or []) + list(getattr(mr, "header_exceptions", None) or [])
        _seen_exc_types: set = set()
        for exc in _all_excs:
            et = getattr(exc, "exception_type", "")
            if not et or et in _seen_exc_types:
                continue
            _seen_exc_types.add(et)
            if et == "qty_over_received":
                continue  # already covered by "qty variance near/exceeds threshold"
            text = _mr_exception_text(et, exc)
            if text:
                parts.append(text)
    subtitle = " | ".join(parts) if parts else "No flags"
    route_label = route.replace("_", " ").title() if route else "β€”"
    error_msg = pipeline_result.get("error", "")
    error_html = f"<br><span style='font-size:11px;opacity:0.85;'>Error: {error_msg}</span>" if error_msg else ""
    st.markdown(
        f"<div style='background:{color};color:white;padding:8px 14px;border-radius:6px;"
        f"margin-bottom:8px;'>"
        f"<span style='font-size:15px;font-weight:bold;'>{label}</span>"
        f"&nbsp;&nbsp;<span style='font-size:12px;opacity:0.9;'>Route: {route_label}</span><br>"
        f"<span style='font-size:12px;opacity:0.9;'>{subtitle}</span>"
        f"{error_html}</div>",
        unsafe_allow_html=True,
    )


def render_matching_result(pipeline_result) -> None:
    if not pipeline_result:
        return
    mr = pipeline_result.get("match_result")
    risk_flags = pipeline_result.get("risk_flags") or []
    adv_flags  = pipeline_result.get("advisory_flags") or []

    with st.expander("Route & Match Details", expanded=False):
        c1, c2 = st.columns(2)
        with c1:
            st.write(f"**Route:** {pipeline_result.get('route', 'N/A')}")
            st.write(f"**Final Status:** {_effective_final_status(pipeline_result).replace('_', ' ').title() or 'N/A'}")
        with c2:
            if mr:
                st.write(f"**Match Zone:** {getattr(mr, 'match_zone', 'N/A')}")
                st.write(f"**Match Status:** {getattr(mr, 'overall_status', 'N/A')}")
        if mr:
            st.write(
                f"Lines: {getattr(mr, 'lines_matched', 0)} matched / "
                f"{getattr(mr, 'lines_in_exception', 0)} in exception / "
                f"{getattr(mr, 'lines_total', 0)} total"
            )
            for exc in (getattr(mr, "header_exceptions", None) or []):
                st.error(f"Header: {getattr(exc, 'exception_type', '')}")
            for exc in (getattr(mr, "match_exceptions", None) or []):
                st.warning(f"Line {getattr(exc, 'line_id', '?')}: {getattr(exc, 'exception_type', '')}")
        if pipeline_result.get("error"):
            st.error(f"Error: {pipeline_result['error']}")

    if risk_flags:
        with st.expander(f"Risk Flags ({len(risk_flags)})", expanded=True):
            for f in risk_flags:
                code = f.get("code", str(f)) if isinstance(f, dict) else str(f)
                st.error(f"**{code}** β€” {_FLAG_LABELS.get(code, code.replace('_', ' ').title())}")

    if adv_flags:
        with st.expander(f"Advisory Flags ({len(adv_flags)})", expanded=False):
            for f in adv_flags:
                code = f.get("code", str(f)) if isinstance(f, dict) else str(f)
                st.warning(f"**{code}** β€” {_FLAG_LABELS.get(code, code.replace('_', ' ').title())}")


# -----------------------------
# Session scaffolding
# -----------------------------
if "batch_results" not in st.session_state:
    st.session_state.batch_results = {}
if "current_file_hash" not in st.session_state:
    st.session_state.current_file_hash = None
if "is_processing_batch" not in st.session_state:
    st.session_state.is_processing_batch = False
if "confirm_back" not in st.session_state:
    st.session_state.confirm_back = False
if "master_data" not in st.session_state:
    st.session_state.master_data = {}
if "pipeline_configs" not in st.session_state:
    st.session_state.pipeline_configs = load_default_configs()
for _mk in ["validation_master_hash", "po_master_hash", "gr_master_hash", "contract_master_hash"]:
    if _mk not in st.session_state:
        st.session_state[_mk] = None
ensure_state("page", "Master Files")

# ── Navigation β€” custom overlay panel, no native st.sidebar ────────────────────
# Driven entirely by session_state: opening/closing the panel is just a normal
# Streamlit rerun, so "click an item -> panel closes" can't get stuck in a loop.
ensure_state("nav_open", False)

_toggle_label = "βœ•" if st.session_state.nav_open else "☰"
if st.button(_toggle_label, key="sidebar_toggle_btn"):
    st.session_state.nav_open = not st.session_state.nav_open
    st.rerun()

if st.session_state.nav_open:
    with st.container(key="nav_overlay_panel"):
        st.markdown("**Navigation**")
        _current_page = st.session_state.get("page", "Invoice Upload")
        # All 3 are always buttons β€” same element type, same wrapper height, zero layout shift.
        # Active page gets a β–Έ prefix so the user knows where they are.
        for _pg in ["Master Files", "Config", "Invoice Upload"]:
            _label = f"β–Έ  {_pg}" if _pg == _current_page else _pg
            if st.button(_label, key=f"nav_{_pg.replace(' ','_')}", use_container_width=True):
                st.session_state.page = _pg
                st.session_state.nav_open = False
                st.rerun()
        st.divider()
        _n_inv = len(st.session_state.batch_results)
        st.caption(f"{_n_inv} invoice{'s' if _n_inv != 1 else ''} loaded")
        if _n_inv > 0:
            if st.button("Clear All", key="sidebar_clear_all"):
                st.session_state.batch_results.clear()
                st.session_state.current_file_hash = None
                st.session_state.is_processing_batch = False
                st.session_state.confirm_back = False
                st.session_state.nav_open = False
                st.rerun()

_active_page = st.session_state.get("page", "Invoice Upload")

# ── Config page ───────────────────────────────────────────────────────────────
if _active_page == "Config":
    st.header("Config")
    if not _pipeline_available:
        st.info(f"Pipeline unavailable: {_pipeline_import_error}")
    _cfg = st.session_state.pipeline_configs
    _pc  = _cfg.get("platform_configs") or {}
    _mc  = _cfg.get("matching_configs") or {}

    col_cfg1, col_cfg2 = st.columns(2)
    with col_cfg1:
        st.subheader("Validation Thresholds")
        _new_pc: dict = {}
        _new_pc["validation.rapidfuzz_high_threshold"] = st.number_input(
            "Fuzzy High", value=float(_pc.get("validation.rapidfuzz_high_threshold", 0.90)),
            min_value=0.0, max_value=1.0, step=0.01, format="%.2f", key="cfg_rfuzz_h")
        _new_pc["validation.rapidfuzz_medium_threshold"] = st.number_input(
            "Fuzzy Medium", value=float(_pc.get("validation.rapidfuzz_medium_threshold", 0.75)),
            min_value=0.0, max_value=1.0, step=0.01, format="%.2f", key="cfg_rfuzz_m")
        _new_pc["validation.rapidfuzz_suggestion_threshold"] = st.number_input(
            "Fuzzy Suggestion", value=float(_pc.get("validation.rapidfuzz_suggestion_threshold", 0.60)),
            min_value=0.0, max_value=1.0, step=0.01, format="%.2f", key="cfg_rfuzz_s")
        _new_pc["validation.iban_checksum_required"] = st.checkbox(
            "IBAN Checksum Required",
            value=bool(_pc.get("validation.iban_checksum_required", True)), key="cfg_iban")
        _new_pc["validation.max_invoice_age_days"] = st.number_input(
            "Max Invoice Age (days)", value=int(_pc.get("validation.max_invoice_age_days", 365)),
            min_value=0, step=1, key="cfg_max_age")
        _new_pc["validation.payment_terms_tolerance_days"] = st.number_input(
            "Payment Terms Tolerance (days)",
            value=int(_pc.get("validation.payment_terms_tolerance_days", 2)),
            min_value=0, step=1, key="cfg_pt_tol")
        _new_pc["validation.tax_rate_match_tolerance"] = str(st.number_input(
            "Tax Rate Tolerance",
            value=float(_pc.get("validation.tax_rate_match_tolerance", 0.0001)),
            min_value=0.0, step=0.0001, format="%.6f", key="cfg_tax_tol"))
        _new_pc["validation.solver_tolerance.cap_minor_units"] = st.number_input(
            "Solver Cap Minor Units",
            value=int(_pc.get("validation.solver_tolerance.cap_minor_units", 5)),
            min_value=0, step=1, key="cfg_sol_cap")
        _new_pc["validation.solver_tolerance.base_per_minor_unit"] = st.number_input(
            "Solver Base Per Minor Unit",
            value=int(_pc.get("validation.solver_tolerance.base_per_minor_unit", 1)),
            min_value=0, step=1, key="cfg_sol_base")
        _new_pc["validation.solver_tolerance.per_line_minor_units"] = st.number_input(
            "Solver Per Line Minor Units",
            value=int(_pc.get("validation.solver_tolerance.per_line_minor_units", 1)),
            min_value=0, step=1, key="cfg_sol_line")
        for _k, _v in _pc.items():
            if _k not in _new_pc:
                _new_pc[_k] = _v

    with col_cfg2:
        st.subheader("Matching Thresholds")
        _new_mc: dict = {}
        _new_mc["tier3_price_variance_threshold"] = st.number_input(
            "Tier3 Price Variance", value=float(_mc.get("tier3_price_variance_threshold", 0.10)),
            min_value=0.0, step=0.01, format="%.2f", key="cfg_t3pv")
        st.write("**Price (Goods)**")
        _new_mc["price_goods_green"] = st.number_input(
            "Green %", value=float(_mc.get("price_goods_green", 5.0)), min_value=0.0, step=0.5, key="cfg_pg_g")
        _new_mc["price_goods_amber"] = st.number_input(
            "Amber %", value=float(_mc.get("price_goods_amber", 10.0)), min_value=0.0, step=0.5, key="cfg_pg_a")
        st.write("**Price (Services)**")
        _new_mc["price_services_green"] = st.number_input(
            "Green %", value=float(_mc.get("price_services_green", 10.0)), min_value=0.0, step=0.5, key="cfg_ps_g")
        _new_mc["price_services_amber"] = st.number_input(
            "Amber %", value=float(_mc.get("price_services_amber", 15.0)), min_value=0.0, step=0.5, key="cfg_ps_a")
        st.write("**Qty (Goods)**")
        _new_mc["qty_goods_green"] = st.number_input(
            "Green %", value=float(_mc.get("qty_goods_green", 2.0)), min_value=0.0, step=0.5, key="cfg_qg_g")
        _new_mc["qty_goods_amber"] = st.number_input(
            "Amber %", value=float(_mc.get("qty_goods_amber", 4.0)), min_value=0.0, step=0.5, key="cfg_qg_a")
        st.write("**Qty (Services)**")
        _new_mc["qty_services_green"] = st.number_input(
            "Green %", value=float(_mc.get("qty_services_green", 3.0)), min_value=0.0, step=0.5, key="cfg_qs_g")
        _new_mc["qty_services_amber"] = st.number_input(
            "Amber %", value=float(_mc.get("qty_services_amber", 6.0)), min_value=0.0, step=0.5, key="cfg_qs_a")
        st.write("**Fuzzy**")
        _new_mc["fuzzy_high_threshold"] = st.number_input(
            "High", value=float(_mc.get("fuzzy_high_threshold", 90.0)),
            min_value=0.0, max_value=100.0, step=1.0, key="cfg_fz_h")
        _new_mc["fuzzy_medium_threshold"] = st.number_input(
            "Medium", value=float(_mc.get("fuzzy_medium_threshold", 80.0)),
            min_value=0.0, max_value=100.0, step=1.0, key="cfg_fz_m")
        _new_mc["fuzzy_score_cutoff"] = st.number_input(
            "Score Cutoff", value=float(_mc.get("fuzzy_score_cutoff", 80.0)),
            min_value=0.0, max_value=100.0, step=1.0, key="cfg_fz_c")
        for _k, _v in _mc.items():
            if _k not in _new_mc:
                _new_mc[_k] = _v

    if st.button("Save Config Changes", key="main_save_config"):
        st.session_state.pipeline_configs = {"platform_configs": _new_pc, "matching_configs": _new_mc}
        st.success("Config saved.")
    st.stop()

# ── Master Files page ──────────────────────────────────────────────────────────
elif _active_page == "Master Files":
    st.header("Master Files")
    st.write("Upload Excel master files below. Once loaded they are used automatically during invoice validation and matching.")

    mf_col1, mf_col2 = st.columns(2)
    with mf_col1:
        _val_f = st.file_uploader("Validation Master (.xlsx)", type=["xlsx"], key="sb_val_master")
        if _val_f is not None:
            _fhv = hashlib.sha256(_val_f.read()).hexdigest(); _val_f.seek(0)
            if st.session_state.get("validation_master_hash") != _fhv:
                try:
                    st.session_state.master_data.update(parse_validation_master(_val_f.read()))
                    st.session_state["validation_master_hash"] = _fhv
                    st.session_state["validation_master_name"] = _val_f.name
                except Exception as _ex:
                    st.error(f"Validation Master error: {_ex}")
        if st.session_state.get("validation_master_hash"):
            st.markdown(f"βœ… **{st.session_state.get('validation_master_name', 'validation_master.xlsx')}** loaded")
        else:
            st.caption("⬜ Not loaded")

        _po_f = st.file_uploader("PO Master (.xlsx)", type=["xlsx"], key="sb_po_master")
        if _po_f is not None:
            _fhp = hashlib.sha256(_po_f.read()).hexdigest(); _po_f.seek(0)
            if st.session_state.get("po_master_hash") != _fhp:
                try:
                    st.session_state.master_data.update(parse_po_master(_po_f.read()))
                    st.session_state["po_master_hash"] = _fhp
                    st.session_state["po_master_name"] = _po_f.name
                except Exception as _ex:
                    st.error(f"PO Master error: {_ex}")
        if st.session_state.get("po_master_hash"):
            st.markdown(f"βœ… **{st.session_state.get('po_master_name', 'po_master.xlsx')}** loaded")
        else:
            st.caption("⬜ Not loaded")

    with mf_col2:
        _gr_f = st.file_uploader("GR Master (.xlsx)", type=["xlsx"], key="sb_gr_master")
        if _gr_f is not None:
            _fhg = hashlib.sha256(_gr_f.read()).hexdigest(); _gr_f.seek(0)
            if st.session_state.get("gr_master_hash") != _fhg:
                try:
                    st.session_state.master_data.update(parse_gr_master(_gr_f.read()))
                    st.session_state["gr_master_hash"] = _fhg
                    st.session_state["gr_master_name"] = _gr_f.name
                except Exception as _ex:
                    st.error(f"GR Master error: {_ex}")
        if st.session_state.get("gr_master_hash"):
            st.markdown(f"βœ… **{st.session_state.get('gr_master_name', 'gr_master.xlsx')}** loaded")
        else:
            st.caption("⬜ Not loaded")

        _ct_f = st.file_uploader("Contract Master (.xlsx)", type=["xlsx"], key="sb_contract_master")
        if _ct_f is not None:
            _fhc = hashlib.sha256(_ct_f.read()).hexdigest(); _ct_f.seek(0)
            if st.session_state.get("contract_master_hash") != _fhc:
                try:
                    st.session_state.master_data.update(parse_contract_master(_ct_f.read()))
                    st.session_state["contract_master_hash"] = _fhc
                    st.session_state["contract_master_name"] = _ct_f.name
                except Exception as _ex:
                    st.error(f"Contract Master error: {_ex}")
        if st.session_state.get("contract_master_hash"):
            st.markdown(f"βœ… **{st.session_state.get('contract_master_name', 'contract_master.xlsx')}** loaded")
        else:
            st.caption("⬜ Not loaded")
    st.stop()

# ── Invoice Upload page ────────────────────────────────────────────────────────
frame_left, frame_right = st.columns([1, 1], vertical_alignment="top")

# =============================================================================
# UPLOAD & BATCH PROCESSING
# =============================================================================
if not st.session_state.is_processing_batch and len(st.session_state.batch_results) == 0:
    with frame_left:
        st.header("πŸ“€ Upload Invoices")
        uploaded_files = st.file_uploader(
            "Upload invoice PDFs, images, JSON, or JSONL files (JSON/JSONL bypasses OCR β€” use for testing)",
            type=["png", "jpg", "jpeg", "pdf", "json", "jsonl"],
            accept_multiple_files=True
        )

        if uploaded_files:
            st.session_state.is_processing_batch = True
            progress_bar = st.progress(0)
            status_text  = st.empty()

            for idx, uploaded_file in enumerate(uploaded_files):
                status_text.text(f"Processing {idx+1}/{len(uploaded_files)}: {uploaded_file.name}")
                uploaded_bytes = uploaded_file.read()
                fname_lower    = uploaded_file.name.lower()

                # ------------------------------------------------------------------
                # JSONL: expand each line into a separate invoice record
                # ------------------------------------------------------------------
                if fname_lower.endswith(".jsonl"):
                    raw_text  = uploaded_bytes.decode("utf-8")
                    jsonl_lines = [l.strip() for l in raw_text.splitlines() if l.strip()]
                    ok = skip = 0
                    for line_idx, line_text in enumerate(jsonl_lines):
                        line_hash = hashlib.sha256(line_text.encode("utf-8")).hexdigest()
                        if line_hash in st.session_state.batch_results:
                            skip += 1
                            continue
                        try:
                            _rpd, _pd = parse_vllm_json(line_text)
                            if not _pd:
                                st.warning(f"{uploaded_file.name} line {line_idx+1}: could not parse fields, skipped.")
                                skip += 1
                                continue
                            _mapped  = validate_and_calculate_taxes(_pd)
                            _sm      = _mapped if isinstance(_mapped, dict) else {}
                            _dr      = prepare_processed_invoice_data(_rpd or {}, _sm)
                            _sm      = _dr if isinstance(_dr, dict) else _sm
                            _entry   = {
                                "file_name":       f"{uploaded_file.name}[{line_idx+1}]",
                                "pages":           [],
                                "current_page":    0,
                                "raw_pred":        line_text,
                                "raw_parsed_data": _rpd or {},
                                "mapped_data":     _sm,
                                "edited_data":     _sm.copy(),
                                "user_saved_edits": False,
                                "pipeline_result": None,
                            }
                            st.session_state.batch_results[line_hash] = _entry
                            if _pipeline_available and st.session_state.get("master_data"):
                                try:
                                    _pr = build_and_run_pipeline(_sm, st.session_state.master_data, st.session_state.pipeline_configs)
                                    st.session_state.batch_results[line_hash]["pipeline_result"] = _pr
                                except Exception as _pe:
                                    st.session_state.batch_results[line_hash]["pipeline_result"] = {
                                        "final_status": "exception", "error": str(_pe),
                                        "risk_flags": [], "advisory_flags": [],
                                        "match_result": None, "route": "error",
                                    }
                            ok += 1
                        except Exception as exc:
                            st.warning(f"{uploaded_file.name} line {line_idx+1}: {exc}")
                            skip += 1
                    if jsonl_lines:
                        st.info(f"{uploaded_file.name}: {ok} invoice(s) loaded, {skip} skipped.")
                    progress_bar.progress((idx + 1) / len(uploaded_files))
                    continue

                # ------------------------------------------------------------------
                # Single-record JSON / PDF / image
                # ------------------------------------------------------------------
                file_hash = hashlib.sha256(uploaded_bytes).hexdigest()
                if file_hash in st.session_state.batch_results:
                    progress_bar.progress((idx + 1) / len(uploaded_files))
                    continue

                pages   = []
                is_json = fname_lower.endswith(".json")

                if is_json:
                    try:
                        json_text = uploaded_bytes.decode("utf-8")
                        raw_parsed_data, parsed_data = parse_vllm_json(json_text)
                        if not parsed_data:
                            st.warning(f"Could not parse JSON fields from {uploaded_file.name}. Check the format.")
                            progress_bar.progress((idx + 1) / len(uploaded_files))
                            continue
                        mapped       = validate_and_calculate_taxes(parsed_data)
                        safe_mapped  = mapped if isinstance(mapped, dict) else {}
                        display_ready = prepare_processed_invoice_data(raw_parsed_data or {}, safe_mapped)
                        safe_mapped  = display_ready if isinstance(display_ready, dict) else safe_mapped
                        raw_json     = json_text
                        raw_parsed_data = raw_parsed_data or {}
                    except Exception as exc:
                        st.warning(f"Failed to load JSON {uploaded_file.name}: {exc}")
                        progress_bar.progress((idx + 1) / len(uploaded_files))
                        continue
                else:
                    is_pdf = (
                        fname_lower.endswith(".pdf")
                        or (hasattr(uploaded_file, "type") and uploaded_file.type == "application/pdf")
                    )
                    if is_pdf:
                        if convert_from_bytes is None and _fitz is None:
                            st.warning(f"PDF {uploaded_file.name} could not be rendered β€” install poppler or PyMuPDF.")
                            progress_bar.progress((idx + 1) / len(uploaded_files))
                            continue
                        try:
                            pages = _pdf_to_images(uploaded_bytes, dpi=300)
                            if not pages:
                                st.warning(f"PDF {uploaded_file.name} has no pages.")
                                progress_bar.progress((idx + 1) / len(uploaded_files))
                                continue
                            st.info(f"{uploaded_file.name}: {len(pages)} page(s) detected β€” all sent in one request.")
                        except Exception as exc:
                            st.warning(f"Could not render PDF {uploaded_file.name}: {exc}")
                            progress_bar.progress((idx + 1) / len(uploaded_files))
                            continue
                    else:
                        try:
                            img = Image.open(BytesIO(uploaded_bytes)).convert("RGB")
                            pages.append(img)
                        except Exception:
                            st.warning(f"Failed to open {uploaded_file.name}.")
                            progress_bar.progress((idx + 1) / len(uploaded_files))
                            continue

                    if not pages:
                        progress_bar.progress((idx + 1) / len(uploaded_files))
                        continue

                    raw_json, raw_parsed_data, safe_mapped = _run_extraction(pages)
                    if raw_json is None:
                        st.warning(f"No response from vLLM for {uploaded_file.name}")
                        progress_bar.progress((idx + 1) / len(uploaded_files))
                        continue

                st.session_state.batch_results[file_hash] = {
                    "file_name":    uploaded_file.name,
                    "pages":        pages,
                    "current_page": 0,
                    "raw_pred":     raw_json,
                    "raw_parsed_data": raw_parsed_data,
                    "mapped_data":  safe_mapped,
                    "edited_data":  safe_mapped.copy(),
                    "user_saved_edits": False,
                    "pipeline_result": None,
                }
                if _pipeline_available and st.session_state.get("master_data"):
                    try:
                        _pr = build_and_run_pipeline(
                            safe_mapped,
                            st.session_state.master_data,
                            st.session_state.pipeline_configs,
                        )
                        st.session_state.batch_results[file_hash]["pipeline_result"] = _pr
                    except Exception as _pe:
                        st.session_state.batch_results[file_hash]["pipeline_result"] = {
                            "final_status": "exception", "error": str(_pe),
                            "risk_flags": [], "advisory_flags": [],
                            "match_result": None, "route": "error",
                        }

                progress_bar.progress((idx + 1) / len(uploaded_files))

            status_text.text("βœ… All files processed!")
            st.session_state.is_processing_batch = False
            st.rerun()

    with frame_right:
        st.caption("Preview & editor will appear here after extraction.")

# =============================================================================
# REVIEW & EDIT
# =============================================================================
elif len(st.session_state.batch_results) > 0:

    with frame_left:
        all_rows = []
        for file_hash, result in st.session_state.batch_results.items():
            processed_result = display_data_for_result(result)
            rows = flatten_invoice_to_rows(processed_result)
            for r in rows:
                r["Source File"] = result.get("file_name", file_hash)
            all_rows.extend(rows)

        if all_rows:
            full_df = pd.DataFrame(all_rows)
            cols    = list(full_df.columns)
            if "Source File" in cols:
                cols    = ["Source File"] + [c for c in cols if c != "Source File"]
                full_df = full_df[cols]

            dl_cols = st.columns(3)
            with dl_cols[0]:
                st.download_button("πŸ“¦ All CSV",
                                   full_df.to_csv(index=False).encode("utf-8"),
                                   file_name="all_extracted_invoices.csv",
                                   mime="text/csv",
                                   key="download_all_csv")
            with dl_cols[1]:
                st.download_button("πŸ“¦ All Excel",
                                   build_excel_bytes(full_df),
                                   file_name="all_extracted_invoices.xlsx",
                                   mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                                   key="download_all_xlsx")
            with dl_cols[2]:
                jsonl_lines = [
                    json.dumps(
                        convert_to_jsonl_record(
                            display_data_for_result(res),
                            res.get("file_name", ""),
                            len(res.get("pages", []))
                        ),
                        ensure_ascii=False
                    )
                    for res in st.session_state.batch_results.values()
                ]
                st.download_button("πŸ“¦ All JSONL",
                                   "\n".join(jsonl_lines).encode("utf-8"),
                                   file_name="all_extracted_invoices.jsonl",
                                   mime="application/jsonl",
                                   key="download_all_jsonl")

    with frame_right:
        if st.button("⬅️ Back to Upload"):
            st.session_state[f"confirm_back"] = True

        if st.session_state.get("confirm_back"):
            st.warning("⚠️ All extracted data will be lost. Are you sure?")
            col_yes, col_no = st.columns(2)
            with col_yes:
                if st.button("βœ… Yes, go back"):
                    st.session_state.batch_results.clear()
                    st.session_state.current_file_hash = None
                    st.session_state.is_processing_batch = False
                    st.session_state.confirm_back = False
                    st.rerun()
            with col_no:
                if st.button("❌ Cancel"):
                    st.session_state.confirm_back = False
                    st.rerun()

    with frame_left:
        file_options     = {f"{v['file_name']} ({k[:6]})": k for k, v in st.session_state.batch_results.items()}
        selected_display = st.selectbox("Select invoice to view/edit:",
                                        options=list(file_options.keys()),
                                        index=0,
                                        key="file_selector")
        selected_hash    = file_options[selected_display]

        if st.session_state.current_file_hash != selected_hash:
            if st.session_state.current_file_hash is not None:
                old_hash = st.session_state.current_file_hash
                for k in [k for k in st.session_state.keys() if k.endswith(f"_{old_hash}")]:
                    del st.session_state[k]
            st.session_state.current_file_hash = selected_hash

    current      = st.session_state.batch_results[selected_hash]
    pages        = current["pages"]
    num_pages    = len(pages)
    cur_page_idx = current.get("current_page", 0)
    form_data    = display_data_for_result(current)

    bank          = form_data.get("Bank Details", {}) if isinstance(form_data.get("Bank Details", {}), dict) else {}
    form_currency = form_data.get("Currency", "")

    # State defaults β€” editable numeric values stay numeric so saves round-trip cleanly.
    state_defaults = {
        f"Invoice Number_{selected_hash}":           form_data.get("Invoice Number", ""),
        f"PO Number_{selected_hash}":                form_data.get("PO Number", ""),
        f"Payment Terms_{selected_hash}":            form_data.get("Payment Terms", ""),
        f"Tax ID_{selected_hash}":                   form_data.get("Tax ID", ""),
        f"Currency_{selected_hash}":                 form_data.get("Currency", "USD") or "USD",
        f"Currency_Custom_{selected_hash}":          form_data.get("Currency", "") if form_data.get("Currency") not in ["USD","EUR","GBP","INR"] else "",
        f"Subtotal_{selected_hash}":                 editable_numeric_value("Subtotal", form_data.get("Subtotal", 0.0)),
        f"Tax Percentage_{selected_hash}":           editable_numeric_value("Tax Percentage", form_data.get("Tax Percentage", 0.0)),
        f"Total Tax_{selected_hash}":                editable_numeric_value("Total Tax", form_data.get("Total Tax", 0.0)),
        f"Discount Rate_{selected_hash}":            editable_numeric_value("Discount Rate", form_data.get("Discount Rate", 0.0)),
        f"Total Discount Amount_{selected_hash}":    editable_numeric_value("Total Discount Amount", form_data.get("Total Discount Amount", 0.0)),
        f"Total Amount_{selected_hash}":             editable_numeric_value("Total Amount", form_data.get("Total Amount", 0.0)),
        f"Sender Name_{selected_hash}":              form_data.get("Sender Name", ""),
        f"Sender Address_{selected_hash}":           form_data.get("Sender Address", ""),
        f"Recipient Name_{selected_hash}":           form_data.get("Recipient Name", ""),
        f"Recipient Address_{selected_hash}":        form_data.get("Recipient Address", ""),
        f"Bank_bank_name_{selected_hash}":           bank.get("bank_name", ""),
        f"Bank_bank_account_number_{selected_hash}": bank.get("bank_account_number", "") or bank.get("bank_acc_no", ""),
        f"Bank_bank_acc_name_{selected_hash}":       bank.get("bank_acc_name", "") or bank.get("bank_account_holder", ""),
        f"Bank_bank_iban_{selected_hash}":           bank.get("bank_iban", ""),
        f"Bank_bank_swift_{selected_hash}":          bank.get("bank_swift", ""),
        f"Bank_bank_routing_{selected_hash}":        bank.get("bank_routing", ""),
        f"Bank_bank_branch_{selected_hash}":         bank.get("bank_branch", ""),
    }
    for key, default in state_defaults.items():
        if key not in st.session_state:
            st.session_state[key] = default

    numeric_state_fields = {
        "Subtotal": f"Subtotal_{selected_hash}",
        "Tax Percentage": f"Tax Percentage_{selected_hash}",
        "Total Tax": f"Total Tax_{selected_hash}",
        "Discount Rate": f"Discount Rate_{selected_hash}",
        "Total Discount Amount": f"Total Discount Amount_{selected_hash}",
        "Total Amount": f"Total Amount_{selected_hash}",
    }
    for field, key in numeric_state_fields.items():
        st.session_state[key] = editable_numeric_value(field, st.session_state.get(key, 0.0))

    if f"Invoice Date_{selected_hash}" not in st.session_state:
        st.session_state[f"Invoice Date_{selected_hash}"] = parse_date_to_object(form_data.get("Invoice Date", ""), form_currency)
    if f"Due Date_{selected_hash}" not in st.session_state:
        st.session_state[f"Due Date_{selected_hash}"] = parse_date_to_object(form_data.get("Due Date", ""), form_currency)

    # Raw strings from model β€” used for ground truth output, never overwritten by date picker
    if f"Invoice Date_raw_{selected_hash}" not in st.session_state:
        st.session_state[f"Invoice Date_raw_{selected_hash}"] = form_data.get("Invoice Date", "")
    if f"Due Date_raw_{selected_hash}" not in st.session_state:
        st.session_state[f"Due Date_raw_{selected_hash}"] = form_data.get("Due Date", "")

    # =========================================================================
    # LEFT COLUMN β€” image preview
    # =========================================================================
    with frame_left:
        if num_pages > 0:
            st.image(pages[cur_page_idx],
                     caption=f"{current['file_name']} β€” Page {cur_page_idx + 1} of {num_pages}",
                     use_container_width=True)

            if num_pages > 1:
                nav_cols = st.columns([1, 2, 1])
                with nav_cols[0]:
                    if st.button("⬅️ Prev", disabled=(cur_page_idx == 0), key=f"prev_page_{selected_hash}"):
                        st.session_state.batch_results[selected_hash]["current_page"] = cur_page_idx - 1
                        st.rerun()
                with nav_cols[1]:
                    st.markdown(f"<p style='text-align:center;'>Page {cur_page_idx + 1} / {num_pages}</p>",
                                unsafe_allow_html=True)
                with nav_cols[2]:
                    if st.button("Next ➑️", disabled=(cur_page_idx == num_pages - 1), key=f"next_page_{selected_hash}"):
                        st.session_state.batch_results[selected_hash]["current_page"] = cur_page_idx + 1
                        st.rerun()

            st.write(f"**File Hash:** `{selected_hash[:8]}…`  |  **Pages:** {num_pages}")

            col_a, col_b = st.columns(2)

            with col_a:
                if st.button("πŸ” Re-Run (All Pages)", key=f"rerun_all_{selected_hash}",
                             help=f"Re-send all {num_pages} page(s) in one request"):
                    with st.spinner(f"Re-running inference on all {num_pages} page(s)…"):
                        try:
                            raw_json, raw_parsed_data, safe_mapped = _run_extraction(pages)
                            if raw_json is None:
                                st.error("No response from vLLM.")
                            else:
                                st.session_state.batch_results[selected_hash]["raw_pred"]    = raw_json
                                st.session_state.batch_results[selected_hash]["raw_parsed_data"] = raw_parsed_data
                                st.session_state.batch_results[selected_hash]["mapped_data"] = safe_mapped
                                st.session_state.batch_results[selected_hash]["edited_data"] = safe_mapped.copy()
                                st.session_state.batch_results[selected_hash]["user_saved_edits"] = False
                                st.session_state.batch_results[selected_hash]["pipeline_result"] = None
                                if _pipeline_available and st.session_state.get("master_data"):
                                    try:
                                        _pr = build_and_run_pipeline(safe_mapped, st.session_state.master_data, st.session_state.pipeline_configs)
                                        st.session_state.batch_results[selected_hash]["pipeline_result"] = _pr
                                    except Exception as _pe:
                                        st.session_state.batch_results[selected_hash]["pipeline_result"] = {"final_status": "exception", "error": str(_pe), "risk_flags": [], "advisory_flags": [], "match_result": None, "route": "error"}
                                for k in [k for k in st.session_state.keys() if k.endswith(f"_{selected_hash}")]:
                                    del st.session_state[k]
                                st.success("βœ… Re-run complete (all pages)")
                                st.rerun()
                        except Exception as e:
                            st.error(f"Re-run failed: {e}")

            with col_b:
                if st.button(f"πŸ” Extract Page {cur_page_idx + 1} Only", key=f"extract_page_{selected_hash}",
                             help="Send only the currently displayed page"):
                    with st.spinner(f"Running inference on page {cur_page_idx + 1} only…"):
                        try:
                            raw_json, raw_parsed_data, safe_mapped = _run_extraction([pages[cur_page_idx]])
                            if raw_json is None:
                                st.error("No response from vLLM.")
                            else:
                                st.session_state.batch_results[selected_hash]["raw_pred"]    = raw_json
                                st.session_state.batch_results[selected_hash]["raw_parsed_data"] = raw_parsed_data
                                st.session_state.batch_results[selected_hash]["mapped_data"] = safe_mapped
                                st.session_state.batch_results[selected_hash]["edited_data"] = safe_mapped.copy()
                                st.session_state.batch_results[selected_hash]["user_saved_edits"] = False
                                st.session_state.batch_results[selected_hash]["pipeline_result"] = None
                                if _pipeline_available and st.session_state.get("master_data"):
                                    try:
                                        _pr = build_and_run_pipeline(safe_mapped, st.session_state.master_data, st.session_state.pipeline_configs)
                                        st.session_state.batch_results[selected_hash]["pipeline_result"] = _pr
                                    except Exception as _pe:
                                        st.session_state.batch_results[selected_hash]["pipeline_result"] = {"final_status": "exception", "error": str(_pe), "risk_flags": [], "advisory_flags": [], "match_result": None, "route": "error"}
                                for k in [k for k in st.session_state.keys() if k.endswith(f"_{selected_hash}")]:
                                    del st.session_state[k]
                                st.success(f"βœ… Page {cur_page_idx + 1} extracted!")
                                st.rerun()
                        except Exception as e:
                            st.error(f"Extraction failed: {e}")
        else:
            st.info("JSON upload β€” no image preview available.")
            st.write(f"**File:** `{current['file_name']}`  |  **Source:** JSON")

        with st.expander("πŸ” Show raw model output"):
            raw_pred = current.get("raw_pred")
            if raw_pred is None:
                st.warning("No raw output available.")
            else:
                st.code(str(raw_pred), language="json")

    # =========================================================================
    # RIGHT COLUMN β€” editable form
    # =========================================================================
    with frame_right:
        st.subheader(f"Editable Invoice: {current['file_name']}")
        pipeline_result = current.get("pipeline_result")
        render_status_badge(pipeline_result)

        if pipeline_result is None and not st.session_state.get("master_data"):
            st.info("ℹ️ Validation and matching have been skipped β€” no master files uploaded. Upload master files on the **Master Files** page, then click **Re-run Pipeline**.")

        if st.button("Re-run Pipeline", key=f"rerun_pipeline_{selected_hash}"):
            if st.session_state.get("master_data"):
                try:
                    _pr = build_and_run_pipeline(
                        current.get("edited_data", {}),
                        st.session_state.master_data,
                        st.session_state.pipeline_configs,
                    )
                    st.session_state.batch_results[selected_hash]["pipeline_result"] = _pr
                    st.rerun()
                except Exception as _e:
                    st.error(f"Pipeline error: {_e}")
            else:
                st.warning("No master data loaded.")

        # Live widgets: keep the data editor outside a form so dynamic row adds/deletes are saved before downloads.
        tabs = st.tabs(["Invoice Details", "Sender/Recipient", "Bank Details", "Line Items"])

        with tabs[0]:
            render_field_status(pipeline_result, "Invoice Number")
            st.text_input("Invoice Number", key=f"Invoice Number_{selected_hash}")
            render_field_status(pipeline_result, "PO Number")
            st.text_input("PO Number",      key=f"PO Number_{selected_hash}")

            render_field_status(pipeline_result, "Invoice Date")
            st.write("**Invoice Date:**")
            raw_invoice_date = form_data.get("Invoice Date", "")
            if raw_invoice_date:
                st.info(f"πŸ“… Model extracted: {raw_invoice_date}")
            st.date_input("Select date:", key=f"Invoice Date_{selected_hash}",
                          format="DD/MM/YYYY", label_visibility="collapsed")

            render_field_status(pipeline_result, "Payment Terms")
            st.text_input("Payment Terms", key=f"Payment Terms_{selected_hash}")

            render_field_status(pipeline_result, "Due Date")
            st.write("**Due Date:**")
            raw_due_date = form_data.get("Due Date", "")
            if raw_due_date:
                st.info(f"πŸ“… Model extracted: {raw_due_date}")
            st.date_input("Select date:", key=f"Due Date_{selected_hash}",
                          format="DD/MM/YYYY", label_visibility="collapsed")

            render_field_status(pipeline_result, "Tax ID")
            st.text_input("Tax ID / VAT Number", key=f"Tax ID_{selected_hash}")

            render_field_status(pipeline_result, "Currency")
            curr_options = ["USD", "EUR", "GBP", "INR", "Other"]
            if st.session_state[f"Currency_{selected_hash}"] not in curr_options:
                st.session_state[f"Currency_{selected_hash}"] = "Other"
            st.selectbox("Currency", options=curr_options, key=f"Currency_{selected_hash}")
            if st.session_state.get(f"Currency_{selected_hash}") == "Other":
                st.text_input("Specify Currency", key=f"Currency_Custom_{selected_hash}")

            render_field_status(pipeline_result, "Subtotal")
            st.number_input("Subtotal",              key=f"Subtotal_{selected_hash}",              format="%.3f", step=0.001)
            render_field_status(pipeline_result, "Tax Percentage")
            st.number_input("Tax %",                 key=f"Tax Percentage_{selected_hash}",        format="%.3f", step=0.001)
            render_field_status(pipeline_result, "Total Tax")
            st.number_input("Total Tax",             key=f"Total Tax_{selected_hash}",             format="%.3f", step=0.001)
            st.number_input("Discount Rate %",       key=f"Discount Rate_{selected_hash}",         format="%.3f", step=0.001)
            st.number_input("Total Discount Amount", key=f"Total Discount Amount_{selected_hash}", format="%.3f", step=0.001)
            render_field_status(pipeline_result, "Total Amount")
            st.number_input("Total Amount",          key=f"Total Amount_{selected_hash}",          format="%.3f", step=0.001)

        with tabs[1]:
            render_vendor_match(
                pipeline_result,
                st.session_state.get("master_data") or {},
                selected_hash=selected_hash,
                edited_data=current.get("edited_data", {}),
                pipeline_configs=st.session_state.pipeline_configs,
            )
            render_field_status(pipeline_result, "Sender Name")
            st.text_input("Sender Name",       key=f"Sender Name_{selected_hash}")
            st.text_area ("Sender Address",    key=f"Sender Address_{selected_hash}",    height=80)
            st.text_input("Recipient Name",    key=f"Recipient Name_{selected_hash}")
            st.text_area ("Recipient Address", key=f"Recipient Address_{selected_hash}", height=80)

        with tabs[2]:
            st.text_input("Bank Name",       key=f"Bank_bank_name_{selected_hash}")
            render_field_status(pipeline_result, "Account Number")
            st.text_input("Account Number",  key=f"Bank_bank_account_number_{selected_hash}")
            render_field_status(pipeline_result, "Account Name")
            st.text_input("Account Name",    key=f"Bank_bank_acc_name_{selected_hash}")
            render_field_status(pipeline_result, "Bank IBAN")
            st.text_input("IBAN",            key=f"Bank_bank_iban_{selected_hash}")
            render_field_status(pipeline_result, "SWIFT")
            st.text_input("SWIFT",           key=f"Bank_bank_swift_{selected_hash}")
            st.text_input("Routing",         key=f"Bank_bank_routing_{selected_hash}")
            st.text_input("Branch",          key=f"Bank_bank_branch_{selected_hash}")

        with tabs[3]:
            items_state_key = f"items_df_{selected_hash}"

            if items_state_key not in st.session_state:
                item_rows  = form_data.get("Itemized Data", []) or []
                normalized = []
                for it in item_rows:
                    if not isinstance(it, dict):
                        it = {}
                    normalized.append({
                        "Description":              it.get("Description", it.get("Item Description", "")),
                        "Service Name":             it.get("Service Name", ""),
                        "Service Start Date":       it.get("Service Start Date", ""),
                        "Service End Date":         it.get("Service End Date", ""),
                        "SKU":                      it.get("SKU", ""),
                        "Quantity":                 editable_numeric_value("Quantity", it.get("Quantity", it.get("Item Quantity", 0.0))),
                        "Unit Price":               editable_numeric_value("Unit Price", it.get("Unit Price", it.get("Item Unit Price", 0.0))),
                        "Amount":                   editable_numeric_value("Amount", it.get("Amount", it.get("Item Amount", 0.0))),
                        "Discount Rate Per Item":   editable_numeric_value("Discount Rate Per Item", it.get("Discount Rate Per Item", 0.0)),
                        "Discount Amount Per Item": editable_numeric_value("Discount Amount Per Item", it.get("Discount Amount Per Item", 0.0)),
                        "Tax Rate Per Item":        editable_numeric_value("Tax Rate Per Item", it.get("Tax Rate Per Item", 0.0)),
                        "Tax Amount Per Item":      editable_numeric_value("Tax Amount Per Item", it.get("Tax Amount Per Item", 0.0)),
                        "IO Number/Cost Centre":    it.get("IO Number/Cost Centre", ""),
                        "Line Total":               editable_numeric_value("Line Total", it.get("Line Total", it.get("Item Line Total", 0.0))),
                    })
                st.session_state[items_state_key] = coerce_numeric_items_df(
                    pd.DataFrame(normalized) if normalized
                    else pd.DataFrame(columns=[
                        "Description", "Service Name", "Service Start Date", "Service End Date", "SKU",
                        "Quantity", "Unit Price", "Amount",
                        "Discount Rate Per Item", "Discount Amount Per Item",
                        "Tax Rate Per Item", "Tax Amount Per Item",
                        "IO Number/Cost Centre", "Line Total"
                    ])
                )

            items_df = coerce_numeric_items_df(st.session_state[items_state_key])

            # Build read-only display columns
            _flags_col = build_flags_column(pipeline_result, len(items_df))
            _reason_col = build_match_reason_column(pipeline_result, len(items_df))
            _reason_texts = [r for r, _ in _reason_col]
            _reason_zones = [z for _, z in _reason_col]

            items_df_display = items_df.copy()
            items_df_display.insert(0, "Flags", _flags_col)
            items_df_display.insert(1, "Match Reason", _reason_texts)

            _display_col_config = {
                "Flags":                    st.column_config.TextColumn("Flags",          width="large"),
                "Match Reason":             st.column_config.TextColumn("Match Reason",   width="medium"),
                "Description":              st.column_config.TextColumn("Description",    width="large"),
                "Service Name":             st.column_config.TextColumn("Service Name",   width="medium"),
                "Service Start Date":       st.column_config.TextColumn("Svc Start",      width="small"),
                "Service End Date":         st.column_config.TextColumn("Svc End",        width="small"),
                "SKU":                      st.column_config.TextColumn("SKU",            width="small"),
                "GL Account":               st.column_config.TextColumn("GL Account",     width="small"),
                "Quantity":                 st.column_config.NumberColumn("Qty",          width="small", format="%.3f"),
                "Unit Price":               st.column_config.NumberColumn("Unit Price",   width="small", format="%.3f"),
                "Amount":                   st.column_config.NumberColumn("Amount",       width="small", format="%.3f"),
                "Discount Rate Per Item":   st.column_config.NumberColumn("Disc %",       width="small", format="%.3f"),
                "Discount Amount Per Item": st.column_config.NumberColumn("Disc Amt",     width="small", format="%.3f"),
                "Tax Rate Per Item":        st.column_config.NumberColumn("Tax %",        width="small", format="%.3f"),
                "Tax Amount Per Item":      st.column_config.NumberColumn("Tax Amt",      width="small", format="%.3f"),
                "IO Number/Cost Centre":    st.column_config.TextColumn("IO/Cost Centre", width="medium"),
                "Line Total":               st.column_config.NumberColumn("Line Total",   width="small", format="%.3f"),
            }

            try:
                _styled = items_df_display.style.apply(
                    _apply_match_reason_style, zones=_reason_zones, axis=None
                )
                st.dataframe(
                    _styled,
                    use_container_width=True,
                    height=DATA_EDITOR_HEIGHT,
                    column_config=_display_col_config,
                )
            except AttributeError:
                # pandas Styler requires jinja2; fall back to emoji zone indicators
                _zone_emoji = {"green": "🟒", "amber": "🟑", "red": "πŸ”΄"}
                _fb_df = items_df_display.copy()
                _fb_df["Match Reason"] = [
                    " | ".join(
                        f"{_zone_emoji.get(z, '')} {seg}".strip()
                        for seg in t.split(" | ") if seg
                    ) if t else ""
                    for t, z in zip(_reason_texts, _reason_zones)
                ]
                st.dataframe(
                    _fb_df,
                    use_container_width=True,
                    height=DATA_EDITOR_HEIGHT,
                    column_config=_display_col_config,
                )

            _edit_col_config = {
                "Description":              st.column_config.TextColumn("Description",    width="large"),
                "Service Name":             st.column_config.TextColumn("Service Name",   width="medium"),
                "Service Start Date":       st.column_config.TextColumn("Svc Start",      width="small"),
                "Service End Date":         st.column_config.TextColumn("Svc End",        width="small"),
                "SKU":                      st.column_config.TextColumn("SKU",            width="small"),
                "GL Account":               st.column_config.TextColumn("GL Account",     width="small"),
                "Quantity":                 st.column_config.NumberColumn("Qty",          width="small", format="%.3f", step=0.001),
                "Unit Price":               st.column_config.NumberColumn("Unit Price",   width="small", format="%.3f", step=0.001),
                "Amount":                   st.column_config.NumberColumn("Amount",       width="small", format="%.3f", step=0.001),
                "Discount Rate Per Item":   st.column_config.NumberColumn("Disc %",       width="small", format="%.3f", step=0.001),
                "Discount Amount Per Item": st.column_config.NumberColumn("Disc Amt",     width="small", format="%.3f", step=0.001),
                "Tax Rate Per Item":        st.column_config.NumberColumn("Tax %",        width="small", format="%.3f", step=0.001),
                "Tax Amount Per Item":      st.column_config.NumberColumn("Tax Amt",      width="small", format="%.3f", step=0.001),
                "IO Number/Cost Centre":    st.column_config.TextColumn("IO/Cost Centre", width="medium"),
                "Line Total":               st.column_config.NumberColumn("Line Total",   width="small", format="%.3f", step=0.001),
            }

            editor_key = f"items_editor_{selected_hash}"
            with st.expander("✏️ Edit Line Items", expanded=False):
                edited_df = st.data_editor(
                    items_df,
                    num_rows="dynamic",
                    key=editor_key,
                    use_container_width=True,
                    height=DATA_EDITOR_HEIGHT,
                    column_config=_edit_col_config,
                )

        saved = st.button("πŸ’Ύ Save All Edits", key=f"save_all_edits_{selected_hash}")

        currency = st.session_state.get(f"Currency_{selected_hash}", "USD")
        if currency == "Other":
            currency = st.session_state.get(f"Currency_Custom_{selected_hash}", "")

        items_state_key  = f"items_df_{selected_hash}"
        current_items_df = coerce_numeric_items_df(st.session_state.get(items_state_key, pd.DataFrame()))
        st.session_state[items_state_key] = current_items_df
        line_items_list  = current_items_df.to_dict("records")

        def _build_updated_dict():
            current_df = apply_data_editor_state(
                st.session_state.get(items_state_key, pd.DataFrame()),
                st.session_state.get(f"items_editor_{selected_hash}"),
            )
            current_df = current_df.drop(columns=["Flags", "Match Reason"], errors="ignore")
            current_line_items = current_df.to_dict("records")
            updated = {
                "Invoice Number":        st.session_state.get(f"Invoice Number_{selected_hash}", ""),
                "PO Number":             st.session_state.get(f"PO Number_{selected_hash}", ""),
                # Raw model string β€” not the date picker's reformatted value
                "Invoice Date":          st.session_state.get(f"Invoice Date_raw_{selected_hash}", ""),
                "Payment Terms":         st.session_state.get(f"Payment Terms_{selected_hash}", ""),
                "Due Date":              st.session_state.get(f"Due Date_raw_{selected_hash}", ""),
                "Tax ID":                st.session_state.get(f"Tax ID_{selected_hash}", ""),
                "Currency":              currency,
                "Subtotal":              editable_numeric_value("Subtotal", st.session_state.get(f"Subtotal_{selected_hash}", 0.0)),
                "Tax Percentage":        editable_numeric_value("Tax Percentage", st.session_state.get(f"Tax Percentage_{selected_hash}", 0.0)),
                "Total Tax":             editable_numeric_value("Total Tax", st.session_state.get(f"Total Tax_{selected_hash}", 0.0)),
                "Discount Rate":         editable_numeric_value("Discount Rate", st.session_state.get(f"Discount Rate_{selected_hash}", 0.0)),
                "Total Discount Amount": editable_numeric_value("Total Discount Amount", st.session_state.get(f"Total Discount Amount_{selected_hash}", 0.0)),
                "Total Amount":          editable_numeric_value("Total Amount", st.session_state.get(f"Total Amount_{selected_hash}", 0.0)),
                "Sender Name":           st.session_state.get(f"Sender Name_{selected_hash}", ""),
                "Sender Address":        st.session_state.get(f"Sender Address_{selected_hash}", ""),
                "Recipient Name":        st.session_state.get(f"Recipient Name_{selected_hash}", ""),
                "Recipient Address":     st.session_state.get(f"Recipient Address_{selected_hash}", ""),
                "Bank Details": {
                    "bank_name":           st.session_state.get(f"Bank_bank_name_{selected_hash}", ""),
                    "bank_account_number": st.session_state.get(f"Bank_bank_account_number_{selected_hash}", ""),
                    "bank_acc_name":       st.session_state.get(f"Bank_bank_acc_name_{selected_hash}", ""),
                    "bank_iban":           st.session_state.get(f"Bank_bank_iban_{selected_hash}", ""),
                    "bank_swift":          st.session_state.get(f"Bank_bank_swift_{selected_hash}", ""),
                    "bank_routing":        st.session_state.get(f"Bank_bank_routing_{selected_hash}", ""),
                    "bank_branch":         st.session_state.get(f"Bank_bank_branch_{selected_hash}", ""),
                },
                "Itemized Data": current_line_items,
                "Sender":    {"Name": st.session_state.get(f"Sender Name_{selected_hash}", ""),
                              "Address": st.session_state.get(f"Sender Address_{selected_hash}", "")},
                "Recipient": {"Name": st.session_state.get(f"Recipient Name_{selected_hash}", ""),
                              "Address": st.session_state.get(f"Recipient Address_{selected_hash}", "")},
            }
            return limit_invoice_decimals(updated)

        if saved:
            updated = _build_updated_dict()
            # Persist user-edited date picker values back as the date strings
            invoice_date = st.session_state.get(f"Invoice Date_{selected_hash}")
            due_date     = st.session_state.get(f"Due Date_{selected_hash}")
            if invoice_date is not None:
                try:
                    updated["Invoice Date"] = invoice_date.strftime("%d-%b-%Y")
                    st.session_state[f"Invoice Date_raw_{selected_hash}"] = invoice_date.strftime("%d-%b-%Y")
                except (AttributeError, ValueError):
                    pass
            if due_date is not None:
                try:
                    updated["Due Date"] = due_date.strftime("%d-%b-%Y")
                    st.session_state[f"Due Date_raw_{selected_hash}"] = due_date.strftime("%d-%b-%Y")
                except (AttributeError, ValueError):
                    pass
            updated = limit_invoice_decimals(updated)
            st.session_state.batch_results[selected_hash]["edited_data"] = updated
            st.session_state.batch_results[selected_hash]["user_saved_edits"] = True
            if _pipeline_available and st.session_state.get("master_data"):
                try:
                    _pr = build_and_run_pipeline(updated, st.session_state.master_data, st.session_state.pipeline_configs)
                    st.session_state.batch_results[selected_hash]["pipeline_result"] = _pr
                except Exception as _pe:
                    st.session_state.batch_results[selected_hash]["pipeline_result"] = {"final_status": "exception", "error": str(_pe), "risk_flags": [], "advisory_flags": [], "match_result": None, "route": "error"}
            for k in [k for k in list(st.session_state.keys()) if k.endswith(f"_{selected_hash}")]:
                del st.session_state[k]
            st.success("βœ… Saved")
            st.rerun()

        download_data = limit_invoice_decimals(_build_updated_dict())
        rows          = flatten_invoice_to_rows(download_data)
        file_df       = pd.DataFrame(rows)
        file_stem     = Path(current["file_name"]).stem

        per_dl_cols = st.columns(3)
        with per_dl_cols[0]:
            st.download_button("πŸ“₯ CSV",
                               file_df.to_csv(index=False).encode("utf-8"),
                               file_name=f"{file_stem}_full.csv",
                               mime="text/csv",
                               key=f"dl_csv_{selected_hash}")
        with per_dl_cols[1]:
            st.download_button("πŸ“₯ Excel",
                               build_excel_bytes(file_df),
                               file_name=f"{file_stem}_full.xlsx",
                               mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                               key=f"dl_xlsx_{selected_hash}")
        with per_dl_cols[2]:
            record    = convert_to_jsonl_record(download_data, current["file_name"], num_pages)
            jsonl_one = json.dumps(record, ensure_ascii=False).encode("utf-8")
            st.download_button("πŸ“₯ JSONL",
                               jsonl_one,
                               file_name=f"{file_stem}.jsonl",
                               mime="application/jsonl",
                               key=f"dl_jsonl_{selected_hash}")

        render_matching_result(pipeline_result)

# =============================================================================
# Processing placeholder
# =============================================================================
elif st.session_state.is_processing_batch:
    with frame_left:
        st.info("⏳ Processing batch… Please wait.")
        st.progress(0)
    with frame_right:
        st.caption("Preview & editor will appear here after extraction.")

else:
    with frame_left:
        st.caption("Ready when you are.")
    with frame_right:
        st.caption("Preview & editor will appear here after extraction.")