File size: 295,946 Bytes
a52bae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d07b40
 
 
 
 
 
a52bae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
# ============================================================================
# app.py β€” Agentic AI Systems for Large Scale Content Analysis
# ============================================================================
#
# PURPOSE
# -------
# A chat-driven Gradio app that demonstrates FOUR different backend
# implementations of the same agent task, side by side. This file is the
# UI SHELL ONLY β€” it owns the chat, the tabs, the data source loaders,
# the training panels, and the download list. It knows nothing about how
# any individual backend works; it dispatches through a 4-symbol contract.
#
# THE FOUR BACKENDS
# -----------------
#   agent_workflow.py   β€” Workflow: 2-step prompt chain, no tools (raw SDK)
#   agent_py.py         β€” Simple Python Agent: tool-calling loop (raw SDK)
#   agent_langchain.py  β€” LangChain AgentExecutor with tool calling
#   agent_langgraph.py  β€” LangGraph state graph with supervisor + task nodes
#
# THE CONTRACT (every backend file exports these four symbols)
# ------------------------------------------------------------
#   BACKEND_NAME               β€” string shown in the UI radio
#   get_client(api_key)        β€” returns whatever 'client' the runner needs
#   run(client, user_message)  β€” returns {"reply", "steps", "extracted"}
#   build_code_snippets(user_message, steps) -> str  β€” for the Code tab
#
# Adding a new backend = new file with these four symbols, then one
# import line in ZONE 2 and a registration into BACKENDS dict. No
# handler, UI, or wiring changes.
#
# GRACEFUL DEGRADATION
# --------------------
# agent_langchain and agent_langgraph are imported inside try/except.
# If langchain / langchain-mistralai / langgraph are not installed, those
# modes are silently hidden from the radio at startup and a warning prints
# to the console. The app keeps running with Workflow + Simple Python Agent.
#
# CODE ORGANIZATION
# -----------------
#   ZONE 1: Imports & constants
#   ZONE 2: Backend imports + helpers (save_json_artifact, build_outputs, ...)
#   ZONE 3: Action handlers (wired to UI buttons)
#   ZONE 4: UI definition (gr.Blocks)
#   ZONE 5: Event wiring (.click handlers β€” the glue)
#
# LOGICAL FLOW OF ONE CHAT TURN
# -----------------------------
# User types in chat, clicks Send.
#   -> send_btn.click fires process_message(...)
#      -> if loaded_context is set, prepend it to user_message
#      -> backend = BACKENDS[mode]
#      -> client = backend.get_client(api_key)
#      -> result = backend.run(client, effective_message)
#         -> returns {reply, steps, extracted}
#      -> build_outputs() produces table / chart / code / extracted JSON
#         -> calls backend.build_code_snippets(...) for the Code tab
#      -> save_json_artifact() writes a timestamped run_*.json
#      -> returns 8 values matching the chat_outputs list in ZONE 5
#         1. new chat history      -> chatbot
#         2. steps dataframe       -> Results > Table
#         3. extracted JSON        -> Results > Extracted
#         4. chart dataframe       -> Visuals
#         5. code snippet          -> Results > Code
#         6. downloads list        -> downloads_state
#         7. downloads list (same) -> Downloads tab file list
#         8. empty string          -> chat_input (clears it)
#
# DATA SOURCE LOADERS follow a shorter pattern:
# User loads a URL / PDF / spreadsheet / ML examples -> saves JSON artifact,
# appends to downloads, updates loaded_context_state for next chat turn.
# Returns 5 values: preview, status, context, downloads_state, downloads_files.
#
# THE TWO RULES THAT WILL SAVE YOU PAIN
# -------------------------------------
#  1. Handler return order MUST match its wiring outputs list.
#     Function returns N values -> outputs=[c1, c2, ..., cN] must have N items
#     in the same order. Mismatch is the #1 source of silent breakage.
#
#  2. All chat handlers (process_message, submit_form, new_chat) share
#     the same chat_outputs list. If you change the shape of one, change
#     all three at once.
#
# WHERE TO ADD NEW THINGS
# -----------------------
#  New backend          -> Create agent_<name>.py with the 4 contract symbols,
#                          add one import line in ZONE 2, add it to BACKENDS.
#                          Nothing else changes.
#
#  New top-level tab    -> ZONE 4 inside outer gr.Tabs()
#                          + handler in ZONE 3
#                          + wiring in ZONE 5
#
#  New sub-tab          -> ZONE 4 inside the parent tab's inner gr.Tabs()
#                          + handler in ZONE 3 following scrape_url pattern
#                          + wiring in ZONE 5 following scrape_btn pattern
#
#  New output display   -> ZONE 4 component + expand build_outputs in ZONE 2
#                          + add to chat_outputs list
#                          + update process_message, submit_form, new_chat
#                            to return one more value in the matching position
#
#  New data source      -> Same as sub-tab. Always call save_json_artifact()
#                          and always return the 5-tuple shape.
#
#  New agent tool       -> Edit tools.py only. Add function to TOOL_FUNCTIONS
#                          dict and schema to TOOL_SCHEMAS list. The raw-SDK
#                          backends pick it up automatically. For LangChain
#                          and LangGraph, also wrap it with @lc_tool in
#                          agent_langchain.py and (if math/info scoped) add
#                          to MATH_TOOLS or INFO_TOOLS in agent_langgraph.py.
#
#  New field in an      -> Find the `artifact = {...}` dict in the relevant
#  existing JSON           handler in ZONE 3 and add your key.
#
# ============================================================================


# ============================================================================
# ZONE 1 β€” Imports & constants
# ============================================================================
import os
import json
import hashlib
from datetime import datetime
try:
    import torch
    if not hasattr(torch, 'float8_e8m0fnu'):
        torch.float8_e8m0fnu = torch.float32
except ImportError:
    pass
from dotenv import load_dotenv

load_dotenv() # Load environment variables from .env file

import gradio as gr
import pandas as pd
import requests
from bs4 import BeautifulSoup
from pypdf import PdfReader


MAX_CONTEXT_CHARS = 5000


# ============================================================================
# ZONE 2 β€” Helpers (pure functions, no UI knowledge)
# ============================================================================
# These functions take plain Python inputs and return plain Python outputs.
# They know nothing about Gradio. Reusable and testable on their own.
#
# NOTE: the actual LLM orchestration (Workflow and Agent runners, the
# MODES dict, the client, and the code snippet builder) lives in agent.py
# so that it can be swapped for alternative implementations (LangChain,
# LangGraph, etc.) without touching this file. We just import what we need.
# ----------------------------------------------------------------
# Agent backend β€” swappable module
# ----------------------------------------------------------------
# ----------------------------------------------------------------
# Agent backends β€” each file is an independent import.
# ALL backend imports are wrapped in try/except so the app boots even
# if one file is broken (missing dep, version conflict, import error).
# Broken backends are silently hidden from the mode radio at startup and
# a warning is printed to the console. At least one backend must load
# or the app will show an empty mode list, but the app itself will run.
# ----------------------------------------------------------------
BACKENDS = {}

# Ringmaster is listed FIRST so it becomes the default selection
try:
    import agent_langgraph_ringmaster
    BACKENDS[agent_langgraph_ringmaster.BACKEND_NAME] = agent_langgraph_ringmaster
except Exception as _rm_err:
    print(f"[app.py] LangGraph Ringmaster backend unavailable: {_rm_err}")

try:
    import agent_workflow
    BACKENDS[agent_workflow.BACKEND_NAME] = agent_workflow
except Exception as _wf_err:
    print(f"[app.py] Workflow backend unavailable: {_wf_err}")

try:
    import agent_py
    BACKENDS[agent_py.BACKEND_NAME] = agent_py
except Exception as _py_err:
    print(f"[app.py] Simple Python Agent backend unavailable: {_py_err}")

try:
    import agent_langchain
    BACKENDS[agent_langchain.BACKEND_NAME] = agent_langchain
except Exception as _lc_err:
    print(f"[app.py] LangChain backend unavailable: {_lc_err}")

try:
    import agent_langgraph
    BACKENDS[agent_langgraph.BACKEND_NAME] = agent_langgraph
except Exception as _lg_err:
    print(f"[app.py] LangGraph backend unavailable: {_lg_err}")

try:
    import agent_smolagents
    BACKENDS[agent_smolagents.BACKEND_NAME] = agent_smolagents
except Exception as _sa_err:
    print(f"[app.py] smolagents backend unavailable: {_sa_err}")

try:
    import agent_crewai
    BACKENDS[agent_crewai.BACKEND_NAME] = agent_crewai
except Exception as _crew_err:
    print(f"[app.py] CrewAI backend unavailable: {_crew_err}")

try:
    import agent_llama_index
    BACKENDS[agent_llama_index.BACKEND_NAME] = agent_llama_index
except Exception as _li_err:
    print(f"[app.py] LlamaIndex backend unavailable: {_li_err}")

# Fallback so the UI never crashes on an empty BACKENDS dict
if not BACKENDS:
    print("[app.py] WARNING: no backends loaded. Check build logs.")

from examples import ML_EXAMPLES
from training_data import TRAINING_EXAMPLES
from training import (
    train_classifier, predict as classifier_predict,
    cluster_hierarchical, cluster_report,
)

try:
    import vectorstore
    VECTORSTORE_OK = True
except Exception as _vs_err:
    print(f"[app.py] vectorstore unavailable: {_vs_err}")
    VECTORSTORE_OK = False

import providers

# Workbench packages β€” each is a self-contained LangGraph supervisor workflow.
# Wrapped so a broken workbench does not kill the whole app on cold boot.
# ============================================================================
# !!! RULE_VIOLATION_6 β€” DELIBERATE β€” see COMPLIANCE.md !!!
# ----------------------------------------------------------------------------
# Pattern:  try/except around module imports + WB_*_OK flags + print fallback.
# Reason:   A broken workbench folder (wrong upload, missing __init__, syntax
#           slip after an edit) must NOT bring down the entire Space on cold
#           boot. Defensive import lets the seven-backend chat, Supervised ML,
#           Unsupervised ML, and Vector Processing tabs keep working even if
#           one workbench is broken.
# Fix-when: Never. This is the one boundary where graceful degradation is
#           worth more than strict compliance. Alternative would be pinning
#           every workbench dependency exhaustively β€” brittle on HF Spaces.
# ============================================================================
try:
    import workbench_grounded_theory as wb_cgt
    WB_CGT_OK = True
    _wb_cgt_err = None
except Exception as _e:
    WB_CGT_OK = False
    _wb_cgt_err = str(_e)
    print(f"[app.py] workbench_grounded_theory unavailable: {_wb_cgt_err}")

try:
    import workbench_thematic_analysis as wb_cta
    WB_CTA_OK = True
    _wb_cta_err = None
except Exception as _e:
    WB_CTA_OK = False
    _wb_cta_err = str(_e)
    print(f"[app.py] workbench_thematic_analysis unavailable: {_wb_cta_err}")

try:
    from workbench_thematic_analysis import phase2_agent
    PHASE2_AGENT_OK = True
    _phase2_agent_err = None
except Exception as _e:
    PHASE2_AGENT_OK = False
    _phase2_agent_err = str(_e)
    print(f"[app.py] phase2_agent unavailable: {_phase2_agent_err}")

try:
    from phase3_themes import run_phase3_searching_themes
    PHASE3_OK = True
    _phase3_err = None
except Exception as _e:
    PHASE3_OK = False
    _phase3_err = str(_e)
    print(f"[app.py] phase3_themes unavailable: {_phase3_err}")

try:
    from phase4_review import run_phase4_reviewing_themes
    PHASE4_OK = True
    _phase4_err = None
except Exception as _e:
    PHASE4_OK = False
    _phase4_err = str(_e)
    print(f"[app.py] phase4_review unavailable: {_phase4_err}")

try:
    from phase5_defining_naming import run_phase5_defining_naming
    PHASE5_OK = True
    _phase5_err = None
except Exception as _e:
    PHASE5_OK = False
    _phase5_err = str(_e)
    print(f"[app.py] phase5_defining_naming unavailable: {_phase5_err}")

try:
    from phase6_report import run_phase6_producing_report
    PHASE6_OK = True
    _phase6_err = None
except Exception as _e:
    PHASE6_OK = False
    _phase6_err = str(_e)
    print(f"[app.py] phase6_report unavailable: {_phase6_err}")

try:
    from corpus_compression import run_corpus_compression
    COMPRESSION_OK = True
    _compression_err = None
except Exception as _e:
    COMPRESSION_OK = False
    _compression_err = str(_e)
    print(f"[app.py] corpus_compression unavailable: {_compression_err}")

try:
    from cluster_labeling import (
        build_cluster_table_from_compression,
        run_iter1,
        run_iter2,
        commit_final_labels,
        LABEL_PROMPT_ITER1,
        LABEL_PROMPT_ITER2,
    )
    CLUSTER_LABELING_OK = True
    _cluster_labeling_err = None
except Exception as _e:
    CLUSTER_LABELING_OK = False
    _cluster_labeling_err = str(_e)
    print(f"[app.py] cluster_labeling unavailable: {_cluster_labeling_err}")

try:
    import database as db
    DB_OK = True
    _db_err = None
    if DB_OK:
        DB_OK = db.create_tables()
except Exception as _e:
    DB_OK = False
    _db_err = str(_e)
    print(f"[app.py] database unavailable: {_db_err}")

try:
    from phase0_preparation import (
        apply_length_filter,
        apply_noise_strip,
        apply_hash_dedup,
        apply_semantic_dedup,
        run_full_preparation_pipeline,
        SEMANTIC_DEDUP_AVAILABLE,
    )
    PHASE0_PREP_OK = True
    _phase0_prep_err = None
except Exception as _e:
    PHASE0_PREP_OK = False
    _phase0_prep_err = str(_e)
    print(f"[app.py] phase0_preparation unavailable: {_phase0_prep_err}")

# ----------------------------------------------------------------
# FT50 method contracts β€” paper-cited preconditions per phase.
# See method_contracts.py for the full registry. Reviewers can grep
# that file for paper citations (e.g. "B&C 2006 p. 84") to see every
# place the corresponding constraint is enforced.
# ----------------------------------------------------------------
from method_contracts import (
    MethodContractError,
    contracts_as_dicts,
    check_phase1_familiarization,
    check_phase0_compression,
    check_phase2_initial_coding,
    check_phase3_searching_themes,
    check_phase4_reviewing_themes,
    check_phase5_defining_naming,
    check_phase6_producing_report,
    check_cgt_phase2_refinement,
)

# ----------------------------------------------------------------
# CGT Phase 2 Pattern Refinement β€” Nelson 2020 Step 2
# ----------------------------------------------------------------
from cgt_phase2_refinement import (
    run_pattern_refinement,
    validate_refinement_table,
)

# ----------------------------------------------------------------
# Methodology comparison β€” reference paper technique vs our 2026
# best-in-class technique, per workbench. Paper-ready Markdown,
# downloadable as .md for injection into papers' methods sections.
# ----------------------------------------------------------------
from methodology_comparison import COMPARISONS as METHOD_COMPARISONS


# ----------------------------------------------------------------
# Artifact writer β€” every input/run becomes a timestamped JSON file
# ----------------------------------------------------------------
def save_json_artifact(data, prefix):
    ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
    path = f"{prefix}_{ts}.json"
    with open(path, "w") as f:
        json.dump(data, f, indent=2, default=str, ensure_ascii=False)
    return path


# ----------------------------------------------------------------
# Methodology comparison download handler
# ----------------------------------------------------------------
def handle_methodology_comparison_download(workbench_key, downloads_list):
    """Save the methodology comparison for a workbench as a .md file.



    Paper-ready Markdown β€” researcher pastes into the methods section.

    Args:

        workbench_key: 'bc', 'gw', or 'cgt'

        downloads_list: current downloads list (Gradio state)

    """
    dl = list(downloads_list or [])
    comp = METHOD_COMPARISONS.get(workbench_key)
    if comp is None:
        return f"**Unknown workbench key: {workbench_key!r}**", dl, dl
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    path = f"methodology_comparison_{workbench_key}_{ts}.md"
    with open(path, "w", encoding="utf-8") as f:
        f.write(comp.as_markdown())
    dl.append(path)
    return f"**Saved:** `{path}` (ready to paste into paper's methods section)", dl, dl


# ----------------------------------------------------------------
# Build outputs for the Results/Visuals tabs from a run result
# ----------------------------------------------------------------
def build_outputs(user_message, mode, result):
    steps_df = pd.DataFrame(result["steps"])
    extracted_json = json.dumps(result["extracted"], indent=2)

    tool_counts = {}
    for s in result["steps"]:
        tool_counts[s["tool"]] = tool_counts.get(s["tool"], 0) + 1
    if tool_counts:
        chart_df = pd.DataFrame(
            [{"tool": k, "count": v} for k, v in tool_counts.items()]
        )
    else:
        chart_df = pd.DataFrame([{"tool": "(none)", "count": 0}])

    # Each backend has its own build_code_snippets β€” pick the right one.
    backend = BACKENDS.get(mode)
    if backend is not None:
        code_snippet = backend.build_code_snippets(user_message, result["steps"])
    else:
        code_snippet = f"# Unknown backend: {mode}"
    return steps_df, extracted_json, chart_df, code_snippet


# ============================================================================
# ZONE 3 β€” Action handlers (wired to UI buttons in Zone 5)
# ============================================================================
# These are the functions Gradio calls when a button is clicked or a form
# is submitted. They read state, call Zone 2 helpers, and return values
# that go directly into UI components.
#
# CONVENTIONS:
#   - Data source loaders return 5 values:
#       (preview, status, loaded_context, downloads_state, downloads_files)
#   - Chat handlers (process_message, submit_form, new_chat) return 8 values:
#       (chat_history, table_df, extracted_json, chart_df, code_snippet,
#        downloads_state, downloads_files, empty_string_to_clear_input)
#   - Clear handlers return only the fields they reset. Never touch downloads.
#
# ----------------------------------------------------------------
# Data source loaders
# Each returns: preview, status, loaded_context, downloads_state, downloads_files
# Each saves a timestamped JSON artifact and appends to the downloads list.
# ----------------------------------------------------------------
def scrape_url(url, downloads_list):
    dl = list(downloads_list or [])
    if not url or not url.strip():
        return "", "Nothing loaded.", "", dl, dl

    resp = requests.get(url.strip(), timeout=15)
    soup = BeautifulSoup(resp.text, "html.parser")
    for tag in soup(["script", "style", "noscript"]):
        tag.decompose()
    text = soup.get_text(separator=" ", strip=True)[:MAX_CONTEXT_CHARS]
    status = f"**Loaded:** {url.strip()} β€” {len(text)} chars"

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "web_scrape",
        "url": url.strip(),
        "char_count": len(text),
        "content": text,
    }
    path = save_json_artifact(artifact, "scrape")
    dl.append(path)
    return text, status, text, dl, dl


def extract_pdf(file_obj, downloads_list):
    dl = list(downloads_list or [])
    if file_obj is None:
        return "", "Nothing loaded.", "", dl, dl

    reader = PdfReader(file_obj.name)
    text = "\n".join((page.extract_text() or "") for page in reader.pages)
    text = text[:MAX_CONTEXT_CHARS]
    status = f"**Loaded:** PDF with {len(reader.pages)} pages β€” {len(text)} chars"

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "pdf_upload",
        "filename": os.path.basename(file_obj.name),
        "page_count": len(reader.pages),
        "char_count": len(text),
        "content": text,
    }
    path = save_json_artifact(artifact, "pdf")
    dl.append(path)
    return text, status, text, dl, dl


def load_spreadsheet(file_obj, downloads_list):
    dl = list(downloads_list or [])
    if file_obj is None:
        return pd.DataFrame(), "Nothing loaded.", "", dl, dl

    path_in = file_obj.name
    if path_in.lower().endswith(".csv"):
        df = pd.read_csv(path_in)
    else:
        df = pd.read_excel(path_in)
    preview_df = df.head(20)
    text = df.head(50).to_string()[:MAX_CONTEXT_CHARS]
    status = f"**Loaded:** {len(df)} rows x {len(df.columns)} columns"

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "spreadsheet_upload",
        "filename": os.path.basename(path_in),
        "row_count": int(len(df)),
        "column_count": int(len(df.columns)),
        "columns": list(df.columns),
        "rows": df.head(100).to_dict(orient="records"),
    }
    path_out = save_json_artifact(artifact, "spreadsheet")
    dl.append(path_out)
    return preview_df, status, text, dl, dl


def load_ml_examples(downloads_list):
    """Load the built-in ML paper catalog as context. No upload needed."""
    dl = list(downloads_list or [])
    paper_ids = {e["paper_id"] for e in ML_EXAMPLES}
    preview_lines = [
        f"[{e['label']}] {e['sentence'][:90]}{'...' if len(e['sentence']) > 90 else ''}"
        f"  β€” {e['paper_title']}, {e['year']}"
        for e in ML_EXAMPLES[:8]
    ]
    preview_lines.append(f"\n... and {max(0, len(ML_EXAMPLES) - 8)} more sentences")
    preview = "\n".join(preview_lines)
    status = f"**Loaded:** {len(ML_EXAMPLES)} labeled sentences from {len(paper_ids)} ML papers"
    context_text = json.dumps(ML_EXAMPLES, indent=2, ensure_ascii=False)[:MAX_CONTEXT_CHARS]

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "ml_examples_catalog",
        "sentence_count": len(ML_EXAMPLES),
        "paper_count": len(paper_ids),
        "examples": ML_EXAMPLES,
    }
    path = save_json_artifact(artifact, "ml_examples")
    dl.append(path)
    return preview, status, context_text, dl, dl


# ----------------------------------------------------------------
# Clear handlers β€” reset only the source-specific fields
# ----------------------------------------------------------------
def clear_scrape():
    return "", "", "Nothing loaded.", ""


def clear_pdf():
    return None, "", "Nothing loaded.", ""


def clear_spreadsheet():
    return None, pd.DataFrame(), "Nothing loaded.", ""


def clear_ml_examples():
    return "", "Nothing loaded.", ""


# ----------------------------------------------------------------
# Training handlers β€” supervised and unsupervised ML on TRAINING_EXAMPLES
# ----------------------------------------------------------------
def handle_train(downloads_list):
    """Fit a TF-IDF + logistic regression classifier and save the result."""
    dl = list(downloads_list or [])
    trained = train_classifier()

    # Build a display-friendly confusion matrix dataframe
    cm_df = pd.DataFrame(
        trained.confusion,
        columns=[f"pred:{l}" for l in trained.labels],
    )
    cm_df.insert(0, "actual", trained.labels)

    status = (
        f"**Accuracy:** {trained.accuracy:.1%}  \n"
        f"**Train size:** {trained.train_size}, "
        f"**Test size:** {trained.test_size}"
    )

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "supervised_training",
        "accuracy": trained.accuracy,
        "train_size": trained.train_size,
        "test_size": trained.test_size,
        "labels": trained.labels,
        "confusion_matrix": trained.confusion,
    }
    path = save_json_artifact(artifact, "training")
    dl.append(path)

    return trained, status, cm_df, dl, dl


def handle_predict(trained, sentence, downloads_list):
    """Predict the label of a new sentence using a previously trained model."""
    dl = list(downloads_list or [])
    if trained is None:
        return "Train the classifier first.", dl, dl
    if not sentence or not sentence.strip():
        return "Enter a sentence to predict.", dl, dl

    result = classifier_predict(trained, sentence.strip())

    lines = [
        f"**Predicted label:** `{result['predicted_label']}`",
        f"**Confidence:** {result['confidence']:.1%}",
        "",
        "**Class probabilities:**",
    ]
    for label, prob in sorted(result["probabilities"].items(), key=lambda x: -x[1]):
        lines.append(f"- `{label}`: {prob:.1%}")

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "supervised_prediction",
        **result,
    }
    path = save_json_artifact(artifact, "prediction")
    dl.append(path)

    return "\n".join(lines), dl, dl


def handle_cluster(similarity_threshold, min_cluster_size, n_nearest,

                   enable_llm_labels, llm_provider, llm_key, downloads_list):
    """Parameterized clustering with optional LLM labeling of each cluster.



    Uses training.cluster_with_params which returns:

        - cluster_ids per sentence (-1 = noise)

        - centroids per surviving cluster

        - n_nearest representative sentences per cluster

    Then (optionally) sends those representatives to an LLM with a

    constrained prompt that asks for a short cluster label.

    """
    from training import cluster_with_params as _cwp

    dl = list(downloads_list or [])

    sentences = [e["sentence"] for e in TRAINING_EXAMPLES]
    true_labels = [e["label"] for e in TRAINING_EXAMPLES]

    result = _cwp(
        sentences,
        similarity_threshold=float(similarity_threshold),
        min_cluster_size=int(min_cluster_size),
        n_nearest=int(n_nearest),
    )

    cluster_ids = result["cluster_ids"]
    representatives = result["representatives"]
    distances = result["distances_to_centroid"]

    # Build LLM labels if enabled
    llm_labels = {}
    llm_error = None
    if enable_llm_labels and result["n_clusters_found"] > 0:
        try:
            client = providers.get_llm_client(llm_provider, llm_key)
            model_name = providers.get_llm_model(llm_provider)
            for cid, reps in representatives.items():
                rep_sentences = [sentences[i] for i, _d in reps]
                numbered = "\n".join(
                    f"{k+1}. {s}" for k, s in enumerate(rep_sentences)
                )
                prompt = (
                    f"The following {len(rep_sentences)} sentences were grouped "
                    f"together by a clustering algorithm. Based ONLY on these "
                    f"sentences, produce a short label (2-5 words) that describes "
                    f"what they have in common. Output ONLY the label, nothing else.\n\n"
                    f"{numbered}\n\nLabel:"
                )
                resp = client.chat.complete(
                    model=model_name,
                    messages=[{"role": "user", "content": prompt}],
                    temperature=0.2,
                    max_tokens=40,
                )
                label = (resp.choices[0].message.content or "").strip()
                # Trim to first line, cap length
                label = label.split("\n")[0][:60]
                llm_labels[cid] = label
        except Exception as e:
            llm_error = str(e)

    # Build sentence-level dataframe
    sent_rows = []
    for idx, sent in enumerate(sentences):
        cid = cluster_ids[idx]
        rep_idxs = {i for i, _d in representatives.get(cid, [])}
        sent_rows.append({
            "idx": idx,
            "sentence": sent,
            "true_label": true_labels[idx],
            "cluster_id": "noise" if cid == -1 else str(cid),
            "cluster_label": llm_labels.get(cid, "") if cid != -1 else "",
            "is_representative": idx in rep_idxs,
            "dist_to_centroid": (
                round(distances[idx], 4) if distances[idx] is not None else None
            ),
        })
    sent_df = pd.DataFrame(sent_rows)

    n_found = result["n_clusters_found"]
    n_noise = result["n_noise_points"]
    status_parts = [
        f"**Similarity >= {float(similarity_threshold):.2f}**, "
        f"**min size = {int(min_cluster_size)}**, "
        f"**N nearest = {int(n_nearest)}**",
        f"**Found:** {n_found} cluster(s), **Noise:** {n_noise} sentence(s)",
    ]
    if enable_llm_labels:
        if llm_error:
            status_parts.append(f"**LLM labeling failed:** {llm_error}")
        else:
            status_parts.append(f"**LLM labels generated** via {llm_provider}")
    status = "  \n".join(status_parts)

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "unsupervised_clustering_parameterized",
        "algorithm": "Hierarchical Agglomerative",
        "similarity_threshold": float(similarity_threshold),
        "min_cluster_size": int(min_cluster_size),
        "n_nearest": int(n_nearest),
        "n_clusters_found": n_found,
        "n_noise_points": n_noise,
        "llm_provider": llm_provider if enable_llm_labels else None,
        "llm_labels": {str(k): v for k, v in llm_labels.items()},
        "sentences": sent_rows,
    }
    path = save_json_artifact(artifact, "clusters_params")
    dl.append(path)

    return sent_df, status, dl, dl


# ----------------------------------------------------------------
# Workbench handlers β€” Grounded Theory (Nelson 2020) + Thematic Analysis
# ----------------------------------------------------------------
def handle_wb_cgt(user_message, similarity_threshold, min_cluster_size,

                  n_nearest, llm_provider, llm_key, loaded_context, downloads_list):
    """Run the Computational Grounded Theory supervisor graph.



    Three-step framework from Nelson 2020. Round 1: Pattern Detection is

    a real LangGraph node, Pattern Refinement and Pattern Confirmation

    are placeholders that return 'not yet implemented'.



    Sentence source resolution:

      1. If loaded_context (from the Inputs tab) is non-empty, split it

         on newlines and use those sentences with true_labels="(unknown)".

      2. Otherwise fall back to the built-in TRAINING_EXAMPLES demo corpus

         with its real ground-truth labels.

    """
    dl = list(downloads_list or [])

    # !!! RULE_VIOLATION_7 β€” DELIBERATE β€” see COMPLIANCE.md !!!
    if not WB_CGT_OK:
        return (
            pd.DataFrame(),
            "# Workbench unavailable\n\n" + (_wb_cgt_err or "unknown error"),
            pd.DataFrame(),
            dl, dl,
        )

    # ---- Resolve sentence source ----
    if loaded_context and loaded_context.strip():
        sentences = [s.strip() for s in loaded_context.split("\n") if s.strip()]
        true_labels = ["(unknown)"] * len(sentences)
        data_source = "uploaded"
    else:
        from training_data import TRAINING_EXAMPLES
        sentences = [e["sentence"] for e in TRAINING_EXAMPLES]
        true_labels = [e["label"] for e in TRAINING_EXAMPLES]
        data_source = "demo"

    result = wb_cgt.run(
        user_message=user_message or "Run computational grounded theory on the training data.",
        similarity_threshold=float(similarity_threshold),
        min_cluster_size=int(min_cluster_size),
        n_nearest=int(n_nearest),
        llm_provider=llm_provider,
        llm_key=llm_key,
    )

    trace_df = pd.DataFrame(result.get("steps") or [])
    reply_md = "## Supervisor reply\n\n" + (result.get("reply") or "(empty)")
    reply_md += f"\n\n*Data source: **{data_source}** ({len(sentences)} sentences)*"

    det = result.get("detection_result") or {}
    sentence_rows = det.get("sentence_rows") or []
    sentences_df = pd.DataFrame(sentence_rows) if sentence_rows else pd.DataFrame()

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "workbench_cgt",
        "paper": "Nelson 2020 - Computational Grounded Theory",
        "data_source": data_source,
        "n_sentences": len(sentences),
        "parameters": {
            "similarity_threshold": float(similarity_threshold),
            "min_cluster_size": int(min_cluster_size),
            "n_nearest": int(n_nearest),
            "llm_provider": llm_provider,
        },
        "reply": result.get("reply"),
        "steps": result.get("steps"),
        "detection_result": result.get("detection_result"),
        "refinement_result": result.get("refinement_result"),
        "confirmation_result": result.get("confirmation_result"),
    }
    path = save_json_artifact(artifact, "workbench_cgt")
    dl.append(path)

    return trace_df, reply_md, sentences_df, dl, dl


# ----------------------------------------------------------------
# CGT Phase 2 Pattern Refinement handlers (Nelson 2020 Step 2)
# ----------------------------------------------------------------
def handle_cgt_p2_surface(

    sentences_df,

    n_exemplars,

    reflexive_positioning,

    llm_provider,

    llm_key,

    downloads_list,

):
    """Surface exemplars per Phase 1 pattern and draft LLM interpretive memos.



    Contracts (Nelson 2020 + C&R 2022):

      - Phase 1 output must exist with cluster_id column

      - at least 1 non-noise cluster

      - n_exemplars in [1, 20]

      - reflexive positioning >=20 chars

      - LLM key present



    Returns:

        (refinement_df, status_markdown, downloads_list, downloads_files)

    """
    dl = list(downloads_list or [])
    empty = pd.DataFrame(columns=[
        "pattern_id", "pattern_label", "n_sentences", "exemplars",
        "llm_memo_draft", "researcher_memo", "verdict", "new_label",
    ])

    # Contract check
    try:
        contracts = check_cgt_phase2_refinement(
            sentences_df=sentences_df,
            n_exemplars=int(n_exemplars),
            reflexive_positioning=reflexive_positioning,
            llm_key=llm_key,
        )
    except MethodContractError as e:
        return empty, f"**Method contract violation (CGT Phase 2):**\n\n{e}", dl, dl

    # Run refinement
    try:
        result = run_pattern_refinement(
            sentences_df=sentences_df,
            n_exemplars=int(n_exemplars),
            llm_provider=llm_provider or "Mistral",
            llm_key=llm_key,
            reflexive_pos=reflexive_positioning or "",
        )
    except Exception as e:
        return empty, f"**CGT Phase 2 error:** {e}", dl, dl

    refinement_rows = result["refinement_rows"]
    if not refinement_rows:
        return empty, "**No patterns to refine** β€” Phase 1 produced no non-noise clusters.", dl, dl

    refinement_df = pd.DataFrame(refinement_rows)

    # Save "surface" artifact (pre-researcher-edit snapshot)
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "cgt_phase2_surface",
        "methodology": "Nelson 2020 Step 2 β€” Pattern Refinement (exemplar surfacing + LLM memo draft)",
        "method_contracts_verified": contracts_as_dicts(contracts),
        "n_patterns": result["n_patterns"],
        "n_noise": result["n_noise"],
        "n_exemplars_per_pattern": int(n_exemplars),
        "llm_errors": result["llm_errors"],
        "refinement_rows": refinement_rows,
    }
    path = save_json_artifact(artifact, "cgt_phase2_surface")
    dl.append(path)

    status = (
        f"**Phase 2 exemplars surfaced.** {result['n_patterns']} patterns, "
        f"{result['n_noise']} noise sentences skipped. "
        f"LLM memo drafts generated. "
        f"**Edit `researcher_memo`, `verdict`, and `new_label` columns below**, "
        f"then click Save."
    )
    if result["llm_errors"]:
        status += f"\n\n*(LLM errors on {len(result['llm_errors'])} clusters β€” see artifact)*"
    return refinement_df, status, dl, dl


def handle_cgt_p2_save(refinement_table, reflexive_positioning, downloads_list):
    """Save the researcher-edited Phase 2 refinement table as artifact.



    Validates the researcher's edits: every row must have a valid verdict

    (keep/merge/split/drop/rename), researcher_memo, and new_label for rename/split.

    """
    dl = list(downloads_list or [])

    if not isinstance(refinement_table, pd.DataFrame):
        refinement_df = pd.DataFrame(refinement_table) if refinement_table else pd.DataFrame()
    else:
        refinement_df = refinement_table.copy()

    # Validate researcher edits
    validation = validate_refinement_table(refinement_df)
    if not validation["ok"]:
        msg = "**Phase 2 save blocked β€” fix these before saving:**\n\n"
        for err in validation["errors"][:10]:
            msg += f"- {err}\n"
        if len(validation["errors"]) > 10:
            msg += f"- ...and {len(validation['errors']) - 10} more\n"
        return msg, dl, dl

    refinement_rows = refinement_df.fillna("").to_dict("records")

    # Verdict tally
    verdict_counts = {}
    for r in refinement_rows:
        v = str(r.get("verdict", "")).strip().lower()
        verdict_counts[v] = verdict_counts.get(v, 0) + 1

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "cgt_phase2_refinement_saved",
        "methodology": "Nelson 2020 Step 2 β€” Pattern Refinement (researcher-approved)",
        "method_contracts_enforced": (
            "See method_contracts.check_cgt_phase2_refinement β€” enforced at surface time. "
            "Contracts: Nelson 2020 (Phase 1 output, cluster count, exemplar range), "
            "C&R 2022 (reflexive positioning), reproducibility."
        ),
        "reflexive_positioning": reflexive_positioning or "",
        "n_patterns_refined": len(refinement_rows),
        "verdict_tally": verdict_counts,
        "refinement_rows": refinement_rows,
    }
    path = save_json_artifact(artifact, "cgt_phase2_refinement")
    dl.append(path)

    tally_str = ", ".join(f"{k}={v}" for k, v in sorted(verdict_counts.items()))
    return (
        f"**Phase 2 refinement saved** ({len(refinement_rows)} patterns). "
        f"Verdicts: {tally_str}. "
        f"Artifact: `{path}`.",
        dl, dl,
    )


def handle_wb_cta(user_message, max_sentences, llm_provider, llm_key,

                  loaded_context, downloads_list):
    """Run the Computational Thematic Analysis supervisor graph.



    Six-phase framework from Braun & Clarke 2006. Round 1: Phase 2

    (Generating Initial Codes) is a real LangGraph node, Phases 1, 3,

    4, 5, 6 are placeholders that return 'not yet implemented'.



    Sentence source resolution: same as CGT β€” loaded_context from Inputs

    tab first, fall back to TRAINING_EXAMPLES demo corpus.

    """
    dl = list(downloads_list or [])

    # !!! RULE_VIOLATION_7 β€” DELIBERATE β€” see COMPLIANCE.md !!!
    # Same pattern as above: pairs with RULE_VIOLATION_6 on cold-boot
    # import failure.
    if not WB_CTA_OK:
        return (
            pd.DataFrame(),
            "# Workbench unavailable\n\n" + (_wb_cta_err or "unknown error"),
            pd.DataFrame(),
            dl, dl,
        )

    # ---- Resolve sentence source ----
    if loaded_context and loaded_context.strip():
        sentences = [s.strip() for s in loaded_context.split("\n") if s.strip()]
        true_labels = ["(unknown)"] * len(sentences)
        data_source = "uploaded"
    else:
        from training_data import TRAINING_EXAMPLES
        sentences = [e["sentence"] for e in TRAINING_EXAMPLES]
        true_labels = [e["label"] for e in TRAINING_EXAMPLES]
        data_source = "demo"

    result = wb_cta.run(
        user_message=user_message or "Run reflexive thematic analysis on the training data.",
        max_sentences_to_code=int(max_sentences),
        llm_provider=llm_provider,
        llm_key=llm_key,
    )

    trace_df = pd.DataFrame(result.get("steps") or [])
    reply_md = "## Supervisor reply\n\n" + (result.get("reply") or "(empty)")
    reply_md += f"\n\n*Data source: **{data_source}** ({len(sentences)} sentences)*"

    phase2 = result.get("phase2_initial_codes") or {}
    coded_rows = phase2.get("coded_rows") or []
    codes_df = pd.DataFrame(coded_rows) if coded_rows else pd.DataFrame()

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "workbench_cta",
        "paper": "Braun & Clarke 2006 - Reflexive Thematic Analysis",
        "data_source": data_source,
        "n_sentences": len(sentences),
        "parameters": {
            "max_sentences_to_code": int(max_sentences),
            "llm_provider": llm_provider,
        },
        "reply": result.get("reply"),
        "steps": result.get("steps"),
        "phase1_familiarization":  result.get("phase1_familiarization"),
        "phase2_initial_codes":    result.get("phase2_initial_codes"),
        "phase3_searching_themes": result.get("phase3_searching_themes"),
        "phase4_reviewing_themes": result.get("phase4_reviewing_themes"),
        "phase5_defining_naming":  result.get("phase5_defining_naming"),
        "phase6_producing_report": result.get("phase6_producing_report"),
    }
    path = save_json_artifact(artifact, "workbench_cta")
    dl.append(path)

    return trace_df, reply_md, codes_df, dl, dl


def clear_training():
    return None, "Not trained yet.", pd.DataFrame(), ""


def clear_clustering():
    return pd.DataFrame(), "Not clustered yet."


def filter_training_dataset(label):
    """Filter the training-data dataframe shown in the Supervised Dataset sub-tab."""
    if label == "(all)" or not label:
        return pd.DataFrame(TRAINING_EXAMPLES)
    return pd.DataFrame([e for e in TRAINING_EXAMPLES if e["label"] == label])


# ============================================================================
# Phase 1 Familiarization handlers β€” Braun & Clarke 2006, Phase 1
# ============================================================================
# These handlers drive the Phase 1 β€” Familiarization sub-tab inside CTA.
# The flow follows Braun & Clarke's active-reading protocol, implemented
# through grounded dialogue partners (Gemini Gems + NotebookLM) plus
# researcher confirmation:
#   1. Load canonical corpus CSV (L1, L2, L3, L4, sentence_id, sentence)
#   2. Researcher runs Familiarization Facilitator dialogue in Gemini,
#      pastes familiarization notes + transcript + source evidence back
#   3. Researcher runs Reflexive Companion dialogue, pastes reflexive
#      challenges + reflexive positioning + immersion coverage back
#   4. Build researcher confirmation table joining corpus with noticings
#   5. Researcher edits the table (confirm/refine/reject each noticing)
#   6. Save to JSON artifact for Downloads tab
# ----------------------------------------------------------------

P1_REQUIRED_COLUMNS = ["L1", "L2", "L3", "L4", "sentence_id", "sentence"]


def handle_p1_load_test_csv(downloads_list):
    """Load the built-in test_phase1.csv for pipeline verification."""
    dl = list(downloads_list or [])
    try:
        df = pd.read_csv("test_phase1.csv")
    except Exception as e:
        return (
            [],
            f"Failed to load test_phase1.csv: {e}",
            pd.DataFrame(),
            dl, dl,
        )

    missing = [c for c in P1_REQUIRED_COLUMNS if c not in df.columns]
    if missing:
        return (
            [],
            f"test_phase1.csv is missing required columns: {missing}",
            pd.DataFrame(),
            dl, dl,
        )

    corpus = df[P1_REQUIRED_COLUMNS].to_dict("records")
    status = (
        f"**Loaded test_phase1.csv** β€” {len(corpus)} sentences across "
        f"{df['L1'].nunique()} documents, "
        f"{df['L2'].nunique()} unique sections."
    )
    return corpus, status, df[P1_REQUIRED_COLUMNS], dl, dl


def handle_p1_upload_csv(file_obj, downloads_list):
    """Load a user-uploaded canonical CSV and write upload-provenance artifact.



    The provenance artifact is the first link in the reproducibility chain.

    It contains: SHA-256 hash (for integrity verification), filename, row

    count, schema, per-hierarchy distribution stats, and sentence previews.



    A reviewer presented with the artifact can verify that the corpus they

    receive matches the one that produced downstream results, by recomputing

    the SHA-256 over the file bytes.

    """
    dl = list(downloads_list or [])
    if file_obj is None:
        return [], "No file uploaded.", pd.DataFrame(), dl, dl

    # Step 1 β€” read file bytes for hashing (before pandas touches it)
    try:
        with open(file_obj.name, "rb") as f:
            file_bytes = f.read()
        file_sha256 = hashlib.sha256(file_bytes).hexdigest()
        file_size_bytes = len(file_bytes)
    except Exception as e:
        return [], f"Failed to read file bytes: {e}", pd.DataFrame(), dl, dl

    # Step 2 β€” parse CSV
    try:
        df = pd.read_csv(file_obj.name)
    except Exception as e:
        return [], f"Failed to read CSV: {e}", pd.DataFrame(), dl, dl

    # Step 3 β€” validate schema
    missing = [c for c in P1_REQUIRED_COLUMNS if c not in df.columns]
    if missing:
        # Still write a provenance artifact for the FAILED upload, so the
        # reviewer can see what was attempted and why it was rejected.
        fail_artifact = {
            "timestamp": datetime.now().isoformat(),
            "source_type": "corpus_upload_rejected",
            "filename": os.path.basename(file_obj.name),
            "file_sha256": file_sha256,
            "file_size_bytes": file_size_bytes,
            "n_rows_attempted": int(len(df)),
            "detected_columns": list(df.columns),
            "required_columns": list(P1_REQUIRED_COLUMNS),
            "missing_columns": missing,
            "rejection_reason": f"Missing required columns: {missing}",
        }
        fail_path = save_json_artifact(fail_artifact, "corpus_upload_rejected")
        dl.append(fail_path)
        return (
            [],
            (
                f"Uploaded CSV is missing required columns: {missing}. "
                f"Canonical schema is: {P1_REQUIRED_COLUMNS}.  \n"
                f"Rejection artifact: `{os.path.basename(fail_path)}`"
            ),
            pd.DataFrame(),
            dl, dl,
        )

    # Step 4 β€” build corpus (only required columns flow downstream)
    corpus = df[P1_REQUIRED_COLUMNS].to_dict("records")

    # Step 5 β€” compute provenance stats (per-hierarchy uniqueness)
    def _safe_nunique(col_name):
        if col_name not in df.columns:
            return 0
        return int(df[col_name].fillna("").astype(str).nunique())

    # Step 6 β€” build upload provenance artifact
    upload_artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "corpus_upload",
        "pipeline_stage": "pre-sampling",
        "filename": os.path.basename(file_obj.name),
        "file_sha256": file_sha256,
        "file_size_bytes": file_size_bytes,
        "n_rows": int(len(corpus)),
        "detected_columns": list(df.columns),
        "required_columns_present": list(P1_REQUIRED_COLUMNS),
        "hierarchy_distribution": {
            "n_unique_L1": _safe_nunique("L1"),
            "n_unique_L2": _safe_nunique("L2"),
            "n_unique_L3": _safe_nunique("L3"),
            "n_unique_L4": _safe_nunique("L4"),
            "n_unique_sentence_id": _safe_nunique("sentence_id"),
        },
        "preview_first_3": [
            {
                "L1": str(r.get("L1", "")),
                "sentence_id": str(r.get("sentence_id", "")),
                "sentence_first_120_chars": str(r.get("sentence", ""))[:120],
            }
            for r in corpus[:3]
        ],
        "integrity_verification_instructions": (
            "To verify this corpus matches downstream artifacts, compute "
            "SHA-256 of the source CSV file and compare to file_sha256 "
            "above. On Linux: `sha256sum <file>`. On Windows PowerShell: "
            "`Get-FileHash <file> -Algorithm SHA256`."
        ),
    }
    path = save_json_artifact(upload_artifact, "corpus_upload")
    dl.append(path)

    status = (
        f"**Loaded uploaded CSV** β€” {len(corpus)} sentences across "
        f"{_safe_nunique('L1')} L1 values.  \n"
        f"- File SHA-256: `{file_sha256[:16]}...` (full hash in artifact)  \n"
        f"- Upload provenance: `{os.path.basename(path)}`"
    )
    return corpus, status, df[P1_REQUIRED_COLUMNS], dl, dl


def handle_p1_build_validation_table(

    corpus,

    facilitator_memo, facilitator_transcript, facilitator_citations,

    companion_challenges, companion_reflexivity, companion_breadth,

):
    """Build the researcher confirmation table from corpus + pasted Phase 1 outputs.



    Strategy: start with every corpus row (L1, L2, L3, L4, sentence_id,

    sentence), then append empty initial_noticing /

    researcher_confirmation columns. The researcher edits the table inline

    to attach initial noticings to specific sentences and mark each one

    confirm/refine/reject.



    This is the minimum viable version. A future round will parse the

    pasted source evidence and auto-populate the initial_noticing column

    for sentences that were explicitly quoted during the dialogue.

    """
    if not corpus:
        empty = pd.DataFrame(columns=[
            "L1", "L2", "L3", "L4", "sentence_id", "sentence",
            "initial_noticing", "reflexive_challenge",
            "researcher_confirmation", "refined_noticing",
        ])
        return empty

    rows = []
    for r in corpus:
        rows.append({
            "L1": r.get("L1", ""),
            "L2": r.get("L2", ""),
            "L3": r.get("L3", ""),
            "L4": r.get("L4", ""),
            "sentence_id": r.get("sentence_id", ""),
            "sentence": r.get("sentence", ""),
            "initial_noticing": "",
            "reflexive_challenge": "",
            "researcher_confirmation": "",
            "refined_noticing": "",
        })
    return pd.DataFrame(rows)


def handle_p1_save(

    corpus,

    facilitator_memo, facilitator_transcript, facilitator_citations,

    companion_challenges, companion_reflexivity, companion_breadth,

    validation_table,

    downloads_list,

):
    """Save all Phase 1 outputs as a timestamped JSON artifact."""
    dl = list(downloads_list or [])

    # --- FT50 method contract check (B&C 2006 Phase 1) ---
    try:
        contracts = check_phase1_familiarization(
            corpus=corpus,
            reflexive_positioning=companion_reflexivity,
        )
    except MethodContractError as e:
        violation = {
            "timestamp": datetime.now().isoformat(),
            "source_type": "method_contract_violation",
            "phase": "Phase 1 β€” Familiarization",
            "error": str(e),
            "contracts": contracts_as_dicts(e.contracts),
        }
        path = save_json_artifact(violation, "contract_violation_phase1")
        dl.append(path)
        return f"**Method contract violation (Phase 1):**\n\n{e}", dl, dl

    # Convert confirmation dataframe to list-of-dicts for JSON
    if isinstance(validation_table, pd.DataFrame):
        confirmation_rows = validation_table.fillna("").to_dict("records")
    else:
        confirmation_rows = []

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase1_familiarization",
        "methodology": "Braun & Clarke 2006 Phase 1 β€” Familiarizing Yourself With Your Data",
        "method_contracts_verified": contracts_as_dicts(contracts),
        "corpus_size": len(corpus or []),
        "step1_familiarization_facilitator": {
            "familiarization_notes": facilitator_memo or "",
            "active_reading_transcript": facilitator_transcript or "",
            "source_evidence": facilitator_citations or "",
        },
        "step2_reflexive_companion": {
            "reflexive_challenges": companion_challenges or "",
            "reflexive_positioning": companion_reflexivity or "",
            "dataset_immersion_coverage": companion_breadth or "",
        },
        "step3_researcher_confirmation_table": confirmation_rows,
    }
    path = save_json_artifact(artifact, "phase1_familiarization")
    dl.append(path)
    status = (
        f"**Saved Phase 1 familiarization output** β€” {len(corpus or [])} corpus sentences, "
        f"{len(confirmation_rows)} confirmation rows. "
        f"Artifact: `{path.split('/')[-1]}`"
    )
    return status, dl, dl


# ============================================================================
# Phase 2 Initial Coding handlers β€” Braun & Clarke 2006, Phase 2
# ============================================================================
# Round 1: scaffolding + data flow. Round 2 replaces placeholder agent with
# real LangGraph supervisor. Round 3 adds iteration 2/3 + convergence.
#
# The agent architecture (Round 2) will have 7 tools:
#   - read_corpus(filter)
#   - read_phase1_context()
#   - propose_code(sentence, semantic, latent)
#   - check_codebook(code_name)
#   - add_to_codebook(code_name, definition, example)
#   - flag_for_review(sentence, reason)
#   - save_iteration(n)
# ----------------------------------------------------------------


def handle_p2_refresh_corpus(

    corpus,

    facilitator_memo, companion_reflexivity, validation_table,

):
    """Refresh Phase 2 corpus status + Phase 1 context summary.



    Phase 2 reads the corpus loaded in Phase 1 (shared state). It also

    surfaces Phase 1's reflexive positioning and confirmed noticings as

    context for the agent.

    """
    if not corpus:
        return (
            "**No corpus loaded.** Go to Phase 1 β€” Familiarization and load "
            "test_phase1.csv (or your own canonical CSV) first.",
            "*Phase 1 output will appear here after Save Phase 1.*",
        )

    # Count confirmed noticings from Phase 1 validation table
    confirmed_count = 0
    if isinstance(validation_table, pd.DataFrame) and not validation_table.empty:
        noticings_col = validation_table.get("initial_noticing")
        if noticings_col is not None:
            confirmed_count = sum(
                1 for v in noticings_col.fillna("").tolist() if str(v).strip()
            )

    n_docs = len({r.get("L1", "") for r in corpus})
    corpus_status = (
        f"**Corpus ready** β€” {len(corpus)} sentences across {n_docs} documents. "
        f"Inherited from Phase 1 state."
    )

    p1_summary_parts = []
    if facilitator_memo and facilitator_memo.strip():
        preview = facilitator_memo.strip()[:300]
        p1_summary_parts.append(f"**Familiarization notes:** {preview}...")
    if companion_reflexivity and companion_reflexivity.strip():
        preview = companion_reflexivity.strip()[:300]
        p1_summary_parts.append(f"**Reflexive positioning:** {preview}...")
    p1_summary_parts.append(
        f"**Confirmed initial noticings:** {confirmed_count} rows with non-empty `initial_noticing`."
    )
    p1_summary = "\n\n".join(p1_summary_parts) if p1_summary_parts else (
        "*Phase 1 output will appear here after Save Phase 1.*"
    )

    return corpus_status, p1_summary


def handle_p2_run_iteration(

    iteration_n, corpus,

    existing_codes_table, existing_codebook_table,

    facilitator_memo, companion_reflexivity, validation_table,

    llm_provider, llm_key,

    orientation,

):
    """Run one Phase 2 coding iteration via the real LangGraph agent.



    Strict B&C 2006 Phase 2:

    - Multiple codes per segment (1-5)

    - Context window (2 before + 2 after)

    - Researcher-chosen orientation (semantic OR latent, not both)

    - Reflexive positioning injected into every code prompt

    - Researcher override is final

    """
    # Empty corpus guard
    if not corpus:
        empty_codes = pd.DataFrame(columns=[
            "L1", "L2", "L3", "L4", "sentence_id", "sentence",
            "ai_code_iter1", "human_code_iter1",
            "ai_code_iter2", "human_code_iter2",
            "ai_code_iter3", "human_code_iter3",
            "final_code", "flagged",
        ])
        empty_codebook = pd.DataFrame(columns=[
            "code_name", "definition", "created_by", "provenance", "sentence_count",
        ])
        return (
            empty_codes, empty_codebook,
            "**Cannot run β€” no corpus loaded.** Load corpus in Phase 1 first.",
        )

    # Agent availability guard
    if not PHASE2_AGENT_OK:
        empty_codes = pd.DataFrame(columns=[
            "L1", "L2", "L3", "L4", "sentence_id", "sentence",
            "ai_code_iter1", "human_code_iter1",
            "ai_code_iter2", "human_code_iter2",
            "ai_code_iter3", "human_code_iter3",
            "final_code", "flagged",
        ])
        empty_codebook = pd.DataFrame(columns=[
            "code_name", "definition", "created_by", "provenance", "sentence_count",
        ])
        return (
            empty_codes, empty_codebook,
            f"**Phase 2 agent unavailable** β€” `{_phase2_agent_err}`",
        )

    # API key guard
    if not llm_key or not str(llm_key).strip():
        empty_codes = pd.DataFrame(columns=[
            "L1", "L2", "L3", "L4", "sentence_id", "sentence",
            "ai_code_iter1", "human_code_iter1",
            "ai_code_iter2", "human_code_iter2",
            "ai_code_iter3", "human_code_iter3",
            "final_code", "flagged",
        ])
        empty_codebook = pd.DataFrame(columns=[
            "code_name", "definition", "created_by", "provenance", "sentence_count",
        ])
        return (
            empty_codes, empty_codebook,
            "**Cannot run β€” Mistral API key is missing.** Paste it in the sidebar first.",
        )

    # --- FT50 method contract check (B&C 2006 Phase 2) ---
    try:
        contracts = check_phase2_initial_coding(
            orientation=orientation,
            corpus=corpus,
            reflexive_positioning=companion_reflexivity,
            llm_key=llm_key,
            iteration_n=int(iteration_n),
        )
    except MethodContractError as e:
        empty_codes = pd.DataFrame(columns=[
            "L1", "L2", "L3", "L4", "sentence_id", "sentence",
            "ai_code_iter1", "human_code_iter1",
            "ai_code_iter2", "human_code_iter2",
            "ai_code_iter3", "human_code_iter3",
            "final_code", "flagged",
        ])
        empty_codebook = pd.DataFrame(columns=[
            "code_name", "definition", "created_by", "provenance", "sentence_count",
        ])
        return (
            empty_codes, empty_codebook,
            f"**Method contract violation (Phase 2):**\n\n{e}",
        )

    # Initialize the codes table (carry forward if it exists)
    if isinstance(existing_codes_table, pd.DataFrame) and not existing_codes_table.empty:
        codes_df = existing_codes_table.copy()
    else:
        rows = []
        for r in corpus:
            rows.append({
                "L1": r.get("L1", ""),
                "L2": r.get("L2", ""),
                "L3": r.get("L3", ""),
                "L4": r.get("L4", ""),
                "sentence_id": r.get("sentence_id", ""),
                "sentence": r.get("sentence", ""),
                "ai_code_iter1": "",
                "human_code_iter1": "",
                "ai_code_iter2": "",
                "human_code_iter2": "",
                "ai_code_iter3": "",
                "human_code_iter3": "",
                "final_code": "",
                "flagged": "",
            })
        codes_df = pd.DataFrame(rows)

    # Initialize codebook
    if isinstance(existing_codebook_table, pd.DataFrame) and not existing_codebook_table.empty:
        codebook_list = existing_codebook_table.fillna("").to_dict("records")
    else:
        codebook_list = []

    # Build confirmed_noticings list from Phase 1 validation table
    confirmed_noticings = []
    if isinstance(validation_table, pd.DataFrame) and not validation_table.empty:
        noticing_col = validation_table.get("initial_noticing")
        if noticing_col is not None:
            confirmed_noticings = [
                str(v).strip() for v in noticing_col.fillna("").tolist()
                if str(v).strip()
            ]

    # Build agent context
    agent_context = {
        "corpus": corpus,
        "phase1": {
            "reflexive_positioning": companion_reflexivity or "",
            "familiarization_notes": facilitator_memo or "",
            "confirmed_noticings": confirmed_noticings,
        },
        "orientation": orientation or "semantic",
        "existing_codes_df": codes_df if iteration_n >= 2 else None,
        "codebook": codebook_list,
        "proposed_codes": {},
    }

    # Run the agent
    try:
        steps, reply, result_context = phase2_agent.run_phase2_iteration(
            llm_provider=llm_provider,
            llm_key=llm_key,
            iteration_n=int(iteration_n),
            context=agent_context,
        )
    except Exception as e:
        return (
            codes_df,
            pd.DataFrame(codebook_list) if codebook_list else pd.DataFrame(columns=[
                "code_name", "definition", "created_by", "provenance", "sentence_count",
            ]),
            f"**Phase 2 agent error:** {e}",
        )

    # Merge agent results into codes_df
    # New shape: each proposed entry has "codes": [list of 1-5 strings]
    proposed = result_context.get("proposed_codes", {})
    ai_col = f"ai_code_iter{int(iteration_n)}"

    for idx, code_dict in proposed.items():
        if 0 <= int(idx) < len(codes_df):
            codes_list = code_dict.get("codes", []) or []
            if isinstance(codes_list, str):
                codes_list = [codes_list]
            combined = ", ".join(c for c in codes_list if c)
            codes_df.at[int(idx), ai_col] = combined

    # Update final_code column β€” latest human edit wins, else latest AI code
    for i in range(len(codes_df)):
        final = ""
        for it in (3, 2, 1):
            h = codes_df.at[i, f"human_code_iter{it}"]
            if h and str(h).strip():
                final = str(h).strip()
                break
        if not final:
            for it in (3, 2, 1):
                a = codes_df.at[i, f"ai_code_iter{it}"]
                if a and str(a).strip():
                    final = str(a).strip()
                    break
        codes_df.at[i, "final_code"] = final

    # Build codebook DataFrame
    updated_codebook = result_context.get("codebook", [])
    codebook_df = pd.DataFrame(updated_codebook) if updated_codebook else pd.DataFrame(
        columns=["code_name", "definition", "created_by", "provenance", "sentence_count"]
    )

    total_codes = sum(len(v.get("codes", [])) for v in proposed.values())
    status = (
        f"**Iteration {iteration_n} complete** ({orientation} orientation). "
        f"Coded {len(proposed)} sentences with {total_codes} total codes "
        f"(avg {total_codes/len(proposed) if proposed else 0:.1f} codes/sentence). "
        f"Codebook has {len(updated_codebook)} entries. "
        f"Agent took {len(steps)} steps. "
        f"Reply: {reply[:200]}"
    )
    return codes_df, codebook_df, status


def handle_p2_save(

    corpus,

    codes_table, codebook_table,

    downloads_list,

):
    """Save Phase 2 outputs as a timestamped JSON artifact."""
    dl = list(downloads_list or [])

    if isinstance(codes_table, pd.DataFrame):
        codes_rows = codes_table.fillna("").to_dict("records")
    else:
        codes_rows = []
    if isinstance(codebook_table, pd.DataFrame):
        codebook_rows = codebook_table.fillna("").to_dict("records")
    else:
        codebook_rows = []

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase2_initial_coding",
        "methodology": "Braun & Clarke 2006 Phase 2 β€” Generating Initial Codes (agentic)",
        "method_contracts_enforced": (
            "See method_contracts.check_phase2_initial_coding β€” enforced at run time. "
            "Contracts: B&C 2006 p. 84 (orientation), p. 88 (systematic coverage), "
            "reflexivity principle (positioning injected), iterative refinement (iter 1-3)."
        ),
        "corpus_size": len(corpus or []),
        "codes_table": codes_rows,
        "codebook": codebook_rows,
    }
    path = save_json_artifact(artifact, "phase2_initial_coding")
    dl.append(path)

    # -- Supabase persistence --
    db_note = ""
    if DB_OK:
        try:
            # Re-read directly from artifact to avoid empty DataFrame issue
            codes_to_save = artifact.get("codes_table", [])
            cb_to_save = artifact.get("codebook", [])
            n_codes = db.save_coded_sentences(codes_to_save)
            n_cb = db.save_codebook(cb_to_save)
            db_note = f" Saved to Supabase: {n_codes} coded rows, {n_cb} codebook entries."
        except Exception as _dbe:
            db_note = f" Supabase save failed: {_dbe}"

    status = (
        f"**Saved Final Codes** β€” {len(codes_rows)} coded sentences, "
        f"{len(codebook_rows)} codebook entries. Artifact: `{path.split('/')[-1]}`{db_note}"
    )
    return status, dl, dl




# ----------------------------------------------------------------
# Phase 3 -- Searching for Themes handlers (Braun & Clarke 2006)
# ----------------------------------------------------------------
def handle_p3_run(

    codebook_table,

    similarity_threshold,

    min_cluster_size,

    orientation,

    companion_reflexivity,

    llm_provider, llm_key,

    downloads_list,

):
    dl = list(downloads_list or [])
    empty_themes = pd.DataFrame(columns=[
        "theme_id", "candidate_theme_name", "description", "rationale",
        "member_codes", "code_count", "researcher_theme_name", "researcher_notes",
    ])
    empty_noise = pd.DataFrame(columns=["code_name", "definition"])

    if not PHASE3_OK:
        return (empty_themes, empty_noise,
                f"**Phase 3 unavailable** -- {_phase3_err}", dl, dl)

    if codebook_table is None or (isinstance(codebook_table, pd.DataFrame) and codebook_table.empty):
        return (empty_themes, empty_noise,
                "**Cannot run Phase 3** -- no codebook. Run Phase 2 first.", dl, dl)

    key = (llm_key or "").strip() or os.environ.get("MISTRAL_API_KEY", "")
    if not key:
        return (empty_themes, empty_noise,
                "**Cannot run Phase 3** -- Mistral API key missing.", dl, dl)

    codebook_df = codebook_table.copy() if isinstance(codebook_table, pd.DataFrame) else pd.DataFrame(codebook_table)

    # --- FT50 method contract check (B&C 2006 Phase 3) ---
    try:
        contracts = check_phase3_searching_themes(
            codebook_table=codebook_df,
            similarity_threshold=float(similarity_threshold),
            min_cluster_size=int(min_cluster_size),
            llm_key=key,
        )
    except MethodContractError as e:
        return (empty_themes, empty_noise,
                f"**Method contract violation (Phase 3):**\n\n{e}", dl, dl)

    try:
        result = run_phase3_searching_themes(
            codebook_df=codebook_df,
            llm_provider=llm_provider or "Mistral",
            llm_key=key,
            similarity_threshold=float(similarity_threshold),
            min_cluster_size=int(min_cluster_size),
            orientation=orientation or "semantic",
            reflexive_pos=companion_reflexivity or "",
        )
    except Exception as e:
        return (empty_themes, empty_noise, f"**Phase 3 error:** {e}", dl, dl)

    themes_df = pd.DataFrame(result["themes_rows"]) if result["themes_rows"] else empty_themes
    noise_df = pd.DataFrame(result["noise_codes"]) if result["noise_codes"] else empty_noise

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase3_searching_themes",
        "methodology": "Braun & Clarke 2006 Phase 3 -- Searching for Themes",
        "method_contracts_verified": contracts_as_dicts(contracts),
        "similarity_threshold": float(similarity_threshold),
        "min_cluster_size": int(min_cluster_size),
        "orientation": orientation,
        "n_themes": result["n_themes"],
        "n_noise": result["n_noise"],
        "themes": result["themes_rows"],
        "noise_codes": result["noise_codes"],
    }
    path = save_json_artifact(artifact, "phase3_searching_themes")
    dl.append(path)

    status = (
        "**Phase 3 complete.** "
        + str(result["n_themes"]) + " candidate themes from "
        + str(len(codebook_df)) + " codes. "
        + str(result["n_noise"]) + " codes in noise bucket. "
        + "Artifact: `" + path.split("/")[-1] + "`"
    )
    return themes_df, noise_df, status, dl, dl


def handle_p3_save(themes_table, noise_table, downloads_list):
    dl = list(downloads_list or [])
    themes_rows = themes_table.fillna("").to_dict("records") if isinstance(themes_table, pd.DataFrame) else []
    noise_rows = noise_table.fillna("").to_dict("records") if isinstance(noise_table, pd.DataFrame) else []
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase3_researcher_confirmed_themes",
        "methodology": "Braun & Clarke 2006 Phase 3 -- Researcher-confirmed candidate themes",
        "themes": themes_rows,
        "noise_codes": noise_rows,
    }
    path = save_json_artifact(artifact, "phase3_themes")
    dl.append(path)

    # -- Supabase persistence --
    db_note = ""
    if DB_OK:
        try:
            n_themes = db.save_themes(themes_rows)
            db_note = f" Saved to Supabase: {n_themes} themes."
        except Exception as _dbe:
            db_note = f" Supabase save failed: {_dbe}"

    status = (
        "**Saved Phase 3 themes** -- "
        + str(len(themes_rows)) + " themes, "
        + str(len(noise_rows)) + " noise codes. Artifact: `" + path.split("/")[-1] + "`"
        + db_note
    )
    return status, dl, dl

# ----------------------------------------------------------------
# Phase 4 -- Reviewing Themes handlers (Braun & Clarke 2006)
# ----------------------------------------------------------------
def handle_p4_run(

    themes_table, codes_table,

    companion_reflexivity,

    llm_provider, llm_key,

    downloads_list,

):
    dl = list(downloads_list or [])
    empty = pd.DataFrame(columns=[
        "theme_id", "theme_name", "member_codes", "code_count",
        "member_sentence_count", "within_cohesion",
        "llm_verdict", "llm_reasoning", "llm_action_suggestion",
        "researcher_verdict", "researcher_action_notes",
    ])

    if not PHASE4_OK:
        return empty, f"**Phase 4 unavailable** -- {_phase4_err}", dl, dl

    if themes_table is None or (isinstance(themes_table, pd.DataFrame) and themes_table.empty):
        return empty, "**Cannot run Phase 4** -- no themes. Run Phase 3 first.", dl, dl

    key = (llm_key or "").strip() or os.environ.get("MISTRAL_API_KEY", "")
    if not key:
        return empty, "**Cannot run Phase 4** -- Mistral API key missing.", dl, dl

    themes_df = themes_table.copy() if isinstance(themes_table, pd.DataFrame) else pd.DataFrame(themes_table)
    codes_df = codes_table.copy() if isinstance(codes_table, pd.DataFrame) else pd.DataFrame()

    # --- FT50 method contract check (B&C 2006 Phase 4) ---
    try:
        contracts = check_phase4_reviewing_themes(
            themes_table=themes_df,
            codes_table=codes_df,
            llm_key=key,
        )
    except MethodContractError as e:
        return empty, f"**Method contract violation (Phase 4):**\n\n{e}", dl, dl

    try:
        result = run_phase4_reviewing_themes(
            themes_df=themes_df,
            codes_df=codes_df,
            corpus=[],
            llm_key=key,
            llm_provider=llm_provider or "Mistral",
            reflexive_pos=companion_reflexivity or "",
        )
    except Exception as e:
        return empty, f"**Phase 4 error:** {e}", dl, dl

    review_df = pd.DataFrame(result["review_rows"]) if result["review_rows"] else empty

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase4_reviewing_themes",
        "methodology": "Braun & Clarke 2006 Phase 4 -- Reviewing Themes",
        "method_contracts_verified": contracts_as_dicts(contracts),
        "review_rows": result["review_rows"],
        "errors": result["errors"],
    }
    path = save_json_artifact(artifact, "phase4_reviewing_themes")
    dl.append(path)

    warns = result.get("errors", [])
    warn_note = " " + str(len(warns)) + " errors." if warns else ""
    status = (
        "**Phase 4 complete.** " + str(len(result["review_rows"])) + " themes reviewed."
        + warn_note + " Artifact: `" + path.split("/")[-1] + "`"
    )
    return review_df, status, dl, dl


def handle_p4_save(review_table, downloads_list):
    dl = list(downloads_list or [])
    rows = review_table.fillna("").to_dict("records") if isinstance(review_table, pd.DataFrame) else []
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase4_researcher_verdicts",
        "methodology": "Braun & Clarke 2006 Phase 4 -- Researcher-confirmed theme verdicts",
        "review_rows": rows,
    }
    path = save_json_artifact(artifact, "phase4_verdicts")
    dl.append(path)

    # -- Supabase persistence --
    db_note = ""
    if DB_OK:
        try:
            n_reviews = db.save_theme_reviews(rows)
            db_note = f" Saved to Supabase: {n_reviews} verdicts."
        except Exception as _dbe:
            db_note = f" Supabase save failed: {_dbe}"

    status = "**Saved Phase 4 verdicts** -- " + str(len(rows)) + " rows. Artifact: `" + path.split("/")[-1] + "`" + db_note
    return status, dl, dl


# ----------------------------------------------------------------
# Phase 5 -- Defining and Naming Themes handlers
# ----------------------------------------------------------------
def handle_p5_run(

    review_table,

    companion_reflexivity,

    llm_provider, llm_key,

    downloads_list,

):
    dl = list(downloads_list or [])
    empty = pd.DataFrame(columns=[
        "theme_id", "original_name", "final_name", "definition",
        "scope_note", "narrative_contribution", "member_codes",
        "code_count", "researcher_final_name", "researcher_definition",
    ])

    if not PHASE5_OK:
        return empty, f"**Phase 5 unavailable** -- {_phase5_err}", dl, dl

    if review_table is None or (isinstance(review_table, pd.DataFrame) and review_table.empty):
        return empty, "**Cannot run Phase 5** -- no theme reviews. Run Phase 4 first.", dl, dl

    key = (llm_key or "").strip() or os.environ.get("MISTRAL_API_KEY", "")
    if not key:
        return empty, "**Cannot run Phase 5** -- Mistral API key missing.", dl, dl

    review_df = review_table.copy() if isinstance(review_table, pd.DataFrame) else pd.DataFrame(review_table)

    # --- FT50 method contract check (B&C 2006 Phase 5) ---
    try:
        contracts = check_phase5_defining_naming(
            review_table=review_df,
            llm_key=key,
        )
    except MethodContractError as e:
        return empty, f"**Method contract violation (Phase 5):**\n\n{e}", dl, dl

    try:
        result = run_phase5_defining_naming(
            review_df=review_df,
            llm_key=key,
            llm_provider=llm_provider or "Mistral",
            reflexive_pos=companion_reflexivity or "",
        )
    except Exception as e:
        return empty, f"**Phase 5 error:** {e}", dl, dl

    def_df = pd.DataFrame(result["definition_rows"]) if result["definition_rows"] else empty

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase5_defining_naming",
        "methodology": "Braun & Clarke 2006 Phase 5 -- Defining and Naming Themes",
        "method_contracts_verified": contracts_as_dicts(contracts),
        "definition_rows": result["definition_rows"],
        "skipped": result["skipped"],
        "errors": result["errors"],
    }
    path = save_json_artifact(artifact, "phase5_defining_naming")
    dl.append(path)

    skip_note = f" {len(result['skipped'])} themes dropped (verdict=drop)." if result["skipped"] else ""
    status = (
        "**Phase 5 complete.** "
        + str(len(result["definition_rows"])) + " themes defined." + skip_note
        + " Artifact: `" + path.split("/")[-1] + "`"
    )
    return def_df, status, dl, dl


def handle_p5_save(def_table, downloads_list):
    dl = list(downloads_list or [])
    rows = def_table.fillna("").to_dict("records") if isinstance(def_table, pd.DataFrame) else []
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase5_researcher_definitions",
        "methodology": "Braun & Clarke 2006 Phase 5 -- Researcher-confirmed theme definitions",
        "definition_rows": rows,
    }
    path = save_json_artifact(artifact, "phase5_definitions")
    dl.append(path)
    status = "**Saved Phase 5 definitions** -- " + str(len(rows)) + " themes. Artifact: `" + path.split("/")[-1] + "`"
    return status, dl, dl


# ----------------------------------------------------------------
# Phase 6 -- Producing the Report handlers
# ----------------------------------------------------------------
def handle_p6_run(

    def_table, codes_table,

    research_question,

    companion_reflexivity,

    corpus,

    llm_provider, llm_key,

    downloads_list,

):
    dl = list(downloads_list or [])

    if not PHASE6_OK:
        return "", f"**Phase 6 unavailable** -- {_phase6_err}", dl, dl

    if def_table is None or (isinstance(def_table, pd.DataFrame) and def_table.empty):
        return "", "**Cannot run Phase 6** -- no theme definitions. Run Phase 5 first.", dl, dl

    key = (llm_key or "").strip() or os.environ.get("MISTRAL_API_KEY", "")
    if not key:
        return "", "**Cannot run Phase 6** -- Mistral API key missing.", dl, dl

    def_df = def_table.copy() if isinstance(def_table, pd.DataFrame) else pd.DataFrame(def_table)
    codes_df = codes_table.copy() if isinstance(codes_table, pd.DataFrame) else pd.DataFrame()
    corpus_desc = f"{len(corpus or [])} sentences" if corpus else "qualitative corpus"

    # --- FT50 method contract check (B&C 2006 Phase 6) ---
    try:
        contracts = check_phase6_producing_report(
            def_table=def_df,
            llm_key=key,
        )
    except MethodContractError as e:
        return "", f"**Method contract violation (Phase 6):**\n\n{e}", dl, dl

    try:
        result = run_phase6_producing_report(
            definition_df=def_df,
            codes_df=codes_df,
            llm_key=key,
            llm_provider=llm_provider or "Mistral",
            research_question=research_question or "",
            reflexive_pos=companion_reflexivity or "",
            corpus_description=corpus_desc,
        )
    except Exception as e:
        return "", f"**Phase 6 error:** {e}", dl, dl

    if result["error"]:
        return "", f"**Phase 6 error:** {result['error']}", dl, dl

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase6_producing_report",
        "methodology": "Braun & Clarke 2006 Phase 6 -- Producing the Report",
        "method_contracts_verified": contracts_as_dicts(contracts),
        "theme_count": result["theme_count"],
        "report_markdown": result["report_markdown"],
    }
    path = save_json_artifact(artifact, "phase6_report")
    dl.append(path)

    status = (
        "**Phase 6 complete.** Report generated for "
        + str(result["theme_count"]) + " themes. "
        + "Artifact: `" + path.split("/")[-1] + "`"
    )
    return result["report_markdown"], status, dl, dl


def handle_p6_save(report_text, downloads_list):
    dl = list(downloads_list or [])
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase6_researcher_report",
        "methodology": "Braun & Clarke 2006 Phase 6 -- Researcher-edited final report",
        "report_markdown": report_text or "",
    }
    path = save_json_artifact(artifact, "phase6_final_report")
    # Also save as .md file
    md_path = path.replace(".json", ".md")
    with open(md_path, "w") as f:
        f.write(report_text or "")
    dl.extend([path, md_path])
    status = "**Saved Phase 6 report** -- JSON + Markdown. Artifact: `" + md_path.split("/")[-1] + "`"
    return status, dl, dl


# ----------------------------------------------------------------
# Phase 0 Preparation handlers (Moreno-Ortiz 2023; BERTopic_Teen 2025)
# ----------------------------------------------------------------
# Four pre-sampling hygiene steps. Each emits an artifact JSON with
# full reproducibility audit + literature citation.
#
# Data flow: corpus (list-of-dicts from upload) β†’ DataFrame β†’
#   noise_strip β†’ length_filter β†’ hash_dedup β†’ semantic_dedup β†’
# DataFrame with frequency_weight col β†’ back to list-of-dicts
# (this becomes the input to Phase 0 Sampling).
#
# All 4 preserve L1/L2/L3/L4/sentence_id/sentence schema.
# All 4 add/update frequency_weight (dedup steps merge; other steps
# pass through).
# ----------------------------------------------------------------
def _corpus_to_df(corpus):
    """Convert corpus (list-of-dicts) to DataFrame with schema ready."""
    if not corpus:
        return pd.DataFrame(columns=["L1", "L2", "L3", "L4", "sentence_id", "sentence"])
    df = pd.DataFrame(corpus)
    # Ensure required columns exist
    for col in ["L1", "L2", "L3", "L4", "sentence_id", "sentence"]:
        if col not in df.columns:
            df[col] = ""
    return df


def _df_to_corpus(df):
    """Convert DataFrame back to list-of-dicts for downstream state."""
    if df is None or len(df) == 0:
        return []
    return df.fillna("").to_dict("records")


def handle_p0prep_length_filter(corpus, min_words, downloads_list):
    """Drop sentences shorter than min_words. Emit audit artifact."""
    dl = list(downloads_list or [])
    if not PHASE0_PREP_OK:
        return corpus or [], pd.DataFrame(), f"**Phase 0 Prep unavailable** β€” {_phase0_prep_err}", dl, dl
    if not corpus:
        return [], pd.DataFrame(), "**No corpus loaded.** Upload a CSV first.", dl, dl

    df_in = _corpus_to_df(corpus)
    result = apply_length_filter(df_in, min_words=int(min_words))
    if "error" in result:
        return corpus, pd.DataFrame(), f"**Length filter error:** {result['error']}", dl, dl

    df_out = result["filtered_df"]
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase0_prep_length_filter",
        "sub_step": "0.0.1",
        "methodology": "Moreno-Ortiz & GarcΓ­a-GΓ‘mez 2023 β€” length-based filtering",
        **{k: v for k, v in result.items() if k != "filtered_df"},
    }
    path = save_json_artifact(artifact, "phase0_prep_length_filter")
    dl.append(path)

    status = (
        f"**Length filter complete** (min_words={min_words}).  \n"
        f"- Input: {result['n_input']} rows  \n"
        f"- Dropped: {result['n_dropped']} (too short)  \n"
        f"- Kept: {result['n_kept']}  \n"
        f"- Word count distribution: min={result['n_words_distribution']['min']}, "
        f"median={result['n_words_distribution']['median']}, max={result['n_words_distribution']['max']}  \n"
        f"- Artifact: `{path.split('/')[-1]}`"
    )
    return _df_to_corpus(df_out), df_out, status, dl, dl


def handle_p0prep_noise_strip(corpus, downloads_list):
    """Strip URLs, emoji, problematic Unicode. Emit audit artifact."""
    dl = list(downloads_list or [])
    if not PHASE0_PREP_OK:
        return corpus or [], pd.DataFrame(), f"**Phase 0 Prep unavailable** β€” {_phase0_prep_err}", dl, dl
    if not corpus:
        return [], pd.DataFrame(), "**No corpus loaded.** Upload a CSV first.", dl, dl

    df_in = _corpus_to_df(corpus)
    result = apply_noise_strip(df_in)
    if "error" in result:
        return corpus, pd.DataFrame(), f"**Noise strip error:** {result['error']}", dl, dl

    df_out = result["filtered_df"]
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase0_prep_noise_strip",
        "sub_step": "0.0.2",
        "methodology": "Moreno-Ortiz & GarcΓ­a-GΓ‘mez 2023; BERTopic_Teen 2025 β€” regex-based hygiene",
        **{k: v for k, v in result.items() if k != "filtered_df"},
    }
    path = save_json_artifact(artifact, "phase0_prep_noise_strip")
    dl.append(path)

    status = (
        f"**Noise strip complete.**  \n"
        f"- URLs removed: {result['n_urls_removed']}  \n"
        f"- Emoji removed: {result['n_emoji_removed']}  \n"
        f"- Sentences modified: {result['n_sentences_modified']}  \n"
        f"- Sentences emptied by stripping: {result['n_sentences_emptied']} "
        f"(run length filter next to drop them)  \n"
        f"- Artifact: `{path.split('/')[-1]}`"
    )
    return _df_to_corpus(df_out), df_out, status, dl, dl


def handle_p0prep_hash_dedup(corpus, case_sensitive, downloads_list):
    """Exact-match dedup with frequency_weight counter. Emit audit artifact."""
    dl = list(downloads_list or [])
    if not PHASE0_PREP_OK:
        return corpus or [], pd.DataFrame(), f"**Phase 0 Prep unavailable** β€” {_phase0_prep_err}", dl, dl
    if not corpus:
        return [], pd.DataFrame(), "**No corpus loaded.** Upload a CSV first.", dl, dl

    df_in = _corpus_to_df(corpus)
    result = apply_hash_dedup(df_in, case_sensitive=bool(case_sensitive))
    if "error" in result:
        return corpus, pd.DataFrame(), f"**Hash dedup error:** {result['error']}", dl, dl

    df_out = result["filtered_df"]
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase0_prep_hash_dedup",
        "sub_step": "0.0.3",
        "methodology": "Moreno-Ortiz & GarcΓ­a-GΓ‘mez 2023 β€” frequency-preserving exact dedup",
        **{k: v for k, v in result.items() if k != "filtered_df"},
    }
    path = save_json_artifact(artifact, "phase0_prep_hash_dedup")
    dl.append(path)

    status = (
        f"**Hash deduplication complete.**  \n"
        f"- Input sentences (weighted): {result['n_input']}  \n"
        f"- Unique after dedup: {result['n_unique']}  \n"
        f"- Duplicates merged: {result['n_duplicates_merged']} "
        f"({result['duplication_rate_pct']}%)  \n"
        f"- Max frequency_weight: {result['max_frequency_weight']}  \n"
        f"- Invariant preserved: {result['invariant_preserved']} "
        f"(sum of frequency_weight == input count)  \n"
        f"- Artifact: `{path.split('/')[-1]}`"
    )
    return _df_to_corpus(df_out), df_out, status, dl, dl


def handle_p0prep_semantic_dedup(corpus, threshold, downloads_list):
    """MiniLM semantic near-dup merge. Emit audit artifact."""
    dl = list(downloads_list or [])
    if not PHASE0_PREP_OK:
        return corpus or [], pd.DataFrame(), f"**Phase 0 Prep unavailable** β€” {_phase0_prep_err}", dl, dl
    if not corpus:
        return [], pd.DataFrame(), "**No corpus loaded.** Upload a CSV first.", dl, dl

    df_in = _corpus_to_df(corpus)
    result = apply_semantic_dedup(df_in, threshold=float(threshold))
    if "error" in result:
        return corpus, pd.DataFrame(), f"**Semantic dedup error:** {result['error']}", dl, dl

    df_out = result["filtered_df"]
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase0_prep_semantic_dedup",
        "sub_step": "0.0.4",
        "methodology": "BERTopic_Teen 2025; SemDeDup Abbas 2023 β€” MiniLM cosine near-duplicate merge",
        **{k: v for k, v in result.items() if k != "filtered_df"},
    }
    path = save_json_artifact(artifact, "phase0_prep_semantic_dedup")
    dl.append(path)

    status = (
        f"**Semantic dedup complete** (threshold={threshold}).  \n"
        f"- Input rows: {result.get('n_input_rows', result['n_input'])}  \n"
        f"- Unique after dedup: {result['n_unique']}  \n"
        f"- Near-duplicates merged: {result['n_near_duplicates_merged']}  \n"
        f"- Model: `{result['model']}`  \n"
        f"- Invariant preserved: {result['invariant_preserved']}  \n"
        f"- Artifact: `{path.split('/')[-1]}`"
    )
    return _df_to_corpus(df_out), df_out, status, dl, dl


# ----------------------------------------------------------------
# Phase 0 -- Sampling handler (Gauthier & Wallace 2022)
# ----------------------------------------------------------------
_PHASE0_EMPTY_COLS = [
    "idx", "L1", "L2", "L3", "L4", "sentence_id", "sentence",
    "cluster_id_original", "cluster_id_refined", "cluster_id",
    "cluster_fit", "cluster_mean_fit", "cluster_std_fit",
    "cluster_quality_tier", "split_decision",
    "cluster_size", "selected", "reason",
]


def _build_split_proposal_df(split_proposals: dict, cluster_stats_by_orig: dict) -> pd.DataFrame:
    """Render LOOSE-cluster split proposals as an editable researcher-review

    table. Columns: cluster_id_original, cluster_size, std_before, n_sub_proposed,

    max_std_after, improvement, target_reached, decision (editable).

    """
    if not split_proposals:
        return pd.DataFrame(columns=[
            "cluster_id_original", "cluster_size", "std_before",
            "n_sub_proposed", "max_std_after", "improvement",
            "target_reached", "decision",
        ])
    rows = []
    for cid, prop in sorted(split_proposals.items()):
        st = cluster_stats_by_orig.get(cid, {})
        rows.append({
            "cluster_id_original": int(cid),
            "cluster_size": int(st.get("size", 0)),
            "std_before": round(float(st.get("std_fit", 0.0)), 4),
            "n_sub_proposed": int(prop.get("n_sub", 1)),
            "max_std_after": round(
                float(max(prop.get("sub_stds", [0.0]))) if prop.get("sub_stds") else 0.0,
                4,
            ),
            "improvement": round(float(prop.get("improvement", 0.0)), 4),
            "target_reached": bool(prop.get("target_reached", False)),
            "decision": "PENDING",  # researcher edits to ACCEPTED / REJECTED
        })
    return pd.DataFrame(rows)


def handle_compression_run(

    corpus,

    sentences_per_cluster,

    min_cluster_size,

    outlier_sample_size,

    min_cluster_fit,

    downloads_list,

):
    """

    Phase 0 Sampling β€” FT50 two-stage design.



    Stage 1: HDBSCAN initial clustering.

    Stage 2: Spread diagnostic per cluster (TIGHT/MEDIUM/LOOSE).

    Stage 3: Agglomerative split PROPOSALS for LOOSE clusters. Researcher

             reviews in a separate table and accepts/rejects.

    Stage 4: Stratified sampling at 10% of cluster size (floor = min_cluster_size).



    First call produces proposals with `decision=PENDING`. Researcher edits

    the proposal table then clicks "Apply Split Decisions" to re-run Phase 0

    with decisions applied (see handle_apply_split_decisions).

    """
    dl = list(downloads_list or [])
    empty = pd.DataFrame(columns=_PHASE0_EMPTY_COLS)
    empty_proposals = pd.DataFrame(columns=[
        "cluster_id_original", "cluster_size", "std_before",
        "n_sub_proposed", "max_std_after", "improvement",
        "target_reached", "decision",
    ])

    if not COMPRESSION_OK:
        return (empty, empty_proposals, corpus or [],
                f"**Sampling unavailable** -- {_compression_err}", dl, dl)

    if not corpus:
        return (empty, empty_proposals, [],
                "**No corpus loaded.** Run Phase 0 Preparation first.", dl, dl)

    # --- FT50 method contract check (G&W 2022 Phase 0) ---
    try:
        contracts = check_phase0_compression(
            corpus=corpus,
            sentences_per_cluster=int(sentences_per_cluster),
            min_cluster_size=int(min_cluster_size),
            outlier_sample_size=int(outlier_sample_size),
        )
    except MethodContractError as e:
        return (empty, empty_proposals, corpus or [],
                f"**Method contract violation (Phase 0):**\n\n{e}", dl, dl)

    try:
        result = run_corpus_compression(
            corpus=corpus,
            sentences_per_cluster=int(sentences_per_cluster),
            min_cluster_size=int(min_cluster_size),
            outlier_sample_size=int(outlier_sample_size),
            min_cluster_fit=float(min_cluster_fit),
            auto_split_loose=True,
            split_decisions=None,  # first pass: no decisions applied
        )
    except Exception as e:
        return (empty, empty_proposals, corpus,
                f"**Sampling error:** {type(e).__name__}: {e}", dl, dl)

    # Phase 0 Sampling output ends here. No `final_label` column β€” labels are
    # produced by the DOWNSTREAM Cluster Labeling stage as its own frozen
    # artifact. Phase 1 and later stages join the two artifacts at read-time
    # on cluster_id. This enforces the one-way pipeline: no later stage
    # mutates this Phase 0 output.
    comp_df = pd.DataFrame(result["compression_rows"]) if result["compression_rows"] else empty

    # Build stats-by-original-cluster mapping for proposal table rendering
    cluster_stats_by_orig: dict[int, dict] = {}
    for row in result["compression_rows"]:
        cid = int(row["cluster_id_original"])
        if cid == -1:
            continue
        if cid not in cluster_stats_by_orig:
            cluster_stats_by_orig[cid] = {
                "size": int(row["cluster_size"]),
                "std_fit": float(row["cluster_std_fit"]),
            }

    proposals_df = _build_split_proposal_df(
        result.get("split_proposals", {}), cluster_stats_by_orig
    )

    quality = result.get("quality_summary", {})
    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase0_sampling",
        "methodology": (
            "Gauthier & Wallace (2022) computational thematic analysis at scale, "
            "extended with two-stage clustering (HDBSCAN β†’ Agglomerative refinement "
            "on LOOSE clusters) and spread-aware stratified sampling for FT50 "
            "submission. Researcher-in-the-loop review preserves B&C 2021 reflexivity."
        ),
        "method_contracts_verified": contracts_as_dicts(contracts),
        "design": {
            "stage_1_clustering": "HDBSCAN (Campello, Moulavi, Zimek & Sander 2015, ACM TKDD 10(1):1-51)",
            "stage_2_spread_diagnostic": "std(cluster_fit) classified TIGHT (<0.15) / MEDIUM (0.15-0.20) / LOOSE (>=0.20)",
            "stage_3_agglomerative_refinement": "Ward (1963) JASA 58(301):236-244; applied to LOOSE clusters; researcher ACCEPT/REJECT/PENDING",
            "stage_4_sampling": "Stratified by cluster_fit (50% top / 30% middle / 20% edge), n = max(min_cluster_size, ceil(0.10 Γ— N))",
        },
        "references": {
            "embedding": "Reimers & Gurevych (2019). Sentence-BERT. EMNLP 2019.",
            "initial_clustering": "Campello, Moulavi, Zimek & Sander (2015). ACM TKDD 10(1):1-51.",
            "agglomerative_split": "Ward (1963). JASA 58(301):236-244.",
            "computational_ta_at_scale": "Gauthier & Wallace (2022). Proc. ACM HCI 6(GROUP) Article 25.",
            "b_and_c_reflexivity": "Braun & Clarke (2021). Qualitative Research in Psychology.",
            "researcher_validation": "Carlsen & Ralund (2022). Big Data & Society 9(1).",
        },
        "n_original": result["n_original"],
        "n_compressed": result["n_compressed"],
        "n_clusters": result["n_clusters"],
        "n_outliers": result["n_outliers"],
        "parameters": {
            "sentences_per_cluster_legacy": int(sentences_per_cluster),
            "min_cluster_size": int(min_cluster_size),
            "outlier_sample_size": int(outlier_sample_size),
            "min_cluster_fit_threshold": float(min_cluster_fit),
            "spread_tight_max": 0.15,
            "spread_medium_max": 0.20,
            "sample_percentage": 0.10,
            "stratify_top_middle_edge": [0.50, 0.30, 0.20],
        },
        "quality_summary": quality,
        "split_proposals_pending_review": [
            {
                "cluster_id_original": int(cid),
                "n_sub_proposed": int(prop["n_sub"]),
                "sub_stds": [round(float(s), 4) for s in prop.get("sub_stds", [])],
                "improvement": round(float(prop.get("improvement", 0.0)), 4),
                "target_reached": bool(prop.get("target_reached", False)),
            }
            for cid, prop in result.get("split_proposals", {}).items()
        ],
        "compression_rows": result["compression_rows"],
    }
    path = save_json_artifact(artifact, "corpus_compression")
    dl.append(path)

    errors_note = " " + "; ".join(result["errors"]) if result["errors"] else ""

    # Build diagnostic status
    tight = quality.get("TIGHT", 0)
    medium = quality.get("MEDIUM", 0)
    loose = quality.get("LOOSE", 0)
    flagged = quality.get("n_flagged_for_split", 0)

    quality_note = (
        f"  \n- **Cluster quality:** "
        f"{tight} TIGHT (std<0.15), {medium} MEDIUM (0.15-0.20), "
        f"**{loose} LOOSE (β‰₯0.20)**"
    )
    if flagged > 0:
        quality_note += (
            f"  \n- **{flagged} LOOSE cluster(s) flagged for Agglomerative split review.** "
            f"See the **Split Proposals** table below and set `decision` to "
            f"`ACCEPTED` or `REJECTED`, then click **Apply Split Decisions** to re-sample. "
            f"Committing now will proceed with PENDING decisions (soft-warn, logged in audit)."
        )

    status = (
        "**Phase 0 Sampling complete.** "
        + str(result["n_original"]) + " sentences β†’ "
        + str(result["n_compressed"]) + " selected across "
        + str(result["n_clusters"]) + " clusters ("
        + str(result["n_outliers"]) + " outliers)."
        + quality_note
        + errors_note
        + "  \nArtifact: `" + path.split("/")[-1] + "`"
    )
    return comp_df, proposals_df, result["compressed_corpus"], status, dl, dl


# ----------------------------------------------------------------
# Apply researcher split decisions (re-runs Phase 0 with decisions)
# ----------------------------------------------------------------
def handle_apply_split_decisions(

    corpus,

    proposals_df,

    sentences_per_cluster,

    min_cluster_size,

    outlier_sample_size,

    min_cluster_fit,

    downloads_list,

):
    """

    Re-run Phase 0 with researcher ACCEPT/REJECT decisions from the proposals

    table. Each ACCEPTED cluster gets its Agglomerative sub-cluster split

    applied, producing refined cluster IDs (original*1000 + sub_id).

    """
    dl = list(downloads_list or [])
    empty = pd.DataFrame(columns=_PHASE0_EMPTY_COLS)
    empty_proposals = pd.DataFrame(columns=[
        "cluster_id_original", "cluster_size", "std_before",
        "n_sub_proposed", "max_std_after", "improvement",
        "target_reached", "decision",
    ])

    if not COMPRESSION_OK:
        return (empty, empty_proposals, corpus or [],
                f"**Sampling unavailable** -- {_compression_err}", dl, dl)
    if not corpus:
        return (empty, empty_proposals, [],
                "**No corpus loaded.** Run Phase 0 Preparation first.", dl, dl)

    # Parse decisions out of the proposals dataframe
    decisions: dict[int, str] = {}
    if isinstance(proposals_df, pd.DataFrame) and not proposals_df.empty:
        for _, row in proposals_df.iterrows():
            try:
                cid = int(row["cluster_id_original"])
                dec = str(row.get("decision", "PENDING")).upper().strip()
                if dec in ("ACCEPTED", "REJECTED", "PENDING"):
                    decisions[cid] = dec
            except Exception:
                continue

    try:
        result = run_corpus_compression(
            corpus=corpus,
            sentences_per_cluster=int(sentences_per_cluster),
            min_cluster_size=int(min_cluster_size),
            outlier_sample_size=int(outlier_sample_size),
            min_cluster_fit=float(min_cluster_fit),
            auto_split_loose=True,
            split_decisions=decisions,
        )
    except Exception as e:
        return (empty, empty_proposals, corpus,
                f"**Re-sampling error:** {type(e).__name__}: {e}", dl, dl)

    comp_df = pd.DataFrame(result["compression_rows"]) if result["compression_rows"] else empty

    # Preserve researcher decisions in the proposal table (don't reset)
    cluster_stats_by_orig: dict[int, dict] = {}
    for row in result["compression_rows"]:
        cid = int(row["cluster_id_original"])
        if cid == -1:
            continue
        if cid not in cluster_stats_by_orig:
            cluster_stats_by_orig[cid] = {
                "size": int(row["cluster_size"]),
                "std_fit": float(row["cluster_std_fit"]),
            }
    proposals_out_df = _build_split_proposal_df(
        result.get("split_proposals", {}), cluster_stats_by_orig
    )
    # Override decision column with researcher's prior decisions
    if not proposals_out_df.empty:
        proposals_out_df["decision"] = proposals_out_df["cluster_id_original"].map(
            lambda c: decisions.get(int(c), "PENDING")
        )

    quality = result.get("quality_summary", {})
    n_accepted = quality.get("n_splits_accepted", 0)
    n_rejected = quality.get("n_splits_rejected", 0)
    n_pending = quality.get("n_splits_pending", 0)

    errors_note = " " + "; ".join(result["errors"]) if result["errors"] else ""
    warn = ""
    if n_pending > 0:
        warn = (
            f"  \n⚠ **{n_pending} split decision(s) still PENDING.** "
            f"Soft-warn: Phase 0 artifact accepted with pending decisions. "
            f"Refine before commit if desired."
        )

    status = (
        "**Split decisions applied.** "
        + str(result["n_original"]) + " sentences β†’ "
        + str(result["n_compressed"]) + " selected across "
        + str(result["n_clusters"]) + " refined clusters."
        + f"  \n- Splits: {n_accepted} ACCEPTED, {n_rejected} REJECTED, {n_pending} PENDING"
        + warn
        + errors_note
    )
    return comp_df, proposals_out_df, result["compressed_corpus"], status, dl, dl


# ----------------------------------------------------------------
# LLM cluster labeling handlers β€” Phase 2 pattern (DataFrame in/out, no state)
# ----------------------------------------------------------------
# Matches the B&C Phase 2 handle_p2_run_iteration pattern that works without
# flicker: handler takes DataFrames as inputs, returns DataFrames as outputs,
# no separate gr.State machinery. Gradio handles the DataFrame round-trip.
def handle_label_init_cluster_table(compression_rows_df):
    """Build cluster-level editing table from compression DataFrame.

    Returns (cluster_df, status_markdown)."""
    empty_cluster_df = pd.DataFrame(columns=[
        "cluster_id", "cluster_size", "mean_cluster_fit",
        "top3_sentences_preview",
        "llm_label_iter1", "researcher_edit_iter1",
        "llm_label_iter2", "researcher_edit_iter2",
        "final_label",
    ])

    if not CLUSTER_LABELING_OK:
        return empty_cluster_df, f"**Cluster labeling unavailable** β€” {_cluster_labeling_err}"

    # compression_rows_df comes from live gw_compress_table
    if isinstance(compression_rows_df, pd.DataFrame):
        rows = compression_rows_df.to_dict(orient="records") if not compression_rows_df.empty else []
    else:
        rows = list(compression_rows_df or [])

    if not rows:
        return empty_cluster_df, "**No sampling rows.** Run Phase 0 first."

    cluster_rows = build_cluster_table_from_compression(rows)
    if not cluster_rows:
        return empty_cluster_df, "**No non-noise clusters to label.**"

    # Preview column already includes [L1 > sentence_id] provenance
    # (built by cluster_labeling.build_cluster_table_from_compression)

    df = pd.DataFrame(cluster_rows)
    status = (
        f"**Cluster Label table initialized.** {len(cluster_rows)} non-noise "
        f"clusters ready for labeling.  \n"
        f"Next: click *Run Iter 1* to have the LLM draft 2-word labels for "
        f"every cluster."
    )
    return df, status


def handle_label_iter1(cluster_labels_df, compression_rows_df, llm_provider, llm_key, downloads_list):
    """Run LLM iter1 β€” labels every cluster.

    Returns (cluster_df, status_markdown, downloads, downloads)."""
    dl = list(downloads_list or [])
    empty_cluster_df = pd.DataFrame(columns=[
        "cluster_id", "cluster_size", "mean_cluster_fit",
        "top3_sentences_preview",
        "llm_label_iter1", "researcher_edit_iter1",
        "llm_label_iter2", "researcher_edit_iter2",
        "final_label",
    ])

    if not CLUSTER_LABELING_OK:
        return empty_cluster_df, f"**Cluster labeling unavailable** β€” {_cluster_labeling_err}", dl, dl

    # Read DataFrames directly
    if isinstance(cluster_labels_df, pd.DataFrame):
        cluster_rows = cluster_labels_df.to_dict(orient="records") if not cluster_labels_df.empty else []
    else:
        cluster_rows = list(cluster_labels_df or [])

    if isinstance(compression_rows_df, pd.DataFrame):
        comp_rows = compression_rows_df.to_dict(orient="records") if not compression_rows_df.empty else []
    else:
        comp_rows = list(compression_rows_df or [])

    # Auto-build cluster table if researcher didn't click Init first
    if not cluster_rows:
        cluster_rows = build_cluster_table_from_compression(comp_rows)
    if not cluster_rows:
        return empty_cluster_df, "**No cluster rows.** Run Phase 0 + Init cluster table first.", dl, dl

    # Preview column already includes [L1 > sentence_id] provenance
    # (built by cluster_labeling.build_cluster_table_from_compression)

    # Validate the UI key field is populated β€” the LLM API key field on the
    # landing page is the ONLY source. If it's empty, tell the user directly.
    key = (llm_key or "").strip()
    if not key:
        return pd.DataFrame(cluster_rows), (
            "**Iter 1 failed: LLM API key missing.** "
            "Paste your Mistral key in the **LLM API key** field at the top of the page, "
            "then click β‘‘ Run Iter 1 again."
        ), dl, dl

    try:
        result = run_iter1(
            cluster_rows=cluster_rows,
            compression_rows=comp_rows,
            llm_provider=llm_provider,
            llm_key=key,
        )
    except Exception as e:
        return pd.DataFrame(cluster_rows), f"**Iter 1 error:** {e}", dl, dl

    if result.get("errors") and result.get("n_labeled", 0) == 0:
        err = "; ".join(result["errors"])
        return pd.DataFrame(cluster_rows), f"**Iter 1 failed:** {err}", dl, dl

    updated = result["updated_cluster_rows"]
    df = pd.DataFrame(updated) if updated else empty_cluster_df

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase0_cluster_labels_iter1",
        "iteration": 1,
        "llm_model": result.get("model_name"),
        "temperature": 0.0,
        "prompt_template": result.get("prompt_template"),
        "label_length_constraint": "exactly 2 words",
        "scope": "every non-noise cluster",
        "n_labeled": result.get("n_labeled", 0),
        "n_errors": result.get("n_errors", 0),
        "errors": result.get("errors", []),
        "per_cluster_audit": result.get("audit", []),
    }
    path = save_json_artifact(artifact, "cluster_labels_iter1")
    dl.append(path)

    n_labeled = result.get("n_labeled", 0)
    n_errors = result.get("n_errors", 0)
    model = result.get("model_name", "unknown")
    err_line = f"  \n- LLM errors: {n_errors}" if n_errors else ""
    status = (
        f"**Iter 1 complete.** {n_labeled} clusters labeled (strict 2-word) via {model} "
        f"(temperature 0.0).  \n"
        f"- Review `llm_label_iter1` β€” type into `researcher_edit_iter1` where you want to refine  \n"
        f"- Then click β‘’ Run Iter 2 for an interpretive second pass on all clusters"
        f"{err_line}  \n"
        f"Artifact: `{path.split('/')[-1]}`"
    )
    return df, status, dl, dl


def handle_label_iter2(cluster_labels_df, compression_rows_df, llm_provider, llm_key, downloads_list):
    """Run LLM iter2 on flagged clusters only."""
    dl = list(downloads_list or [])
    empty_cluster_df = pd.DataFrame(columns=[
        "cluster_id", "cluster_size", "mean_cluster_fit",
        "top3_sentences_preview",
        "llm_label_iter1", "researcher_edit_iter1",
        "llm_label_iter2", "researcher_edit_iter2",
        "final_label",
    ])

    if not CLUSTER_LABELING_OK:
        return empty_cluster_df, f"**Cluster labeling unavailable** β€” {_cluster_labeling_err}", dl, dl

    if isinstance(cluster_labels_df, pd.DataFrame):
        cluster_rows = cluster_labels_df.to_dict(orient="records") if not cluster_labels_df.empty else []
    else:
        cluster_rows = list(cluster_labels_df or [])

    if isinstance(compression_rows_df, pd.DataFrame):
        comp_rows = compression_rows_df.to_dict(orient="records") if not compression_rows_df.empty else []
    else:
        comp_rows = list(compression_rows_df or [])

    if not cluster_rows:
        return empty_cluster_df, "**No cluster rows.** Run iter 1 first.", dl, dl

    # Validate the UI key field is populated β€” same as iter1
    key = (llm_key or "").strip()
    if not key:
        return pd.DataFrame(cluster_rows), (
            "**Iter 2 failed: LLM API key missing.** "
            "Paste your Mistral key in the **LLM API key** field at the top of the page, "
            "then click β‘’ Run Iter 2 again."
        ), dl, dl

    try:
        result = run_iter2(
            cluster_rows=cluster_rows,
            compression_rows=comp_rows,
            llm_provider=llm_provider,
            llm_key=key,
        )
    except Exception as e:
        return pd.DataFrame(cluster_rows), f"**Iter 2 error:** {e}", dl, dl

    if result.get("errors") and result.get("n_refined", 0) == 0:
        err = "; ".join(result["errors"])
        return pd.DataFrame(cluster_rows), f"**Iter 2 skipped/failed:** {err}", dl, dl

    updated = result["updated_cluster_rows"]
    df = pd.DataFrame(updated) if updated else empty_cluster_df

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "phase0_cluster_labels_iter2",
        "iteration": 2,
        "llm_model": result.get("model_name"),
        "temperature": 0.0,
        "prompt_template": result.get("prompt_template"),
        "label_length_constraint": "2-4 words max",
        "scope": "all clusters (interpretive re-label)",
        "n_refined": result.get("n_refined", 0),
        "n_errors": result.get("n_errors", 0),
        "errors": result.get("errors", []),
        "per_cluster_audit": result.get("audit", []),
    }
    path = save_json_artifact(artifact, "cluster_labels_iter2")
    dl.append(path)

    n_refined = result.get("n_refined", 0)
    n_errors = result.get("n_errors", 0)
    model = result.get("model_name", "unknown")
    err_line = f"  \n- LLM errors: {n_errors}" if n_errors else ""
    status = (
        f"**Iter 2 complete.** {n_refined} clusters re-labeled with interpretive "
        f"prompt via {model} (temp 0.0).  \n"
        f"- Review `llm_label_iter2` against `llm_label_iter1` β€” do they differ? Which is stronger?  \n"
        f"- Optionally type into `researcher_edit_iter2` to refine further  \n"
        f"- **Then type the winning label into `final_label` for every cluster**  \n"
        f"- Click *Commit Final Labels* when ALL final_labels are filled{err_line}  \n"
        f"Artifact: `{path.split('/')[-1]}`"
    )
    return df, status, dl, dl


def handle_label_commit_final(cluster_labels_df, compression_rows_df, downloads_list):
    """Commit researcher's final labels. ONE-WAY PIPELINE.



    Produces a frozen cluster-level artifact:

        {cluster_id β†’ final_label, choice_source, candidates}

    Does NOT mutate the Phase 0 Sampling Table (compression_rows). The Sampling

    Table is Phase 0's frozen output; this handler only writes its own artifact.

    Phase 1 and downstream stages join the two frozen artifacts at read-time

    on cluster_id.



    Returns: (cluster_df, status_markdown, downloads_state, downloads_files_out)

    β€” 4 outputs. Sampling Table is NOT in outputs.

    """
    dl = list(downloads_list or [])
    empty_cluster_df = pd.DataFrame(columns=[
        "cluster_id", "cluster_size", "mean_cluster_fit",
        "top3_sentences_preview",
        "llm_label_iter1", "researcher_edit_iter1",
        "llm_label_iter2", "researcher_edit_iter2",
        "final_label",
    ])

    if not CLUSTER_LABELING_OK:
        return (empty_cluster_df,
                f"**Cluster labeling unavailable** β€” {_cluster_labeling_err}", dl, dl)

    if isinstance(cluster_labels_df, pd.DataFrame):
        cluster_rows = cluster_labels_df.to_dict(orient="records") if not cluster_labels_df.empty else []
    else:
        cluster_rows = list(cluster_labels_df or [])

    if isinstance(compression_rows_df, pd.DataFrame):
        comp_rows = compression_rows_df.to_dict(orient="records") if not compression_rows_df.empty else []
    else:
        comp_rows = list(compression_rows_df or [])

    if not cluster_rows:
        return empty_cluster_df, "**No cluster rows.** Run iter 1 first.", dl, dl

    try:
        result = commit_final_labels(cluster_rows, comp_rows)
    except Exception as e:
        return (pd.DataFrame(cluster_rows),
                f"**Commit error:** {e}", dl, dl)

    # Validation failure: some final_labels blank β€” no artifact written, no propagation
    validation_error = result.get("validation_error")
    if validation_error:
        cluster_df = pd.DataFrame(cluster_rows) if cluster_rows else empty_cluster_df
        return (
            cluster_df,
            f"**Commit blocked.** {validation_error}",
            dl, dl,
        )

    updated_cluster = result["updated_cluster_rows"]
    cluster_df = pd.DataFrame(updated_cluster) if updated_cluster else empty_cluster_df

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "cluster_labels_final",
        "pipeline_stage": "cluster_labeling (downstream of phase0_sampling)",
        "methodology": (
            "For each cluster, researcher reviewed 4 candidate labels "
            "(llm_label_iter1 strict + researcher_edit_iter1 + llm_label_iter2 interpretive + "
            "researcher_edit_iter2) and typed authoritative final_label. "
            "Commit rejects blanks β€” every final_label is researcher-authored. "
            "Per Braun & Clarke (2006) 'themes are actively developed by the researcher.'"
        ),
        "pipeline_contract": (
            "This artifact is a frozen cluster-level mapping. "
            "Phase 0 Sampling's output (sentences with cluster_id) is NOT mutated. "
            "Downstream stages join on cluster_id at read-time."
        ),
        "n_committed": result.get("n_committed", 0),
        "n_blank": result.get("n_blank", 0),
        "source_distribution": result.get("source_distribution", {}),
        "cluster_id_to_final_label": {
            str(a["cluster_id"]): a["final_label"] for a in result.get("audit", [])
        },
        "per_cluster_resolution": result.get("audit", []),
    }
    path = save_json_artifact(artifact, "cluster_labels_final")
    dl.append(path)

    n_committed = result.get("n_committed", 0)
    source_dist = result.get("source_distribution", {})
    dist_lines = []
    label_map = {
        "llm_label_iter1": "LLM iter1 (strict)",
        "researcher_edit_iter1": "your iter1 edit",
        "llm_label_iter2": "LLM iter2 (interpretive)",
        "researcher_edit_iter2": "your iter2 edit",
        "custom_5th_option": "custom (none of 4 candidates)",
    }
    for src_key, friendly in label_map.items():
        n = source_dist.get(src_key, 0)
        if n:
            dist_lines.append(f"  - From **{friendly}**: {n}")
    dist_text = "\n".join(dist_lines) if dist_lines else "  - (no breakdown available)"

    status = (
        f"**Final labels committed.** {n_committed} clusters labeled.  \n"
        f"- Frozen artifact: cluster_id β†’ final_label mapping  \n"
        f"- Phase 0 Sampling Table above is **unchanged** (one-way pipeline)  \n"
        f"- Phase 1 and downstream stages will join on `cluster_id` at read-time  \n\n"
        f"**Source distribution of researcher's choices:**  \n"
        f"{dist_text}  \n\n"
        f"Artifact: `{path.split('/')[-1]}`"
    )
    return cluster_df, status, dl, dl


def handle_vectorize_preview(embedding_provider, embedding_key, downloads_list):
    """Compute embeddings for the first 10 training sentences and show them."""
    dl = list(downloads_list or [])
    if not VECTORSTORE_OK:
        return pd.DataFrame(), "vectorstore unavailable β€” check build logs", dl, dl

    try:
        rows = vectorstore.preview_vectors(
            n=10,
            embedding_provider=embedding_provider,
            embedding_api_key=embedding_key,
        )
    except Exception as e:
        return (
            pd.DataFrame(),
            f"Embedding failed on provider `{embedding_provider}`: {e}",
            dl, dl,
        )

    df = pd.DataFrame(rows)
    status = (
        f"**Embedding provider:** `{embedding_provider}`  \n"
        f"**Vector dim:** {rows[0]['vector_dim'] if rows else '?'}  \n"
        f"Showing first 10 sentences with the first 8 of the vector dimensions."
    )

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "vectorize_preview",
        "embedding_provider": embedding_provider,
        "preview_rows": rows,
    }
    path = save_json_artifact(artifact, "vectors_preview")
    dl.append(path)
    return df, status, dl, dl


def handle_vector_index(embedding_provider, embedding_key, downloads_list):
    """Embed all 100 sentences and write them to ChromaDB."""
    dl = list(downloads_list or [])
    if not VECTORSTORE_OK:
        return "vectorstore unavailable β€” check build logs", dl, dl

    try:
        result = vectorstore.index_training_data(
            embedding_provider=embedding_provider,
            embedding_api_key=embedding_key,
        )
    except Exception as e:
        return (
            f"Indexing failed on provider `{embedding_provider}`: {e}",
            dl, dl,
        )

    status = (
        f"**Indexed {result['indexed']} sentences** into ChromaDB collection "
        f"`{result['collection_name']}`.  \n"
        f"**Vector dim:** {result['vector_dim']}  \n"
        f"**Embedding provider:** `{result['embedding_provider']}`  \n"
        f"**Embedding model:** `{result['embedding_model']}`  \n"
        f"**Persist dir:** `{result['persist_dir']}`"
    )

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "vector_index",
        **result,
    }
    path = save_json_artifact(artifact, "vector_index")
    dl.append(path)
    return status, dl, dl


def handle_vector_search(query, n_results,

                         embedding_provider, embedding_key, downloads_list):
    """Semantic search β€” embed query and retrieve top-N nearest sentences."""
    dl = list(downloads_list or [])
    if not VECTORSTORE_OK:
        return pd.DataFrame(), "vectorstore unavailable β€” check build logs", dl, dl

    if not query or not query.strip():
        return pd.DataFrame(), "Enter a query to search.", dl, dl

    try:
        hits = vectorstore.search(
            query.strip(),
            n_results=int(n_results),
            embedding_provider=embedding_provider,
            embedding_api_key=embedding_key,
        )
    except Exception as e:
        return (
            pd.DataFrame(),
            f"Search failed on provider `{embedding_provider}`: {e}",
            dl, dl,
        )

    if not hits:
        return (
            pd.DataFrame(),
            "No results. Have you indexed the collection yet? "
            "Click 'Index all 100 sentences' in the Vector DB tab first. "
            "Note: indexing and searching must use the SAME embedding provider "
            "because vector dimensions differ between providers.",
            dl, dl,
        )

    df = pd.DataFrame([
        {
            "rank": i + 1,
            "similarity": round(h["similarity"], 4),
            "label": h["label"],
            "sentence": h["sentence"],
        }
        for i, h in enumerate(hits)
    ])
    status = f"**Query:** `{query}` β€” found {len(hits)} nearest neighbors"

    artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "vector_search",
        "query": query,
        "n_results": int(n_results),
        "embedding_provider": embedding_provider,
        "hits": hits,
    }
    path = save_json_artifact(artifact, "vector_search")
    dl.append(path)
    return df, status, dl, dl


def handle_vector_clear(downloads_list):
    """Drop all rows from the Chroma collection."""
    dl = list(downloads_list or [])
    if not VECTORSTORE_OK:
        return "vectorstore unavailable", dl, dl

    result = vectorstore.clear_collection()
    stats = vectorstore.collection_stats()
    status = f"**Cleared {result['cleared']} vectors.** Collection now has {stats['count']} rows."
    return status, dl, dl


def clear_vectorize_preview():
    return pd.DataFrame(), "Click 'Preview embeddings' to see sentence vectors."


# ----------------------------------------------------------------
# Main chat handler
# ----------------------------------------------------------------
# Only the two raw-SDK backends (Workflow, Simple Python Agent) respect
# the chosen LLM provider. Framework backends are pinned to Mistral
# because each framework wires its LLM differently and swapping them
# per-provider is a larger rewrite.
PROVIDER_AWARE_BACKENDS = {"Workflow", "Simple Python Agent"}


def process_message(user_message, mode, llm_provider, llm_key,

                    chat_history, loaded_context, downloads_list):
    dl = list(downloads_list or [])

    if not user_message or not user_message.strip():
        return chat_history, pd.DataFrame(), "", pd.DataFrame(), "", dl, dl, ""

    backend = BACKENDS.get(mode)
    if backend is None:
        return chat_history, pd.DataFrame(), "", pd.DataFrame(), \
               f"# Unknown backend: {mode}", dl, dl, ""

    # Framework backends always use Mistral; raw-SDK backends use chosen provider
    effective_provider = llm_provider if mode in PROVIDER_AWARE_BACKENDS else "Mistral"

    try:
        if mode in PROVIDER_AWARE_BACKENDS:
            client = backend.get_client(llm_key, provider=effective_provider)
        else:
            client = backend.get_client(llm_key)
    except Exception as e:
        err = f"# Could not create client for {effective_provider}: {e}"
        return chat_history, pd.DataFrame(), "", pd.DataFrame(), err, dl, dl, ""

    # ----------------------------------------------------------------
    # Dispatch: ringmaster-aware backend vs legacy backend
    # ----------------------------------------------------------------
    is_ringmaster = hasattr(backend, "run_ringmaster")

    if is_ringmaster:
        # Ringmaster receives the raw user message plus a context dict
        # holding session state. The supervisor calls check_data_status
        # as its first tool, so we must NOT prefix the message with the
        # loaded data the way legacy backends do.
        ringmaster_context = {
            "loaded_context": loaded_context or "",
            "llm_provider": effective_provider,
            "llm_key": llm_key or "",
            "cgt_result": None,
            "cta_result": None,
        }
        try:
            result = backend.run_ringmaster(client, user_message, ringmaster_context)
        except Exception as e:
            err_reply = f"(error from {mode} / {effective_provider}: {e})"
            new_history = (chat_history or []) + [
                {"role": "user", "content": user_message},
                {"role": "assistant", "content": err_reply},
            ]
            return new_history, pd.DataFrame(), "", pd.DataFrame(), "", dl, dl, ""
    else:
        # Legacy path: prefix loaded_context into the message text, call
        # backend.run(client, message) or backend.run(client, message, provider=...)
        if loaded_context:
            effective_message = (
                f"Available data:\n{loaded_context[:MAX_CONTEXT_CHARS]}\n\n"
                f"User question: {user_message}"
            )
        else:
            effective_message = user_message

        try:
            if mode in PROVIDER_AWARE_BACKENDS:
                result = backend.run(client, effective_message, provider=effective_provider)
            else:
                result = backend.run(client, effective_message)
        except Exception as e:
            err_reply = f"(error from {mode} / {effective_provider}: {e})"
            new_history = (chat_history or []) + [
                {"role": "user", "content": user_message},
                {"role": "assistant", "content": err_reply},
            ]
            return new_history, pd.DataFrame(), "", pd.DataFrame(), "", dl, dl, ""

    new_history = (chat_history or []) + [
        {"role": "user", "content": user_message},
        {"role": "assistant", "content": result["reply"]},
    ]

    steps_df, extracted_json, chart_df, code_snippet = build_outputs(
        user_message, mode, result
    )

    # For the artifact log, record what was actually sent to the backend.
    # Ringmaster receives the raw user_message; legacy backends may receive
    # the prefixed effective_message.
    logged_effective = effective_message if not is_ringmaster else user_message

    run_artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": f"chat_run_{mode.lower()}",
        "mode": mode,
        "llm_provider": effective_provider,
        "user_message": user_message,
        "effective_message": logged_effective,
        "reply": result["reply"],
        "steps": result["steps"],
        "extracted": result["extracted"],
    }
    run_path = save_json_artifact(run_artifact, f"run_{mode.lower()}")
    dl.append(run_path)

    return (
        new_history, steps_df, extracted_json, chart_df, code_snippet,
        dl, dl, "",
    )


# ----------------------------------------------------------------
# Form submission β€” saves a form JSON, then routes through process_message
# ----------------------------------------------------------------
def submit_form(task_type, operation, num_a, num_b, city, notes,

                mode, llm_provider, llm_key, chat_history, loaded_context, downloads_list):
    dl = list(downloads_list or [])

    form_artifact = {
        "timestamp": datetime.now().isoformat(),
        "source_type": "form_submission",
        "task_type": task_type,
        "operation": operation,
        "number_a": num_a,
        "number_b": num_b,
        "city": city,
        "notes": notes,
    }
    form_path = save_json_artifact(form_artifact, "form")
    dl.append(form_path)

    builders = {
        "Math": lambda: f"Calculate {num_a} {operation.lower()} {num_b}",
        "Weather": lambda: f"What is the weather in {city}?",
        "General": lambda: notes or "Hello",
    }
    user_message = builders[task_type]()
    return process_message(user_message, mode, llm_provider, llm_key,
                           chat_history, loaded_context, dl)


def clear_form():
    return "Math", "Add", 0, 0, "", ""


def new_chat(downloads_list):
    dl = list(downloads_list or [])
    return [], pd.DataFrame(), "", pd.DataFrame(), "", dl, dl, ""


# ============================================================================
# ZONE 4 β€” UI definition (gr.Blocks)
# ============================================================================
# Layout tree:
#   Row
#   +-- Column (sidebar): settings, mode, new chat, tab guide
#   +-- Column (main):
#       +-- Chatbot (display)
#       +-- Row: chat_input + send_btn
#       +-- Tabs (top-level)
#           +-- Data sources  (Tab)
#           |   +-- Tabs (inner)
#           |       +-- Web scraping
#           |       +-- PDF upload
#           |       +-- CSV / Excel upload
#           +-- Form          (Tab)
#           +-- Results       (Tab)
#           |   +-- Tabs (inner)
#           |       +-- Table
#           |       +-- Code
#           |       +-- Extracted
#           +-- Visuals       (Tab)
#           +-- Downloads     (Tab)
#
# TWO gr.State OBJECTS persist values across clicks:
#   loaded_context_state -> text from the last loaded data source
#   downloads_state      -> list of file paths, grows as artifacts are created
# ----------------------------------------------------------------
# UI
# ----------------------------------------------------------------
with gr.Blocks(
    theme=gr.themes.Soft(primary_hue="orange"),
    title="Agentic AI Systems for Large Scale Content Analysis",
    css="""

    #main_chatbot {

        border: 1px solid #e0e0e0;

        border-radius: 8px;

        padding: 4px;

    }

    #send_btn { min-height: 42px !important; max-height: 42px !important; height: 42px !important; }

    #chat_input textarea { min-height: 42px !important; max-height: 42px !important; }

    #desc_block p, #desc_block small { font-size: 0.78rem; line-height: 1.3; }

    #desc_block { margin-bottom: 2px; }

    #sidebar_block label { font-size: 0.78rem !important; }

    #sidebar_block .wrap { padding: 4px 6px !important; }

    #sidebar_block input { font-size: 0.78rem !important; padding: 4px !important; }

    .sidebar-label { font-size: 0.72rem; color: #666; margin: 2px 0 0 0; line-height: 1.2; }

    }

    .tab-nav button.selected,

    [role="tab"][aria-selected="true"] {

        background: #e8621a !important;

        color: white !important;

        border: 1px solid #e8621a !important;

    }

    """
) as demo:
    gr.Markdown("<h1 style=\"text-align:center; margin-bottom:2px;\">Agentic AI Systems for Large Scale Content Analysis</h1>")
    gr.Markdown("<p style=\"text-align:center; font-size:0.95rem; font-weight:600; margin:2px 0;\">Where Agentic AI Meets Qualitative Research β€” Thematic Analysis, Grounded Theory and Machine Learning</p>")
    gr.Markdown("<p style=\"text-align:center; font-size:0.85rem; font-weight:700; font-style:italic; color:#e8621a; border-top:2px solid #e8621a; border-bottom:2px solid #e8621a; padding:3px 0; margin:4px 0 6px 0;\">AI-First User Interface in the Age of Agents and Chatbots</p>")
    with gr.Row(elem_id="desc_block"):
        with gr.Column(scale=1):
            gr.Markdown(
                "<small>"
                "**Agent Progression** β€” Raw Python β†’ LangChain β†’ LangGraph Supervisor β†’ smolagents β†’ CrewAI Multi-Agent β†’ LlamaIndex  \n"
                "**Web Scraping at Scale** β€” Agentic URL scraper, PDF loader, spreadsheet loader, real-time web search  \n"
                "**Embedding-Based Supervised ML** β€” sentence embeddings β†’ text classifier β†’ accuracy evaluation β†’ prediction  \n"
                "**Embedding-Based Unsupervised ML** β€” sentence embeddings β†’ hierarchical clustering β†’ silhouette scoring β†’ LLM cluster labelling"
                "</small>"
            )
        with gr.Column(scale=1):
            gr.Markdown(
                "**πŸ”¬ Researcher Workbench**  \n"
                "**⚑ Agentic Computational Thematic Analysis** β€” 6-phase: familiarize β†’ code β†’ themes β†’ review β†’ define β†’ report  \n"
                "**⚑ Agentic Computational Grounded Theory** β€” pattern detection β†’ refinement β†’ confirmation  \n"
                "<span style=\"font-size:0.65rem; color:#888;\">"
                "Refs: Braun & Clarke (2006) QRP 3(2); Gauthier & Wallace (2022) PACMHCI 6(GROUP); "
                "Nelson (2020) SMR 49(1); Carlsen & Ralund (2022) BDS 9(1); Glaser & Strauss (1967)."
                "</span>"
            )
    loaded_context_state = gr.State("")
    downloads_state = gr.State([])
    trained_state = gr.State(None)
    # ------------------------------------------------------------------------
    # Per-workbench corpus states β€” methodological isolation (FT50 Priority 2a).
    # Each of the three workbenches owns its own corpus so a CSV loaded in one
    # does NOT appear in another. Replaces the former shared corpus state.
    # ------------------------------------------------------------------------
    bc_corpus_state = gr.State([])   # Braun & Clarke (reflexive TA) workbench corpus
    gw_corpus_state = gr.State([])   # Gauthier & Wallace (TA at scale) workbench corpus
    gw_approved_corpus_state = gr.State([])  # G&W Phase 1 output β€” feeds Phase 2-6
    cgt_corpus_state = gr.State([])  # Nelson + Carlsen & Ralund (grounded theory) corpus

    with gr.Row():

        # ---------------- Sidebar ----------------
        with gr.Column(scale=1, min_width=220):
            new_chat_btn = gr.Button("+ New chat", variant="primary")

            gr.Markdown("<span class=\"sidebar-label\">LLM β€” Mistral (locked)</span>")
            llm_provider_select = gr.Dropdown(
                choices=list(providers.LLM_PROVIDERS.keys()),
                value="Mistral",
                label="LLM provider",
                interactive=False,
                info="Locked to Mistral for this release.",
            )
            llm_key_input = gr.Textbox(
                label="LLM API key",
                type="password",
                placeholder="paste your Mistral API key",
            )
            gr.Markdown("<span class=\"sidebar-label\">Embedding β€” MiniLM 384-dim (locked)</span>")
            embedding_provider_select = gr.Dropdown(
                choices=list(providers.EMBEDDING_PROVIDERS.keys()),
                value="MiniLM (local)",
                label="Embedding provider",
                interactive=False,
                info="Locked to MiniLM (local) for this release.",
            )
            embedding_key_input = gr.Textbox(
                label="Embedding API key",
                type="password",
                placeholder="not needed for MiniLM (local)",
                interactive=False,
            )

            gr.Markdown("<span class=\"sidebar-label\">Agent Backend β€” Research Assistant + Vector Embeddings (locked)</span>")
            _mode_choices = list(BACKENDS.keys()) or ["(no backends loaded)"]
            # Prefer Research Assistant as the default if present
            if "Research Assistant enabled by Vector Embeddings" in _mode_choices:
                _mode_default = "Research Assistant enabled by Vector Embeddings"
            else:
                _mode_default = _mode_choices[0]
            mode_select = gr.Radio(
                choices=_mode_choices,
                value=_mode_default,
                label="Backend",
                interactive=False,
                info="Locked to Research Assistant for this release.",
            )

            gr.Markdown(
                "<span class=\"sidebar-label\">"
                "**Tabs:** Inputs (data, form) Β· Processing (Supervised ML, Unsupervised ML, Vector) Β· Outputs (Results, Visuals, Downloads) Β· Researcher Workbench"
                "</span>"
            )

        # ---------------- Main area ----------------
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(height=220, label="Conversation", elem_id="main_chatbot")

            with gr.Row():
                chat_input = gr.Textbox(
                    placeholder="Message the agent...",
                    show_label=False,
                    scale=5,
                    elem_id="chat_input",
                )
                send_btn = gr.Button("Send", scale=1, variant="primary", elem_id="send_btn")

            with gr.Tabs():

                # =================== INPUTS ===================
                # =================== INPUTS ===================
                with gr.Tab("Inputs"):
                    with gr.Tabs():
                        with gr.Tab("Data sources"):
                            gr.Markdown(
                                "Load external data as context. Each load is saved "
                                "as a timestamped JSON file in the Downloads tab."
                            )

                            with gr.Tabs():

                                with gr.Tab("Web scraping"):
                                    url_input = gr.Textbox(
                                        label="URL", placeholder="https://example.com",
                                    )
                                    with gr.Row():
                                        scrape_btn = gr.Button("Scrape", variant="primary")
                                        scrape_clear_btn = gr.Button("Clear")
                                    scrape_preview = gr.Textbox(
                                        label="Extracted text", lines=8, interactive=False,
                                    )
                                    scrape_status = gr.Markdown("Nothing loaded.")

                                with gr.Tab("PDF upload"):
                                    pdf_input = gr.File(
                                        label="Upload PDF", file_types=[".pdf"],
                                    )
                                    with gr.Row():
                                        pdf_extract_btn = gr.Button("Extract text", variant="primary")
                                        pdf_clear_btn = gr.Button("Clear")
                                    pdf_preview = gr.Textbox(
                                        label="Extracted text", lines=8, interactive=False,
                                    )
                                    pdf_status = gr.Markdown("Nothing loaded.")

                                with gr.Tab("CSV / Excel upload"):
                                    csv_input = gr.File(
                                        label="Upload CSV or Excel",
                                        file_types=[".csv", ".xlsx", ".xls"],
                                    )
                                    with gr.Row():
                                        csv_load_btn = gr.Button("Load", variant="primary")
                                        csv_clear_btn = gr.Button("Clear")
                                    csv_preview = gr.Dataframe(
                                        label="Preview (first 20 rows)", interactive=False,
                                    )
                                    csv_status = gr.Markdown("Nothing loaded.")

                                with gr.Tab("ML examples"):
                                    gr.Markdown(
                                        "Load the built-in catalog of labeled ML paper "
                                        "sentences as context. No upload needed β€” the "
                                        "dataset lives in examples.py."
                                    )
                                    with gr.Row():
                                        ml_load_btn = gr.Button("Load catalog", variant="primary")
                                        ml_clear_btn = gr.Button("Clear")
                                    ml_preview = gr.Textbox(
                                        label="Catalog preview", lines=10, interactive=False,
                                    )
                                    ml_status = gr.Markdown("Nothing loaded.")

                        with gr.Tab("Form"):
                            gr.Markdown(
                                "Fill structured fields and hit Submit. Generates a chat "
                                "message and saves the form fields as their own JSON file."
                            )
                            form_task = gr.Dropdown(
                                ["Math", "Weather", "General"],
                                value="Math", label="Task type",
                            )
                            form_op = gr.Dropdown(
                                ["Add", "Multiply"],
                                value="Add", label="Operation (Math only)",
                            )
                            with gr.Row():
                                form_a = gr.Number(label="Number A", value=0)
                                form_b = gr.Number(label="Number B", value=0)
                            form_city = gr.Textbox(
                                label="City (Weather only)", placeholder="e.g. Tokyo",
                            )
                            form_notes = gr.Textbox(
                                label="Notes (General only)", lines=2,
                            )
                            with gr.Row():
                                form_submit = gr.Button("Submit", variant="primary")
                                form_clear = gr.Button("Clear")

                        # =================== SUPERVISED MACHINE LEARNING ===================
                # =================== PROCESSING / ANALYSIS ===================
                with gr.Tab("Processing / Analysis"):
                    with gr.Tabs():
                        with gr.Tab("Supervised Machine Learning"):
                            gr.Markdown(
                                "**Supervised ML** on the built-in 100-sentence customer-feedback "
                                "dataset (6 labels). Uses semantic embeddings from "
                                "`sentence-transformers/all-MiniLM-L6-v2` + logistic regression. "
                                "No LLM involved."
                            )

                            with gr.Tabs():

                                with gr.Tab("Dataset"):
                                    gr.Markdown(
                                        "The 100 labeled sentences the classifier learns from. "
                                        "Six labels, roughly balanced: positive_review, "
                                        "negative_review, question, complaint, compliment, "
                                        "feature_request."
                                    )
                                    sup_label_filter = gr.Dropdown(
                                        choices=["(all)"] + list(sorted(
                                            {e["label"] for e in TRAINING_EXAMPLES}
                                        )),
                                        value="(all)",
                                        label="Filter by label",
                                    )
                                    sup_dataset_view = gr.Dataframe(
                                        value=pd.DataFrame(TRAINING_EXAMPLES),
                                        label=f"Training dataset ({len(TRAINING_EXAMPLES)} sentences)",
                                        interactive=False,
                                        wrap=True,
                                    )

                                with gr.Tab("Train"):
                                    gr.Markdown(
                                        "Click Train to fit a logistic regression classifier on "
                                        "semantic embeddings of 80 sentences (stratified split), "
                                        "then evaluate on the remaining 20."
                                    )
                                    with gr.Row():
                                        train_btn = gr.Button("Train classifier", variant="primary")
                                        train_clear_btn = gr.Button("Clear")
                                    train_status = gr.Markdown("Not trained yet.")
                                    confusion_out = gr.Dataframe(
                                        label="Confusion matrix (rows=actual, cols=predicted)",
                                        interactive=False,
                                        wrap=True,
                                    )

                                with gr.Tab("Predict"):
                                    gr.Markdown(
                                        "Type a new sentence to classify. The classifier must "
                                        "be trained first β€” go to the Train sub-tab and click "
                                        "Train classifier before using this panel."
                                    )
                                    predict_input = gr.Textbox(
                                        label="Sentence",
                                        placeholder="e.g. this product is amazing",
                                        lines=2,
                                    )
                                    predict_btn = gr.Button("Predict", variant="primary")
                                    predict_out = gr.Markdown("No prediction yet.")

                        # =================== UNSUPERVISED MACHINE LEARNING ===================
                        with gr.Tab("Unsupervised Machine Learning"):
                            gr.Markdown(
                                "**Unsupervised ML** on the same 100-sentence dataset with the "
                                "labels hidden from the algorithm. Uses semantic embeddings from "
                                "`sentence-transformers/all-MiniLM-L6-v2` + **Hierarchical "
                                "Agglomerative Clustering** with cosine distance."
                            )

                            with gr.Tabs():

                                with gr.Tab("Dataset"):
                                    gr.Markdown(
                                        "The 100 sentences the clustering algorithm sees. "
                                        "Labels are hidden here on purpose β€” unsupervised "
                                        "learning works without them. After clustering runs, "
                                        "the Cluster sub-tab compares discovered clusters to "
                                        "the true labels so you can see what the algorithm "
                                        "figured out on its own."
                                    )
                                    unsup_dataset_view = gr.Dataframe(
                                        value=pd.DataFrame(
                                            [{"sentence": e["sentence"]} for e in TRAINING_EXAMPLES]
                                        ),
                                        label=f"Sentences only ({len(TRAINING_EXAMPLES)} rows, no labels)",
                                        interactive=False,
                                        wrap=True,
                                    )

                                with gr.Tab("Cluster"):
                                    gr.Markdown(
                                        "**Hierarchical Agglomerative Clustering** on "
                                        "semantic embeddings. Clusters emerge from a "
                                        "similarity threshold instead of a fixed count. "
                                        "Small clusters become **noise**. Each surviving "
                                        "cluster exposes its **centroid** and the "
                                        "**N nearest-to-centroid** sentences as "
                                        "representatives β€” optionally sent to an LLM "
                                        "for an automatic cluster label."
                                    )
                                    cluster_sim = gr.Slider(
                                        0.40, 0.90, value=0.60, step=0.05,
                                        label="Similarity threshold",
                                        info="Minimum cosine similarity between vectors to merge.",
                                    )
                                    cluster_min = gr.Slider(
                                        2, 10, value=3, step=1,
                                        label="Minimum cluster size",
                                        info="Clusters smaller than this are reassigned to noise.",
                                    )
                                    cluster_nnear = gr.Slider(
                                        1, 10, value=3, step=1,
                                        label="N nearest-to-centroid",
                                        info="How many representative sentences to pick per cluster.",
                                    )
                                    cluster_llm_toggle = gr.Checkbox(
                                        label="Label clusters with LLM",
                                        value=False,
                                        info="Sends the N nearest sentences per cluster to the sidebar LLM provider for a short label. Adds ~2s per cluster.",
                                    )
                                    with gr.Row():
                                        cluster_btn = gr.Button("Cluster", variant="primary")
                                        cluster_clear_btn = gr.Button("Clear")
                                    cluster_status = gr.Markdown("Not clustered yet.")
                                    cluster_out = gr.Dataframe(
                                        label="Sentence-level cluster table",
                                        interactive=False,
                                        wrap=True,
                                    )

                        # =================== VECTOR PROCESSING ===================
                        with gr.Tab("Vector Processing"):
                            gr.Markdown(
                                "**Semantic vector storage and retrieval** using ChromaDB "
                                "as a persistent on-disk vector database.  \n"
                                "Same embedding model as Supervised / Unsupervised ML "
                                "(`sentence-transformers/all-MiniLM-L6-v2`), 384 dimensions, "
                                "cosine similarity. Every sentence is stored with its label "
                                "as metadata so retrieval results include ground-truth labels."
                            )

                            with gr.Tabs():

                                with gr.Tab("Vectorize"):
                                    gr.Markdown(
                                        "See what a sentence embedding actually looks like. "
                                        "Click Preview to compute embeddings for the first "
                                        "10 training sentences and show the first 8 dimensions "
                                        "of each 384-dim vector."
                                    )
                                    with gr.Row():
                                        vectorize_btn = gr.Button(
                                            "Preview embeddings", variant="primary",
                                        )
                                        vectorize_clear_btn = gr.Button("Clear")
                                    vectorize_status = gr.Markdown(
                                        "Click 'Preview embeddings' to see sentence vectors."
                                    )
                                    vectorize_out = gr.Dataframe(
                                        label="Sentences with embedding preview",
                                        interactive=False,
                                        wrap=True,
                                    )

                                with gr.Tab("Vector DB"):
                                    gr.Markdown(
                                        "**ChromaDB-backed persistent vector store.**  \n"
                                        "Step 1: Click 'Index all 100 sentences' once per "
                                        "session to embed the training data and write it to "
                                        "the local Chroma collection.  \n"
                                        "Step 2: Type a query and click 'Semantic search' to "
                                        "retrieve the nearest training sentences. The results "
                                        "show cosine similarity and the ground-truth label "
                                        "from the metadata."
                                    )

                                    gr.Markdown("### Index")
                                    with gr.Row():
                                        vector_index_btn = gr.Button(
                                            "Index all 100 sentences", variant="primary",
                                        )
                                        vector_clear_btn = gr.Button("Clear index")
                                    vector_index_status = gr.Markdown("Not indexed yet.")

                                    gr.Markdown("### Semantic search")
                                    vector_query = gr.Textbox(
                                        label="Query",
                                        placeholder="e.g. the app keeps crashing",
                                        lines=2,
                                    )
                                    vector_n = gr.Slider(
                                        1, 10, value=5, step=1,
                                        label="Number of results",
                                    )
                                    vector_search_btn = gr.Button(
                                        "Semantic search", variant="primary",
                                    )
                                    vector_search_status = gr.Markdown(
                                        "Enter a query and click 'Semantic search'."
                                    )
                                    vector_search_out = gr.Dataframe(
                                        label="Nearest neighbors (cosine similarity)",
                                        interactive=False,
                                        wrap=True,
                                    )

                        # =================== OUTPUTS ===================
                # =================== OUTPUTS ===================
                with gr.Tab("Outputs"):
                    with gr.Tabs():
                        with gr.Tab("Results"):
                            with gr.Tabs():
                                with gr.Tab("Table"):
                                    gr.Markdown("Step log for the most recent run.")
                                    table_out = gr.Dataframe(
                                        headers=["step", "type", "tool", "args", "result"],
                                        label="",
                                        wrap=True,
                                    )
                                with gr.Tab("Code"):
                                    gr.Markdown("Python snippets for the most recent run.")
                                    code_out = gr.Code(language="python", label="")
                                with gr.Tab("Extracted"):
                                    gr.Markdown("What the agent parsed from the most recent run.")
                                    extracted_out = gr.Code(language="json", label="")

                        with gr.Tab("Visuals"):
                            gr.Markdown("Tool-call counts for the most recent run.")
                            chart_out = gr.BarPlot(
                                x="tool", y="count",
                                title="", tooltip=["tool", "count"],
                                height=280,
                            )

                        with gr.Tab("Downloads"):
                            gr.Markdown(
                                "Every input and every run is saved here as a "
                                "timestamped JSON file. Files accumulate across the session."
                            )
                            downloads_files_out = gr.File(
                                label="All artifacts (timestamped JSON)",
                                file_count="multiple",
                                interactive=False,
                            )
                # ======================= RESEARCHER WORKBENCH (parent tab) =======================
                with gr.Tab("Researcher Workbench"):
                    gr.Markdown(
                        "**Researcher Workbench.** Each published research methodology is a "
                        "self-contained workbench β€” its own corpus state, its own phases, its "
                        "own prompts, its own contracts. Nothing is shared between workbenches. "
                        "Pick a methodology, upload your corpus, run the phases. New "
                        "methodologies are added as sibling workbenches as the research "
                        "programme expands."
                    )
                    with gr.Tabs():

                        # ==================== COMPUTATIONAL THEMATIC ANALYSIS ====================
                        with gr.Tab("Computational Grounded Theory"):
                            gr.Markdown(
                                "**Computational Grounded Theory** β€” methodology family based on "
                                "Glaser & Strauss (1967), operationalized computationally by Nelson (2020) "
                                "with Carlsen & Ralund (2022) insisting the researcher remains central."
                            )
                            with gr.Tabs():
                                with gr.Tab("Nelson + Carlsen & Ralund Workbench"):
                                    gr.Markdown(
                                        "## Computational Grounded Theory (3-step framework)\n"
                                        "*Nelson (2020). Computational grounded theory: A methodological framework. "
                                        "Sociological Methods & Research, 49(1), 3-42.*  \n"
                                        "*Carlsen & Ralund (2022). Computational grounded theory revisited: From computer-led to computer-assisted. "
                                        "Big Data & Society, 9(1) β€” critique implemented: researcher approves every step.*\n\n"
                                        "**Pipeline (co-pilot, researcher approves every step):** "
                                        "**Load corpus** β†’ Pattern Detection (unsupervised ML) β†’ Pattern Refinement (close reading) β†’ Pattern Confirmation (supervised ML)  \n"
                                        "Maps to traditional GT: open β†’ axial β†’ selective coding."
                                    )

                                    with gr.Accordion(
                                        "πŸ“Š Methodology reference: paper technique vs ours (click to expand β€” copy-ready for paper)",
                                        open=False,
                                    ):
                                        gr.Markdown(
                                            METHOD_COMPARISONS["cgt"].as_markdown(),
                                            elem_classes=["comparison-window"],
                                        )
                                        cgt_comparison_dl_btn = gr.Button(
                                            "⬇ Download methods comparison as .md (paste into paper)",
                                            variant="secondary",
                                        )
                                        cgt_comparison_dl_status = gr.Markdown("")

                                    gr.Markdown("---")
                                    gr.Markdown("### Step 1 β€” Load your corpus")
                                    cgt_load_test_btn = gr.Button(
                                        "Load built-in test_phase1.csv (30 sentences)",
                                        variant="secondary",
                                    )
                                    gr.Markdown("**β€” or β€”**")
                                    cgt_upload_csv = gr.UploadButton(
                                        label="πŸ“ Upload corpus CSV",
                                        file_types=[".csv"],
                                        file_count="single",
                                        variant="primary",
                                    )
                                    gr.Markdown(
                                        "*Required columns: `L1`, `L2`, `L3`, `L4`, `sentence_id`, `sentence`*"
                                    )
                                    cgt_load_status = gr.Markdown("**No corpus loaded.**")
                                    cgt_corpus_preview = gr.Dataframe(
                                        label="Loaded corpus preview",
                                        interactive=False,
                                        wrap=True,
                                    )

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Step 2 β€” LangGraph Supervisor (Pattern Detection)\n"
                                        "*Architectural demo of the 3-step framework. "
                                        "Pattern Detection is implemented; Refinement and Confirmation are placeholders pending full integration.*"
                                    )
                                    wb_cgt_msg = gr.Textbox(
                                        label="Request to the supervisor",
                                        value="Run computational grounded theory on the training data.",
                                        lines=2,
                                    )
                                    with gr.Row():
                                        wb_cgt_sim = gr.Slider(
                                            0.40, 0.90, value=0.60, step=0.05,
                                            label="Similarity threshold",
                                        )
                                        wb_cgt_min = gr.Slider(
                                            2, 10, value=3, step=1,
                                            label="Minimum cluster size",
                                        )
                                        wb_cgt_nnear = gr.Slider(
                                            1, 10, value=3, step=1,
                                            label="N nearest to centroid",
                                        )
                                    with gr.Row():
                                        wb_cgt_run = gr.Button("Run Workbench", variant="primary")
                                    wb_cgt_reply = gr.Markdown("Not run yet.")
                                    gr.Markdown("### Graph execution trace")
                                    wb_cgt_trace = gr.Dataframe(
                                        headers=["step", "node", "action", "detail"],
                                        label="Supervisor routing + node invocations",
                                        interactive=False,
                                        wrap=True,
                                    )
                                    gr.Markdown("### Pattern Detection output (Step 1)")
                                    wb_cgt_sentences = gr.Dataframe(
                                        label="Sentences with cluster id + LLM cluster label",
                                        interactive=False,
                                        wrap=True,
                                    )

                                    # ============================================
                                    # CGT Phase 2 β€” Pattern Refinement (Nelson 2020 Step 2)
                                    # ============================================
                                    gr.Markdown("---")
                                    with gr.Accordion(
                                        "Phase 2 β€” Pattern Refinement (Nelson 2020 Step 2) β€” close reading + verdict",
                                        open=False,
                                    ):
                                        gr.Markdown(
                                            "### Phase 2 β€” Pattern Refinement\n"
                                            "*Nelson (2020) Step 2: for each pattern from Phase 1, the tool "
                                            "surfaces exemplar sentences (top-N by centroid proximity) and drafts "
                                            "an interpretive memo. The researcher reads the exemplars, writes the "
                                            "final memo, and assigns a verdict: **keep / merge / split / drop / rename**. "
                                            "Per Carlsen & Ralund 2022, the researcher decides; the LLM drafts.*\n\n"
                                            "**Prerequisites:** Phase 1 Pattern Detection must have run (populating "
                                            "the table above). Reflexive positioning required (>=20 chars, contract-enforced)."
                                        )

                                        with gr.Row():
                                            cgt_p2_n_exemplars = gr.Slider(
                                                minimum=1, maximum=20, value=5, step=1,
                                                label="Exemplar sentences per pattern",
                                                info="Top-N closest to cluster centroid (higher = more context, slower LLM drafting)",
                                            )
                                        cgt_p2_reflexivity = gr.Textbox(
                                            label="Reflexive positioning (required, >=20 chars β€” C&R 2022 contract)",
                                            placeholder="Your position as analyst for CGT: who are you reading the patterns as? What stake?",
                                            lines=3,
                                        )

                                        cgt_p2_surface_btn = gr.Button(
                                            "Surface exemplars + draft LLM memos (Phase 2)",
                                            variant="primary",
                                        )
                                        cgt_p2_status = gr.Markdown(
                                            "*Click the button above after Phase 1 has run.*"
                                        )

                                        cgt_p2_refinement_table = gr.Dataframe(
                                            headers=[
                                                "pattern_id", "pattern_label", "n_sentences", "exemplars",
                                                "llm_memo_draft", "researcher_memo", "verdict", "new_label",
                                            ],
                                            label="Phase 2 Refinement Table β€” EDIT researcher_memo + verdict + new_label for each row",
                                            interactive=True,
                                            wrap=True,
                                        )
                                        gr.Markdown(
                                            "**Valid verdicts:** `keep`, `merge`, `split`, `drop`, `rename`. "
                                            "For `rename` or `split`, fill in the `new_label` column. "
                                            "**Every row must have a researcher_memo and a valid verdict before saving.**"
                                        )

                                        cgt_p2_save_btn = gr.Button(
                                            "Save Phase 2 refinement -> JSON artifact",
                                            variant="secondary",
                                        )
                                        cgt_p2_save_status = gr.Markdown("")
                        with gr.Tab("Computational Thematic Analysis"):
                            gr.Markdown(
                                "**Braun & Clarke 2006** β€” six-phase reflexive thematic analysis. "
                                "This workbench groups two complementary paths:  \n"
                                "- **Workbench** β€” the LangGraph supervisor approach (Phase 2 real, rest placeholders)  \n"
                                "- **Phase 1 β€” Familiarization** β€” active-reading dialogue via grounded "
                                "dialogue partners, followed by researcher confirmation of each initial noticing"
                            )
                            with gr.Tabs():
                                # ------------ Gauthier & Wallace at-scale path ------------
                                with gr.Tab("G&W at Scale"):
                                    gr.Markdown(
                                        "## Computational Thematic Analysis at Scale\n\n"
                                        "*Gauthier & Wallace (2022). The Computational Thematic Analysis Toolkit. "
                                        "Proc. ACM Hum.-Comput. Interact., 6(GROUP), Art. 25.*\n\n"
                                        "**Same 6 phases as Braun & Clarke β€” with Phase 0 Sampling (G&W 2022) prepended.**\n\n"
                                        "Designed for large-scale corpora (Apify scrapes, forums, 1000s of documents). "
                                        "MiniLM embeds all sentences, HDBSCAN clusters them, and representative "
                                        "sentences are selected for Phase 2 coding.\n\n"
                                        "**Pipeline:** **Load corpus** β†’ **P0 Compress** β†’ **P1 Familiarize** (on compressed corpus) β†’ P2 Code β†’ P3 Themes β†’ P4 Review β†’ P5 Define β†’ P6 Report"
                                    )

                                    with gr.Accordion(
                                        "πŸ“Š Methodology reference: paper technique vs ours (click to expand β€” copy-ready for paper)",
                                        open=False,
                                    ):
                                        gr.Markdown(
                                            METHOD_COMPARISONS["gw"].as_markdown(),
                                            elem_classes=["comparison-window"],
                                        )
                                        gw_comparison_dl_btn = gr.Button(
                                            "⬇ Download methods comparison as .md (paste into paper)",
                                            variant="secondary",
                                        )
                                        gw_comparison_dl_status = gr.Markdown("")

                                    gr.Markdown("---")
                                    gr.Markdown("### Step 1 β€” Load your corpus")
                                    gw_load_test_btn = gr.Button(
                                        "Load built-in test_phase1.csv (30 sentences)",
                                        variant="secondary",
                                    )
                                    gr.Markdown("**β€” or β€”**")
                                    gw_upload_csv = gr.UploadButton(
                                        label="πŸ“ Upload large corpus CSV (e.g. 1000 sentences)",
                                        file_types=[".csv"],
                                        file_count="single",
                                        variant="primary",
                                    )
                                    gr.Markdown(
                                        "*Required columns: `L1`, `L2`, `L3`, `L4`, `sentence_id`, `sentence`*"
                                    )
                                    gw_load_status = gr.Markdown("**No corpus loaded.**")
                                    gw_corpus_preview = gr.Dataframe(
                                        label="Loaded corpus preview",
                                        interactive=False,
                                        wrap=True,
                                    )

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Step 1.5 β€” Phase 0 Preparation (pre-sampling hygiene)\n"
                                        "*Four optional sub-steps for 1M-scale corpora. Each preserves the "
                                        "L1/L2/L3/L4/sentence_id/sentence schema and adds a `frequency_weight` "
                                        "column. Recommended order: noise β†’ length β†’ hash dedup β†’ semantic dedup. "
                                        "Each emits a reproducibility artifact.  \n\n"
                                        "**Literature:** Moreno-Ortiz & GarcΓ­a-GΓ‘mez (2023) *Corpus Pragmatics* 7:241–265 "
                                        "(31B-word Twitter corpus methodology); BERTopic_Teen (2025) PMC12378273 "
                                        "(hash + semantic dedup); Abbas et al. (2023) *SemDeDup* ICLR Workshop; "
                                        "Reimers & Gurevych (2019) EMNLP (MiniLM).*"
                                    )

                                    with gr.Row():
                                        p0prep_min_words = gr.Slider(
                                            minimum=1, maximum=10, value=3, step=1,
                                            label="Length filter β€” min words",
                                            info="Moreno-Ortiz 2023 p.7: default=3.",
                                        )
                                        p0prep_case_sensitive = gr.Checkbox(
                                            label="Hash dedup case-sensitive",
                                            value=False,
                                            info="Unchecked: 'Great!' and 'great!' merge. Default for reviews.",
                                        )
                                        p0prep_semantic_threshold = gr.Slider(
                                            minimum=0.90, maximum=0.99, value=0.97, step=0.01,
                                            label="Semantic dedup threshold (cosine)",
                                            info="0.97 default for reviews (SemDeDup). 0.95 tighter (more merging). 0.99 stricter.",
                                        )

                                    with gr.Row():
                                        p0prep_noise_btn = gr.Button(
                                            "β‘  Strip noise (URLs, emoji, Unicode)",
                                            variant="secondary",
                                        )
                                        p0prep_length_btn = gr.Button(
                                            "β‘‘ Apply length filter",
                                            variant="secondary",
                                        )
                                        p0prep_hash_btn = gr.Button(
                                            "β‘’ Hash deduplicate (exact)",
                                            variant="secondary",
                                        )
                                        p0prep_semantic_btn = gr.Button(
                                            "β‘£ Semantic deduplicate (MiniLM)",
                                            variant="secondary",
                                        )

                                    p0prep_status = gr.Markdown(
                                        "*No preparation step run yet. Click any button above to run that step "
                                        "on the currently loaded corpus. Each step updates the corpus state "
                                        "and writes an audit JSON artifact.*"
                                    )

                                    p0prep_table = gr.Dataframe(
                                        label="Preparation output β€” last step result",
                                        interactive=False,
                                        wrap=True,
                                    )

                                    gr.Markdown(
                                        "*`frequency_weight` counts how many original-corpus sentences this row "
                                        "represents after deduplication. Downstream prevalence (in Phase 6) is "
                                        "computed as weighted sum, so compression is honest to the full corpus. "
                                        "The final output of whichever preparation steps you run becomes the "
                                        "input to Phase 0 Sampling below.*"
                                    )

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Step 2 β€” Phase 0 Sampling (G&W 2022)\n"
                                        "*Reduce large corpus to representative sentences. "
                                        "MiniLM (Reimers & Gurevych 2019) embeds all sentences, "
                                        "HDBSCAN (Campello et al. 2013, 2015) clusters them, "
                                        "and representatives are selected by HDBSCAN cluster membership "
                                        "probability (density-tree score β€” the points most central to each "
                                        "cluster's density region, ranked descending). "
                                        "Phase 1 familiarization and Phase 2 coding run on the compressed corpus.*"
                                    )

                                    with gr.Row():
                                        gw_sentences_per_cluster = gr.Slider(
                                            minimum=1, maximum=5, value=2, step=1,
                                            label="Representatives per cluster",
                                            info="Top N sentences by HDBSCAN membership probability (descending). 1 = single heart-of-cluster sentence; 5 = more within-cluster variance.",
                                        )
                                        gw_min_cluster_size = gr.Slider(
                                            minimum=2, maximum=20, value=3, step=1,
                                            label="Minimum cluster size (HDBSCAN mclSize)",
                                            info="Campello et al. 2013: components with fewer sentences than this are disregarded as noise. Raise if cluster_fit values come out mostly low (forces tighter clusters).",
                                        )
                                        gw_outlier_sample = gr.Slider(
                                            minimum=0, maximum=50, value=10, step=5,
                                            label="Outlier sample size",
                                            info="How many noise-labeled sentences to retain (rare but potentially important views).",
                                        )
                                    with gr.Row():
                                        gw_min_cluster_fit = gr.Slider(
                                            minimum=0.0, maximum=0.5, value=0.1, step=0.05,
                                            label="Minimum cluster_fit threshold",
                                            info="Representatives with HDBSCAN membership probability below this are de-selected (reason='below_cluster_fit_threshold') but stay visible in the table so you can override. 0.0 = accept all picks; 0.1 = default; 0.3 = only confident reps; 0.5 = only deepest reps.",
                                        )

                                    gw_compress_btn = gr.Button(
                                        "Run Phase 0 β€” Sample corpus",
                                        variant="primary",
                                    )
                                    gw_compress_status = gr.Markdown("*No compression run yet.*")

                                    gr.Markdown(
                                        "### Sampling Table\n"
                                        "*Edit the `selected` column to manually include or exclude sentences. "
                                        "**The selected sentences flow into Phase 1 Familiarization below β€” "
                                        "you cannot skip Phase 1.** Phase 2 coding operates on Phase-1-approved "
                                        "sentences only.*"
                                    )
                                    gw_compress_table = gr.Dataframe(
                                        headers=[
                                            "idx", "L1", "L2", "L3", "L4", "sentence_id",
                                            "sentence",
                                            "cluster_id_original", "cluster_id_refined", "cluster_id",
                                            "cluster_fit", "cluster_mean_fit", "cluster_std_fit",
                                            "cluster_quality_tier", "split_decision",
                                            "cluster_size", "selected", "reason",
                                        ],
                                        label="Corpus compression β€” edit selected column",
                                        interactive=True,
                                        wrap=True,
                                    )
                                    gr.Markdown(
                                        "*`cluster_id_original`: HDBSCAN cluster assignment. "
                                        "`cluster_id_refined`: final cluster after any accepted Agglomerative split "
                                        "(original Γ— 1000 + sub_id for split clusters; same as original otherwise). "
                                        "`cluster_fit`: **1.0** = heart of cluster's density region, **0** = edge / near noise. "
                                        "`cluster_std_fit`: standard deviation of cluster_fit values within the refined cluster. "
                                        "`cluster_quality_tier`: **TIGHT** (std<0.15) / **MEDIUM** (0.15–0.20) / **LOOSE** (β‰₯0.20). "
                                        "LOOSE clusters are flagged for researcher review below.  \n\n"
                                        "**This table is Phase 0 Sampling's output β€” frozen.** Cluster labels live "
                                        "in the Cluster Label Review table further down (one row per refined cluster). "
                                        "Phase 1 and later stages join both artifacts on `cluster_id_refined`.*"
                                    )

                                    # --- Split Proposals review (LOOSE clusters only) ---
                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Split Proposals β€” Researcher Review (LOOSE clusters)\n"
                                        "*When a HDBSCAN cluster has internal std(cluster_fit) β‰₯ 0.20, "
                                        "the pipeline proposes an Agglomerative split (Ward 1963; cosine distance) "
                                        "to separate mixed-density sub-patterns. Review each proposal below and "
                                        "set `decision` to **ACCEPTED** or **REJECTED**, then click "
                                        "**Apply Split Decisions** to re-run Phase 0 with your choices. "
                                        "Leaving a row as `PENDING` is allowed but will trigger a soft-warn in the audit.*"
                                    )
                                    gw_split_proposals_table = gr.Dataframe(
                                        headers=[
                                            "cluster_id_original", "cluster_size", "std_before",
                                            "n_sub_proposed", "max_std_after", "improvement",
                                            "target_reached", "decision",
                                        ],
                                        label="Split proposals β€” edit the `decision` column",
                                        interactive=True,
                                        wrap=True,
                                    )
                                    gw_apply_splits_btn = gr.Button(
                                        "Apply Split Decisions & Re-sample",
                                        variant="secondary",
                                    )
                                    gr.Markdown(
                                        "*`std_before`: cluster's std(cluster_fit) before splitting. "
                                        "`max_std_after`: largest sub-cluster std if split accepted. "
                                        "`improvement`: std_before βˆ’ max_std_after (higher = cleaner split). "
                                        "`target_reached`: True if every proposed sub-cluster has std ≀ 0.15. "
                                        "`decision`: **ACCEPTED** = apply the split; **REJECTED** = keep the original cluster intact; "
                                        "**PENDING** = undecided (soft-warn allowed).*"
                                    )

                                    gw_compressed_corpus_state = gr.State([])

                                    # ============================================================
                                    # Cluster-level labeling workflow (2 iterations + commit)
                                    # Researcher-centric design: LLM proposes, researcher edits,
                                    # LLM refines (only flagged), researcher commits final labels.
                                    # Parallels the Phase 2 iter1/iter2/final pattern.
                                    # ============================================================
                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Cluster Label Review  \n"
                                        "*Four candidate labels per cluster (2 LLM + 2 researcher), followed by researcher's "
                                        "mandatory final choice. Iter 1 LLM is strict 2-word descriptive; Iter 2 LLM is "
                                        "interpretive 2-4 words. Researcher types into `researcher_edit_iter1` / "
                                        "`researcher_edit_iter2` wherever they want to refine. Finally, researcher types the "
                                        "authoritative label in `final_label` for every cluster β€” commit is blocked until all "
                                        "are filled. Temperature 0.0 pinned; every iteration's prompt + per-cluster audit "
                                        "logged. Final labels propagate to the Sampling Table above.*"
                                    )
                                    with gr.Row():
                                        gw_label_init_btn = gr.Button(
                                            "β‘  Initialize cluster table",
                                            variant="secondary",
                                        )
                                        gw_label_iter1_btn = gr.Button(
                                            "β‘‘ Run Iter 1 β€” LLM strict 2-word labels (all clusters)",
                                            variant="primary",
                                        )
                                        gw_label_iter2_btn = gr.Button(
                                            "β‘’ Run Iter 2 β€” LLM interpretive re-label (all clusters)",
                                            variant="primary",
                                        )
                                        gw_label_commit_btn = gr.Button(
                                            "β‘£ Commit final labels",
                                            variant="primary",
                                        )
                                    gw_label_status = gr.Markdown(
                                        "*Workflow: β‘  build cluster table β†’ β‘‘ iter 1 (strict 2-word on all) β†’ "
                                        "optionally edit `researcher_edit_iter1` β†’ β‘’ iter 2 (interpretive on all) β†’ "
                                        "optionally edit `researcher_edit_iter2` β†’ TYPE `final_label` for every cluster β†’ "
                                        "β‘£ commit (blocked if any final_label blank).*"
                                    )
                                    gw_cluster_labels_table = gr.Dataframe(
                                        headers=[
                                            "cluster_id", "cluster_size", "mean_cluster_fit",
                                            "top3_sentences_preview",
                                            "llm_label_iter1", "researcher_edit_iter1",
                                            "llm_label_iter2", "researcher_edit_iter2",
                                            "final_label",
                                        ],
                                        label="Cluster Label Review β€” one row per cluster",
                                        interactive=True,
                                        wrap=True,
                                    )
                                    gr.Markdown(
                                        "**4 candidate label columns + 1 mandatory choice.**  \n"
                                        "- `llm_label_iter1` β€” LLM strict 2-word draft (Button β‘‘)  \n"
                                        "- `researcher_edit_iter1` β€” your response to iter 1 (type here; blank = you accept iter 1)  \n"
                                        "- `llm_label_iter2` β€” LLM interpretive re-label, 2-4 words (Button β‘’, all clusters)  \n"
                                        "- `researcher_edit_iter2` β€” your response after seeing iter 2 (type here; blank = OK)  \n"
                                        "- `final_label` β€” **MANDATORY**. Type (or copy-paste) the winning label for every cluster.  \n\n"
                                        "Commit is **blocked** until every cluster has a non-blank `final_label`. "
                                        "This enforces active researcher choice per Braun & Clarke (2006) β€” themes are "
                                        "*actively developed* by the researcher, not auto-filled. "
                                        "Every iteration's artifact JSON contains the exact prompt + top-3 sentences + "
                                        "model name for reproducibility."
                                    )

                                    # ============================================================
                                    # Phase 1 β€” Familiarization (G&W path, on compressed corpus)
                                    # ============================================================
                                    gr.Markdown("---")
                                    with gr.Accordion(
                                        "Phase 1 β€” Familiarization (on compressed corpus)",
                                        open=False,
                                    ):
                                        gr.Markdown(
                                            "### Phase 1 β€” Familiarization\n"
                                            "*Braun & Clarke (2006) Phase 1 applied to the Phase 0 sampled corpus. "
                                            "Read the representative sentences, write reflexive positioning, "
                                            "and confirm initial noticings. This feeds Phase 2 coding.*"
                                        )
                                        gr.Markdown("#### Step 1 β€” Familiarization (facilitator)")
                                        gw_p1_facilitator_memo = gr.Textbox(
                                            label="Familiarization notes",
                                            placeholder="What do you notice in the representative sentences? Patterns, tensions, surprises?",
                                            lines=5,
                                        )
                                        gw_p1_facilitator_transcript = gr.Textbox(
                                            label="Active reading transcript",
                                            placeholder="Your dialogue with the facilitator AI, or your own notes.",
                                            lines=4,
                                        )
                                        gw_p1_facilitator_citations = gr.Textbox(
                                            label="Source evidence (quotes + L1/sentence_id)",
                                            placeholder="e.g., DOC_0002 Extract 7: 'I kept waiting for the other shoe to drop...'",
                                            lines=4,
                                        )

                                        gr.Markdown("#### Step 2 β€” Reflexive companion")
                                        gw_p1_companion_challenges = gr.Textbox(
                                            label="Reflexive challenges",
                                            placeholder="What assumptions are you bringing? What perspectives might you miss?",
                                            lines=3,
                                        )
                                        gw_p1_companion_reflexivity = gr.Textbox(
                                            label="Reflexive positioning (required, min 20 chars β€” contract enforced)",
                                            placeholder="Your position as analyst: who are you reading this as? What's your stake?",
                                            lines=3,
                                        )
                                        gw_p1_companion_breadth = gr.Textbox(
                                            label="Dataset immersion coverage",
                                            placeholder="How did you ensure breadth of engagement across the compressed corpus?",
                                            lines=2,
                                        )

                                        gr.Markdown("#### Step 3 β€” Researcher confirmation")
                                        gw_p1_validation_table = gr.Dataframe(
                                            headers=["noticing", "source_evidence", "researcher_confirmed"],
                                            label="Confirm each initial noticing before proceeding to Phase 2",
                                            interactive=True,
                                            wrap=True,
                                        )
                                        gw_p1_save_btn = gr.Button(
                                            "Save Phase 1 output -> JSON artifact",
                                            variant="primary",
                                        )
                                        gw_p1_save_status = gr.Markdown("")

                                    gr.Markdown("---")

                                    # ============================================================
                                    # G&W Phase 2 β€” Generating Initial Codes (Braun & Clarke p.88)
                                    # ============================================================
                                    with gr.Accordion("Phase 2 β€” Generating Initial Codes", open=False):
                                        gr.Markdown(
                                            "## Phase 2 β€” Generating Initial Codes\n\n"
                                            "*Braun & Clarke 2006, Phase 2: \"Coding interesting features of "
                                            "the data in a systematic fashion across the entire data set\" (p. 88).*\n\n"
                                            "Operates on the **Phase-1-approved sentences** from the G&W sampled "
                                            "+ familiarized corpus. Iterative refinement: iteration 1 β†’ researcher "
                                            "edits β†’ iteration 2 (reads edits) β†’ iteration 3 (convergence). "
                                            "Runtime depends on sentence count."
                                        )

                                        gr.Markdown("### Corpus β€” inherited from G&W Phase 1")
                                        gr.Markdown(
                                            "*Phase 2 reads the Phase-1-approved corpus (selected=true sentences "
                                            "from the Sampling Table, filtered by your edits in Phase 1). "
                                            "If Phase 1 hasn't been saved, this phase falls back to the raw corpus.*"
                                        )
                                        gw_p2_corpus_status = gr.Markdown(
                                            "*Save Phase 1 first to populate the approved corpus for Phase 2.*"
                                        )
                                        gw_p2_refresh_btn = gr.Button(
                                            "Refresh corpus status from G&W Phase 1",
                                            variant="secondary",
                                        )

                                        gr.Markdown("---")
                                        gr.Markdown("### Phase 1 context (consumed by the agent)")
                                        gr.Markdown(
                                            "*The Phase 2 agent reads the researcher's reflexive "
                                            "positioning and confirmed initial noticings from G&W Phase 1 "
                                            "as context. This ensures Phase 2 coding is grounded in the "
                                            "researcher's familiarization of the compressed corpus.*"
                                        )
                                        gw_p2_phase1_summary = gr.Markdown(
                                            "*Phase 1 output will appear here after Save Phase 1.*"
                                        )

                                        gr.Markdown("---")
                                        gr.Markdown("### Coding orientation (Braun & Clarke p. 84)")
                                        gr.Markdown(
                                            "*SEMANTIC vs LATENT is an analysis-wide choice. "
                                            "Choose ONE orientation for this whole G&W analysis.*  \n\n"
                                            "**Semantic** β€” surface content, what the text explicitly says  \n"
                                            "**Latent** β€” underlying assumptions, what the text implies"
                                        )
                                        gw_p2_orientation = gr.Radio(
                                            choices=["semantic", "latent"],
                                            value="semantic",
                                            label="Coding orientation for this G&W analysis",
                                            interactive=True,
                                        )

                                        gr.Markdown("---")
                                        gr.Markdown("### Agentic coding iterations")
                                        gr.Markdown(
                                            "Iteration 1 β†’ review AI codes β†’ edit `human_code_iterN` β†’ "
                                            "iteration 2 (agent reads your edits) β†’ review β†’ iteration 3 β†’ converge."
                                        )
                                        with gr.Row():
                                            gw_p2_run_iter1_btn = gr.Button(
                                                "Run iteration 1", variant="primary",
                                            )
                                            gw_p2_run_iter2_btn = gr.Button(
                                                "Run iteration 2 (reads your edits)", variant="primary",
                                            )
                                            gw_p2_run_iter3_btn = gr.Button(
                                                "Run iteration 3 (final)", variant="primary",
                                            )
                                        gw_p2_iter_status = gr.Markdown("*No iterations run yet.*")

                                        gr.Markdown("---")
                                        gr.Markdown("### Initial Codes Table (G&W)")
                                        gw_p2_codes_table = gr.Dataframe(
                                            headers=[
                                                "L1", "L2", "L3", "L4", "sentence_id", "sentence",
                                                "ai_code_iter1", "human_code_iter1",
                                                "ai_code_iter2", "human_code_iter2",
                                                "ai_code_iter3", "human_code_iter3",
                                                "final_code", "flagged",
                                            ],
                                            label="G&W Phase 2 Initial Codes β€” edit human_code_iterN columns",
                                            interactive=True,
                                            wrap=True,
                                        )

                                        gr.Markdown("---")
                                        gr.Markdown("### Codebook (G&W)")
                                        gw_p2_codebook_table = gr.Dataframe(
                                            headers=[
                                                "code_name", "definition", "created_by",
                                                "provenance", "sentence_count",
                                            ],
                                            label="G&W Phase 2 Codebook β€” edit definitions",
                                            interactive=True,
                                            wrap=True,
                                        )

                                        gr.Markdown("---")
                                        gw_p2_save_btn = gr.Button(
                                            "Save G&W Phase 2 Final Codes + Codebook β†’ JSON artifact",
                                            variant="primary",
                                        )
                                        gw_p2_save_status = gr.Markdown("")

                                    # ============================================================
                                    # G&W Phase 3 β€” Searching for Themes
                                    # ============================================================
                                    with gr.Accordion("Phase 3 β€” Searching for Themes", open=False):
                                        gr.Markdown(
                                            "## Phase 3 β€” Searching for Themes\n\n"
                                            "*Braun & Clarke 2006, Phase 3: \"Collating codes into potential "
                                            "themes, gathering all data relevant to each potential theme\" (p. 89).*\n\n"
                                            "Clusters the G&W Phase 2 codebook codes by semantic similarity "
                                            "(sentence-transformers embeddings + agglomerative clustering), "
                                            "then proposes a candidate theme name and description for each "
                                            "cluster via one Mistral call per cluster."
                                        )

                                        gr.Markdown("### Clustering parameters (researcher-controlled)")
                                        with gr.Row():
                                            gw_p3_similarity = gr.Slider(
                                                minimum=0.3, maximum=0.95, value=0.60, step=0.05,
                                                label="Similarity threshold",
                                                info="Codes more similar than this cluster together. Default 0.60.",
                                            )
                                            gw_p3_min_size = gr.Slider(
                                                minimum=2, maximum=10, value=2, step=1,
                                                label="Minimum cluster size",
                                                info="Clusters smaller than this go into noise bucket. Default 2.",
                                            )
                                        gw_p3_run_btn = gr.Button(
                                            "Run G&W Phase 3 β€” Cluster codes into candidate themes",
                                            variant="primary",
                                        )
                                        gw_p3_status = gr.Markdown("*No themes generated yet. Run G&W Phase 2 first.*")

                                        gr.Markdown("---")
                                        gr.Markdown("### Candidate Themes Table (G&W)")
                                        gw_p3_themes_table = gr.Dataframe(
                                            headers=[
                                                "theme_id", "candidate_theme_name", "description",
                                                "rationale", "member_codes", "code_count",
                                                "researcher_theme_name", "researcher_notes",
                                            ],
                                            label="G&W Phase 3 Candidate Themes β€” edit researcher_theme_name / researcher_notes",
                                            interactive=True,
                                            wrap=True,
                                        )

                                        gr.Markdown("---")
                                        gr.Markdown("### Noise Codes (G&W)")
                                        gw_p3_noise_table = gr.Dataframe(
                                            headers=["code_name", "definition"],
                                            label="G&W noise codes (did not cluster)",
                                            interactive=False,
                                            wrap=True,
                                        )

                                        gr.Markdown("---")
                                        gw_p3_save_btn = gr.Button(
                                            "Save G&W Phase 3 output (themes + noise β†’ JSON artifact)",
                                            variant="secondary",
                                        )
                                        gw_p3_save_status = gr.Markdown("")

                                    # ============================================================
                                    # G&W Phase 4 β€” Reviewing Themes
                                    # ============================================================
                                    with gr.Accordion("Phase 4 β€” Reviewing Themes", open=False):
                                        gr.Markdown(
                                            "## Phase 4 β€” Reviewing Themes\n\n"
                                            "*Braun & Clarke 2006 p. 91: \"Reviewing, refining and sometimes "
                                            "reducing your themes.\"*\n\n"
                                            "**Level 1** β€” within-theme coherence. **Level 2** β€” between-theme "
                                            "distinctness. LLM suggests verdict; researcher edits "
                                            "`researcher_verdict` and `researcher_action_notes`."
                                        )

                                        gw_p4_run_btn = gr.Button(
                                            "Run G&W Phase 4 β€” Review all themes (cohesion + LLM verdict)",
                                            variant="primary",
                                        )
                                        gw_p4_status = gr.Markdown("*No review run yet. Run G&W Phase 3 first.*")

                                        gr.Markdown("---")
                                        gr.Markdown("### Theme Review Table (G&W)")
                                        gw_p4_review_table = gr.Dataframe(
                                            headers=[
                                                "theme_id", "theme_name", "member_codes", "code_count",
                                                "member_sentence_count", "within_cohesion",
                                                "llm_verdict", "llm_reasoning", "llm_action_suggestion",
                                                "researcher_verdict", "researcher_action_notes",
                                            ],
                                            label="G&W Phase 4 Theme Review β€” edit researcher_verdict / researcher_action_notes",
                                            interactive=True,
                                            wrap=True,
                                        )

                                        gr.Markdown("---")
                                        gw_p4_save_btn = gr.Button(
                                            "Save G&W Phase 4 verdicts β†’ JSON artifact",
                                            variant="secondary",
                                        )
                                        gw_p4_save_status = gr.Markdown("")

                                    # ============================================================
                                    # G&W Phase 5 β€” Defining and Naming Themes
                                    # ============================================================
                                    with gr.Accordion("Phase 5 β€” Defining and Naming Themes", open=False):
                                        gr.Markdown(
                                            "## Phase 5 β€” Defining and Naming Themes\n\n"
                                            "*Braun & Clarke 2006 p. 92: refine specifics of each theme, "
                                            "produce definitions and names.*\n\n"
                                            "Takes surviving themes from G&W Phase 4 (verdict = keep or merge) "
                                            "and produces final name, definition, scope, narrative contribution. "
                                            "Edit `researcher_final_name` / `researcher_definition` to override."
                                        )

                                        gw_p5_run_btn = gr.Button(
                                            "Run G&W Phase 5 β€” Define and name surviving themes",
                                            variant="primary",
                                        )
                                        gw_p5_status = gr.Markdown("*No definitions yet. Run G&W Phase 4 first.*")

                                        gr.Markdown("---")
                                        gr.Markdown("### Theme Definitions Table (G&W)")
                                        gw_p5_def_table = gr.Dataframe(
                                            headers=[
                                                "theme_id", "original_name", "final_name",
                                                "definition", "scope_note",
                                                "narrative_contribution", "member_codes",
                                                "code_count", "researcher_final_name",
                                                "researcher_definition",
                                            ],
                                            label="G&W Phase 5 Definitions β€” edit researcher_final_name / researcher_definition",
                                            interactive=True,
                                            wrap=True,
                                        )

                                        gr.Markdown("---")
                                        gw_p5_save_btn = gr.Button(
                                            "Save G&W Phase 5 definitions β†’ JSON artifact",
                                            variant="secondary",
                                        )
                                        gw_p5_save_status = gr.Markdown("")

                                    # ============================================================
                                    # G&W Phase 6 β€” Producing the Report
                                    # ============================================================
                                    with gr.Accordion("Phase 6 β€” Producing the Report", open=False):
                                        gr.Markdown(
                                            "## Phase 6 β€” Producing the Report\n\n"
                                            "*Braun & Clarke 2006 p. 93: \"tell the complicated story of your data.\"*\n\n"
                                            "Generates a complete analytic report from G&W Phase 5 theme definitions. "
                                            "AI drafts, researcher refines."
                                        )

                                        gw_p6_research_question = gr.Textbox(
                                            label="Research question / focus (optional)",
                                            placeholder="e.g. How do employees experience organisational change?",
                                            lines=2,
                                        )

                                        gw_p6_run_btn = gr.Button(
                                            "Run G&W Phase 6 β€” Generate analytic report",
                                            variant="primary",
                                        )
                                        gw_p6_status = gr.Markdown("*No report yet. Run G&W Phase 5 first.*")

                                        gr.Markdown("---")
                                        gr.Markdown("### Analytic Report (G&W)")
                                        gw_p6_report_text = gr.Textbox(
                                            label="G&W Phase 6 Analytic Report (editable)",
                                            lines=30,
                                            placeholder="Report will appear here after running G&W Phase 6...",
                                            interactive=True,
                                        )

                                        gr.Markdown("---")
                                        gw_p6_save_btn = gr.Button(
                                            "Save G&W report β†’ JSON + Markdown artifacts",
                                            variant="secondary",
                                        )
                                        gw_p6_save_status = gr.Markdown("")

                                # ------------ Existing Workbench path ------------
                                with gr.Tab("B&C Workbench"):
                                    gr.Markdown(
                                        "## Reflexive Thematic Analysis (6-phase)\n"
                                        "*Braun & Clarke (2006). Using thematic analysis in psychology. "
                                        "Qualitative Research in Psychology, 3(2), 77-101.*\n\n"
                                        "**Pipeline (co-pilot, researcher approves every step):** "
                                        "**Load corpus** β†’ P1 Familiarize β†’ P2 Code β†’ P3 Themes β†’ P4 Review β†’ P5 Define β†’ P6 Report"
                                    )

                                    with gr.Accordion(
                                        "πŸ“Š Methodology reference: paper technique vs ours (click to expand β€” copy-ready for paper)",
                                        open=False,
                                    ):
                                        gr.Markdown(
                                            METHOD_COMPARISONS["bc"].as_markdown(),
                                            elem_classes=["comparison-window"],
                                        )
                                        bc_comparison_dl_btn = gr.Button(
                                            "⬇ Download methods comparison as .md (paste into paper)",
                                            variant="secondary",
                                        )
                                        bc_comparison_dl_status = gr.Markdown("")

                                    gr.Markdown("---")
                                    gr.Markdown("### Step 1 β€” Load your corpus")
                                    bc_load_test_btn = gr.Button(
                                        "Load built-in test_phase1.csv (30 sentences)",
                                        variant="secondary",
                                    )
                                    gr.Markdown("**β€” or β€”**")
                                    bc_upload_csv = gr.UploadButton(
                                        label="πŸ“ Upload corpus CSV",
                                        file_types=[".csv"],
                                        file_count="single",
                                        variant="primary",
                                    )
                                    gr.Markdown(
                                        "*Required columns: `L1`, `L2`, `L3`, `L4`, `sentence_id`, `sentence`*"
                                    )
                                    bc_load_status = gr.Markdown("**No corpus loaded.**")
                                    bc_corpus_preview = gr.Dataframe(
                                        label="Loaded corpus preview",
                                        interactive=False,
                                        wrap=True,
                                    )

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Step 2 β€” Open each Phase accordion below (in order)\n"
                                        "*Scroll down. Six accordions: Phase 1 β†’ Phase 2 β†’ Phase 3 β†’ Phase 4 β†’ Phase 5 β†’ Phase 6. "
                                        "Click any Phase header to expand it. Each phase has its own Run and Save buttons. "
                                        "Nothing auto-runs β€” you approve every step.*"
                                    )

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### LangGraph Supervisor Demo (optional)\n"
                                        "*Architectural demo showing how a LangGraph supervisor routes between "
                                        "six phase-nodes automatically. This is NOT the co-pilot research pipeline "
                                        "β€” use the Phase accordions below for actual analysis.*"
                                    )
                                    wb_cta_msg = gr.Textbox(
                                        label="Request to the supervisor",
                                        value="Run reflexive thematic analysis on the training data.",
                                        lines=2,
                                    )
                                    wb_cta_max = gr.Slider(
                                        5, 100, value=20, step=5,
                                        label="Max sentences to code",
                                        info="One LLM call per sentence in Phase 2. "
                                             "Default 20 keeps runtime under ~40 seconds.",
                                    )
                                    wb_cta_run = gr.Button("Run Workbench", variant="primary")
                                    wb_cta_reply = gr.Markdown("Not run yet.")
                                    gr.Markdown("### Graph execution trace")
                                    wb_cta_trace = gr.Dataframe(
                                        headers=["step", "node", "action", "detail"],
                                        label="Supervisor routing + node invocations",
                                        interactive=False,
                                        wrap=True,
                                    )
                                    gr.Markdown("### Phase 2 output β€” Initial Codes")
                                    wb_cta_codes = gr.Dataframe(
                                        label="Sentences with LLM-generated codes",
                                        interactive=False,
                                        wrap=True,
                                    )

                                # ------------ NEW: Phase 1 β€” Familiarization path ------------
                                with gr.Accordion("Phase 1 β€” Familiarizing Yourself With Your Data", open=False):
                                    gr.Markdown(
                                        "## Phase 1 β€” Familiarizing Yourself With Your Data\n\n"
                                        "*Braun & Clarke 2006, Phase 1: \"immerse yourself in the data "
                                        "to the extent that you are familiar with the depth and breadth "
                                        "of the content\"* (p. 87).\n\n"
                                        "This workbench implements Phase 1 through a three-step "
                                        "active-reading protocol. Two complementary dialogue partners "
                                        "(implemented as Gemini Gems backed by NotebookLM) guide the "
                                        "researcher through immersion and reflexive engagement, "
                                        "followed by researcher confirmation of every initial noticing "
                                        "against its source evidence.\n\n"
                                        "**Step 1 β€” Familiarization Facilitator** β€” an active-reading "
                                        "dialogue partner that asks grounded questions, surfaces "
                                        "patterns, and prompts the researcher to articulate initial "
                                        "noticings. Every response is anchored in direct quotation "
                                        "from the source corpus.  \n"
                                        "**Step 2 β€” Reflexive Companion** β€” a critical dialogue partner "
                                        "that challenges the researcher's initial noticings, probes "
                                        "reflexive positioning, and verifies dataset immersion "
                                        "coverage across all sources.  \n"
                                        "**Step 3 β€” Researcher Confirmation** β€” the researcher reviews "
                                        "each initial noticing against its source sentence and "
                                        "confirms, refines, or rejects it. This forces active "
                                        "engagement with the evidence and is the researcher's own "
                                        "analytic act β€” not the dialogue partner's.\n\n"
                                        "**Braun & Clarke 2006 compliance target:** β‰₯90% when both "
                                        "dialogue partners are engaged with iteration. Unclosable "
                                        "gaps documented in COMPLIANCE.md: felt sense of the data "
                                        "(phenomenological, unautomatable), and time-on-task "
                                        "verification (researcher's own responsibility)."
                                    )

                                    # ---- Corpus loader ----
                                    gr.Markdown("### Corpus β€” Canonical CSV")
                                    gr.Markdown(
                                        "*Phase 1 consumes a canonical CSV with five columns: "
                                        "`L1`, `L2`, `L3`, `L4`, `sentence_id`, `sentence`. "
                                        "Inputs tab transformers (PDF→CSV, web scrape→CSV) will "
                                        "produce this schema in a future round. For pipeline testing, "
                                        "load the built-in test corpus.*"
                                    )
                                    with gr.Row():
                                        bc_p1_load_test_btn = gr.Button(
                                            "Load built-in test_phase1.csv (30 sentences)",
                                            variant="secondary",
                                            scale=1,
                                        )
                                    gr.Markdown("### Upload your own CSV (canonical schema)")
                                    bc_p1_upload_csv = gr.UploadButton(
                                        label="πŸ“ Click to upload canonical CSV",
                                        file_types=[".csv"],
                                        file_count="single",
                                        variant="primary",
                                    )
                                    gr.Markdown(
                                        "*Required columns: `L1`, `L2`, `L3`, `L4`, `sentence_id`, `sentence`*"
                                    )
                                    bc_p1_corpus_status = gr.Markdown("**No corpus loaded.**")
                                    bc_p1_corpus_preview = gr.Dataframe(
                                        label="Corpus preview",
                                        interactive=False,
                                        wrap=True,
                                    )

                                    # ---- Step 1 β€” Familiarization Facilitator ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Step 1 β€” Familiarization Facilitator")
                                    gr.Markdown(
                                        "An active-reading dialogue partner grounded in your "
                                        "corpus via NotebookLM. Copy the instructions below, "
                                        "create a Gem in Gemini with your NotebookLM notebook "
                                        "attached under Knowledge, engage in the active-reading "
                                        "dialogue, then paste your outputs here."
                                    )
                                    bc_p1_facilitator_instructions = gr.Textbox(
                                        label="Familiarization Facilitator instructions (paste into Gemini Gem)",
                                        value="(instructions will be drafted in next round)",
                                        lines=8,
                                        max_lines=20,
                                    )
                                    bc_p1_facilitator_memo = gr.Textbox(
                                        label="Paste: Familiarization notes (Braun & Clarke 2006, Phase 1 output)",
                                        lines=4,
                                    )
                                    bc_p1_facilitator_transcript = gr.Textbox(
                                        label="Paste: Full active-reading dialogue transcript",
                                        lines=6,
                                    )
                                    bc_p1_facilitator_citations = gr.Textbox(
                                        label="Paste: Source evidence β€” quoted sentences anchoring each initial noticing",
                                        lines=4,
                                        info="One citation per line. Format: L1 | L2 | sentence",
                                    )

                                    # ---- Step 2 β€” Reflexive Companion ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Step 2 β€” Reflexive Companion")
                                    gr.Markdown(
                                        "A critical dialogue partner that challenges your initial "
                                        "noticings, probes your reflexive positioning, and verifies "
                                        "immersion coverage across all sources. Run this after the "
                                        "Facilitator dialogue is complete."
                                    )
                                    bc_p1_companion_instructions = gr.Textbox(
                                        label="Reflexive Companion instructions (paste into Gemini Gem)",
                                        value="(instructions will be drafted in next round)",
                                        lines=8,
                                        max_lines=20,
                                    )
                                    bc_p1_companion_challenges = gr.Textbox(
                                        label="Paste: Reflexive challenges raised by Companion",
                                        lines=4,
                                    )
                                    bc_p1_companion_reflexivity = gr.Textbox(
                                        label="Paste: Reflexive positioning statement",
                                        lines=4,
                                        info="Your position as researcher β€” assumptions, theoretical lens, relationship to the data.",
                                    )
                                    bc_p1_companion_breadth = gr.Textbox(
                                        label="Paste: Dataset immersion coverage notes",
                                        lines=3,
                                        info="Which sources and sections were engaged with, which remain unread.",
                                    )

                                    # ---- Step 3 β€” Researcher Confirmation ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Step 3 β€” Researcher Confirmation")
                                    gr.Markdown(
                                        "Review each initial noticing against its source sentence. "
                                        "Confirm, refine, or reject each one. This is the researcher's "
                                        "own analytic act β€” not the dialogue partner's. Braun & Clarke "
                                        "2019/2021 insist that reflexive thematic analysis is *constructed* "
                                        "by the researcher's engagement with the data, not *extracted* by a tool."
                                    )
                                    bc_p1_build_table_btn = gr.Button(
                                        "Build confirmation table from Steps 1 + 2",
                                        variant="secondary",
                                    )
                                    bc_p1_validation_table = gr.Dataframe(
                                        headers=[
                                            "L1", "L2", "L3", "L4", "sentence_id",
                                            "sentence", "initial_noticing",
                                            "reflexive_challenge", "researcher_confirmation",
                                            "refined_noticing",
                                        ],
                                        label="Phase 1 Researcher Confirmation Table β€” edit the last 4 columns",
                                        interactive=True,
                                        wrap=True,
                                    )

                                    # ---- Save ----
                                    gr.Markdown("---")
                                    bc_p1_save_btn = gr.Button(
                                        "Save Phase 1 output (all 3 steps β†’ JSON artifact)",
                                        variant="primary",
                                    )
                                    bc_p1_save_status = gr.Markdown("")

                                # ------------ Phase 2 β€” Initial Coding ------------
                                with gr.Accordion("Phase 2 β€” Generating Initial Codes", open=False):
                                    gr.Markdown(
                                        "## Phase 2 β€” Generating Initial Codes\n\n"
                                        "*Braun & Clarke 2006, Phase 2: \"Coding interesting features "
                                        "of the data in a systematic fashion across the entire data "
                                        "set, collating data relevant to each code\"* (p. 87).\n\n"
                                        "This workbench implements Phase 2 through a **fully agentic "
                                        "LangGraph architecture**. The agent loops systematically "
                                        "across every sentence, generates both semantic and latent "
                                        "codes, maintains a growing codebook with definitions, and "
                                        "iterates with researcher-edited context. The researcher is "
                                        "the final authority β€” human code columns always override AI.\n\n"
                                        "**Architecture:** LangGraph supervisor + 7 agent tools "
                                        "(read_corpus, read_phase1_context, propose_code, "
                                        "check_codebook, add_to_codebook, flag_for_review, "
                                        "save_iteration). Agent decides ordering, flags ambiguous "
                                        "sentences, and avoids codebook duplication.\n\n"
                                        "**Braun & Clarke 2006 compliance target:** ~88% with full "
                                        "agent + 3 iterations + researcher review. Unclosable gaps: "
                                        "reflexive engagement depth, time-on-task verification, felt "
                                        "sense of codes (documented in COMPLIANCE.md).\n\n"
                                        "**Round 2 status (this release):** Real LangGraph agent wired. "
                                        "Click Run iteration 1 to invoke Mistral through the 7-tool "
                                        "supervisor loop. Runtime: ~60-120 seconds for 30 sentences. "
                                        "Iteration 2 reads researcher edits from iteration 1. "
                                        "Iteration 3 is the final convergence pass."
                                    )

                                    # ---- Corpus source ----
                                    gr.Markdown("### Corpus β€” inherited from Phase 1")
                                    gr.Markdown(
                                        "*Phase 2 reads the canonical corpus loaded in Phase 1. "
                                        "If no corpus is loaded, go to Phase 1 β†’ Familiarization "
                                        "and load test_phase1.csv or your own canonical CSV first.*"
                                    )
                                    bc_p2_corpus_status = gr.Markdown("No corpus loaded. Load in Phase 1 first.")
                                    bc_p2_refresh_btn = gr.Button(
                                        "Refresh corpus status from Phase 1",
                                        variant="secondary",
                                    )

                                    # ---- Phase 1 context consumption ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Phase 1 context (consumed by the agent)")
                                    gr.Markdown(
                                        "*The Phase 2 agent reads the researcher's reflexive "
                                        "positioning and confirmed initial noticings from Phase 1 "
                                        "as context. This ensures Phase 2 coding is grounded in "
                                        "the researcher's familiarization, not starting from scratch.*"
                                    )
                                    bc_p2_phase1_summary = gr.Markdown(
                                        "*Phase 1 output will appear here after Save Phase 1.*"
                                    )

                                    # ---- Orientation β€” Braun & Clarke p. 84 ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Coding orientation (Braun & Clarke p. 84)")
                                    gr.Markdown(
                                        "*Braun & Clarke 2006 (p. 84) treat SEMANTIC vs LATENT as "
                                        "an analysis-wide choice, not a per-sentence distinction. "
                                        "Choose ONE orientation for this whole analysis. The agent "
                                        "will code every sentence at the level you pick.*  \n\n"
                                        "**Semantic** β€” surface content, what the text explicitly says  \n"
                                        "**Latent** β€” underlying assumptions, what the text implies"
                                    )
                                    bc_p2_orientation = gr.Radio(
                                        choices=["semantic", "latent"],
                                        value="semantic",
                                        label="Coding orientation for this analysis",
                                        interactive=True,
                                    )

                                    # ---- Iteration controls ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Agentic coding iterations")
                                    gr.Markdown(
                                        "Braun & Clarke insist on iterative refinement. Run "
                                        "iteration 1 β†’ review AI codes in the table β†’ edit human "
                                        "columns β†’ run iteration 2 (agent reads your edits as "
                                        "context) β†’ review β†’ iteration 3 β†’ converge."
                                    )
                                    with gr.Row():
                                        bc_p2_run_iter1_btn = gr.Button(
                                            "Run iteration 1",
                                            variant="primary",
                                        )
                                        bc_p2_run_iter2_btn = gr.Button(
                                            "Run iteration 2 (reads your edits)",
                                            variant="primary",
                                        )
                                        bc_p2_run_iter3_btn = gr.Button(
                                            "Run iteration 3 (final)",
                                            variant="primary",
                                        )
                                    bc_p2_iter_status = gr.Markdown("*No iterations run yet.*")

                                    # ---- Coding table ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Initial Codes Table")
                                    gr.Markdown(
                                        "*Every sentence gets two code levels (semantic + latent) "
                                        "per iteration. Edit the `human_code_iterN` columns to "
                                        "override the agent. The `final_code` column is populated "
                                        "from the latest human edit or the latest AI code if no "
                                        "human edit exists.*"
                                    )
                                    bc_p2_codes_table = gr.Dataframe(
                                        headers=[
                                            "L1", "L2", "L3", "L4", "sentence_id", "sentence",
                                            "ai_code_iter1", "human_code_iter1",
                                            "ai_code_iter2", "human_code_iter2",
                                            "ai_code_iter3", "human_code_iter3",
                                            "final_code", "flagged",
                                        ],
                                        label="Phase 2 Initial Codes β€” edit human_code_iterN columns",
                                        interactive=True,
                                        wrap=True,
                                    )

                                    # ---- Codebook ----
                                    gr.Markdown("---")
                                    gr.Markdown("### Codebook")
                                    gr.Markdown(
                                        "*Braun & Clarke 2006 require a codebook: the dictionary "
                                        "of codes with definitions, provenance, and usage counts. "
                                        "The agent maintains this as it codes; the researcher can "
                                        "edit definitions directly.*"
                                    )
                                    bc_p2_codebook_table = gr.Dataframe(
                                        headers=[
                                            "code_name", "definition", "created_by",
                                            "provenance", "sentence_count",
                                        ],
                                        label="Phase 2 Codebook β€” edit definitions",
                                        interactive=True,
                                        wrap=True,
                                    )

                                    # ---- Save ----
                                    gr.Markdown("---")
                                    bc_p2_save_btn = gr.Button(
                                        "Save Final Codes + Codebook β†’ Supabase + JSON artifact",
                                        variant="primary",
                                    )
                                    bc_p2_save_status = gr.Markdown("")





                                # ------------ Phase 3 -- Searching for Themes ------------
                                with gr.Accordion("Phase 3 β€” Searching for Themes", open=False):
                                    gr.Markdown(
                                        "## Phase 3 -- Searching for Themes\n\n"
                                        "*Braun & Clarke 2006, Phase 3: \"Collating codes into potential "
                                        "themes, gathering all data relevant to each potential theme\" (p. 89).*\n\n"
                                        "This phase clusters the Phase 2 codebook codes by semantic similarity "
                                        "(sentence-transformers embeddings + agglomerative clustering), then "
                                        "proposes a candidate theme name and description for each cluster "
                                        "via one Mistral call per cluster.\n\n"
                                        "**Researcher action:** review the candidate themes, edit "
                                        "`researcher_theme_name` and `researcher_notes` columns, then "
                                        "re-run with different thresholds if needed. B&C 2006 explicitly "
                                        "say Phase 3 is tentative and iterative."
                                    )

                                    gr.Markdown("### Clustering parameters (researcher-controlled)")
                                    gr.Markdown(
                                        "*B&C 2006 do not prescribe a fixed number of themes. "
                                        "Themes emerge from the clustering threshold you set. "
                                        "Lower similarity = fewer, broader themes. "
                                        "Higher similarity = more, tighter themes.*"
                                    )
                                    with gr.Row():
                                        bc_p3_similarity = gr.Slider(
                                            minimum=0.3, maximum=0.95, value=0.60, step=0.05,
                                            label="Similarity threshold",
                                            info="Codes more similar than this cluster together. Default 0.60.",
                                        )
                                        bc_p3_min_size = gr.Slider(
                                            minimum=2, maximum=10, value=2, step=1,
                                            label="Minimum cluster size",
                                            info="Clusters smaller than this go into noise bucket. Default 2.",
                                        )

                                    bc_p3_run_btn = gr.Button(
                                        "Run Phase 3 -- Cluster codes into candidate themes",
                                        variant="primary",
                                    )
                                    bc_p3_status = gr.Markdown("*No themes generated yet. Run Phase 2 first.*")

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Candidate Themes Table\n"
                                        "*Edit `researcher_theme_name` and `researcher_notes` to override "
                                        "or refine the AI-generated theme names. Researcher is the final "
                                        "authority (Braun & Clarke 2006, reflexive TA principle).*"
                                    )
                                    bc_p3_themes_table = gr.Dataframe(
                                        headers=[
                                            "theme_id", "candidate_theme_name", "description",
                                            "rationale", "member_codes", "code_count",
                                            "researcher_theme_name", "researcher_notes",
                                        ],
                                        label="Phase 3 Candidate Themes -- edit researcher_theme_name and researcher_notes",
                                        interactive=True,
                                        wrap=True,
                                    )

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Noise Codes\n"
                                        "*Codes that did not fit any cluster (below minimum cluster size). "
                                        "Review these -- they may represent important edge cases or require "
                                        "lower similarity threshold to be absorbed.*"
                                    )
                                    bc_p3_noise_table = gr.Dataframe(
                                        headers=["code_name", "definition"],
                                        label="Noise codes (did not cluster)",
                                        interactive=False,
                                        wrap=True,
                                    )

                                    gr.Markdown("---")
                                    bc_p3_save_btn = gr.Button(
                                        "Save Phase 3 output (themes + noise -> JSON artifact)",
                                        variant="secondary",
                                    )
                                    bc_p3_save_status = gr.Markdown("")


                                # ------------ Phase 4 -- Reviewing Themes ------------
                                with gr.Accordion("Phase 4 β€” Reviewing Themes", open=False):
                                    gr.Markdown(
                                        "## Phase 4 -- Reviewing Themes\n\n"
                                        "*Braun & Clarke 2006 p. 91: \"Reviewing, refining and sometimes "
                                        "reducing your themes.\"*\n\n"
                                        "**Level 1** -- coded extracts check: are the member codes and "
                                        "sentences within each theme coherent? (within-theme cohesion score)\n\n"
                                        "**Level 2** -- full dataset check: is each theme distinct from "
                                        "others? Is it appropriately scoped?\n\n"
                                        "The LLM suggests a verdict for each theme. "
                                        "**Researcher makes the final call** by editing "
                                        "`researcher_verdict` and `researcher_action_notes`."
                                    )

                                    bc_p4_run_btn = gr.Button(
                                        "Run Phase 4 -- Review all themes (cohesion + LLM verdict)",
                                        variant="primary",
                                    )
                                    bc_p4_status = gr.Markdown("*No review run yet. Run Phase 3 first.*")

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Theme Review Table\n"
                                        "*`within_cohesion`: 0.0 = incoherent, 1.0 = perfectly tight. "
                                        "B&C guidance: cohesion < 0.4 = consider split/drop, > 0.7 = healthy.*\n\n"
                                        "*`llm_verdict`: AI suggestion (keep/merge/split/drop). "
                                        "Edit `researcher_verdict` with your own decision.*"
                                    )
                                    bc_p4_review_table = gr.Dataframe(
                                        headers=[
                                            "theme_id", "theme_name", "member_codes", "code_count",
                                            "member_sentence_count", "within_cohesion",
                                            "llm_verdict", "llm_reasoning", "llm_action_suggestion",
                                            "researcher_verdict", "researcher_action_notes",
                                        ],
                                        label="Phase 4 Theme Review -- edit researcher_verdict and researcher_action_notes",
                                        interactive=True,
                                        wrap=True,
                                    )

                                    gr.Markdown("---")
                                    bc_p4_save_btn = gr.Button(
                                        "Save Phase 4 verdicts -> JSON artifact",
                                        variant="secondary",
                                    )
                                    bc_p4_save_status = gr.Markdown("")


                                # ------------ Phase 5 -- Defining and Naming ------------
                                with gr.Accordion("Phase 5 β€” Defining and Naming Themes", open=False):
                                    gr.Markdown(
                                        "## Phase 5 -- Defining and Naming Themes\n\n"
                                        "*Braun & Clarke 2006 p. 92: \"Ongoing analysis to refine "
                                        "the specifics of each theme, and the overall story the "
                                        "analysis tells, generating clear definitions and names.\"*\n\n"
                                        "This phase takes the **surviving themes from Phase 4** "
                                        "(verdict = keep or merge) and produces:\n"
                                        "- A **final theme name** (concise, punchy, analytically clear)\n"
                                        "- A **definition** (what the theme includes and excludes)\n"
                                        "- A **scope note** (what it does NOT cover)\n"
                                        "- A **narrative contribution** (role in the overall analysis story)\n\n"
                                        "**Researcher action:** Edit `researcher_final_name` and "
                                        "`researcher_definition` to override the AI suggestions. "
                                        "Researcher is the final authority."
                                    )

                                    bc_p5_run_btn = gr.Button(
                                        "Run Phase 5 -- Define and name all surviving themes",
                                        variant="primary",
                                    )
                                    bc_p5_status = gr.Markdown("*No definitions yet. Run Phase 4 first.*")

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Theme Definitions Table\n"
                                        "*Edit `researcher_final_name` and `researcher_definition` "
                                        "to set your own final names and definitions. "
                                        "These will carry forward to Phase 6 (the report).*"
                                    )
                                    bc_p5_def_table = gr.Dataframe(
                                        headers=[
                                            "theme_id", "original_name", "final_name",
                                            "definition", "scope_note",
                                            "narrative_contribution", "member_codes",
                                            "code_count", "researcher_final_name",
                                            "researcher_definition",
                                        ],
                                        label="Phase 5 Theme Definitions -- edit researcher_final_name and researcher_definition",
                                        interactive=True,
                                        wrap=True,
                                    )

                                    gr.Markdown("---")
                                    bc_p5_save_btn = gr.Button(
                                        "Save Phase 5 definitions -> JSON artifact",
                                        variant="secondary",
                                    )
                                    bc_p5_save_status = gr.Markdown("")


                                # ------------ Phase 6 -- Producing the Report ------------
                                with gr.Accordion("Phase 6 β€” Producing the Report", open=False):
                                    gr.Markdown(
                                        "## Phase 6 -- Producing the Report\n\n"
                                        "*Braun & Clarke 2006 p. 93: \"The final phase is writing the report. "
                                        "The task here is to tell the complicated story of your data in a way "
                                        "that convinces the reader of the merit and validity of your analysis.\"*\n\n"
                                        "This phase generates a complete analytic report from your Phase 5 "
                                        "theme definitions, weaving together:\n"
                                        "- Theme definitions and analytic narratives\n"
                                        "- Data extracts (quotes) evidencing each theme\n"
                                        "- Cross-theme analysis\n"
                                        "- Conclusion\n\n"
                                        "**Researcher action:** Edit the report directly in the text area below. "
                                        "The report is yours β€” the AI drafts, you refine."
                                    )

                                    bc_p6_research_question = gr.Textbox(
                                        label="Research question / focus (optional)",
                                        placeholder="e.g. How do employees experience organisational change?",
                                        lines=2,
                                    )

                                    bc_p6_run_btn = gr.Button(
                                        "Run Phase 6 -- Generate analytic report",
                                        variant="primary",
                                    )
                                    bc_p6_status = gr.Markdown("*No report yet. Run Phase 5 first.*")

                                    gr.Markdown("---")
                                    gr.Markdown(
                                        "### Analytic Report\n"
                                        "*Edit directly below. The report is in Markdown format β€” "
                                        "headers, bold, and block quotes render automatically.*"
                                    )
                                    bc_p6_report_text = gr.Textbox(
                                        label="Phase 6 Analytic Report (editable)",
                                        lines=30,
                                        placeholder="Report will appear here after running Phase 6...",
                                        interactive=True,
                                    )

                                    gr.Markdown("---")
                                    bc_p6_save_btn = gr.Button(
                                        "Save report -> JSON + Markdown artifacts",
                                        variant="secondary",
                                    )
                                    bc_p6_save_status = gr.Markdown("")


                        # ==================== COMPUTATIONAL GROUNDED THEORY (family) ====================
                        # ==================== SPJIMR CORPUS ANALYSIS ====================
                        with gr.Tab("SPJIMR Corpus Analysis"):
                            import spjimr_ui
                            spjimr_ui.render_spjimr_ui()

    # ZONE 5 β€” Event wiring (.click handlers β€” the glue)
    # ========================================================================
    # Each .click() connects a button to a handler function. The function's
    # return values go into the components listed in outputs=[...].
    #
    # GOLDEN RULE: the number of return values from the handler must match
    # the length of the outputs list, in the same order.
    #
    # chat_outputs is the shared list used by process_message, submit_form,
    # and new_chat. All three must return 8 values in the same order.
    # ----------------
    # Event wiring
    # ----------------
    chat_outputs = [
        chatbot, table_out, extracted_out, chart_out, code_out,
        downloads_state, downloads_files_out, chat_input,
    ]

    send_btn.click(
        process_message,
        inputs=[chat_input, mode_select, llm_provider_select, llm_key_input,
                chatbot, loaded_context_state, downloads_state],
        outputs=chat_outputs,
    )
    chat_input.submit(
        process_message,
        inputs=[chat_input, mode_select, llm_provider_select, llm_key_input,
                chatbot, loaded_context_state, downloads_state],
        outputs=chat_outputs,
    )

    form_submit.click(
        submit_form,
        inputs=[
            form_task, form_op, form_a, form_b, form_city, form_notes,
            mode_select, llm_provider_select, llm_key_input, chatbot,
            loaded_context_state, downloads_state,
        ],
        outputs=chat_outputs,
    )

    form_clear.click(
        clear_form,
        outputs=[form_task, form_op, form_a, form_b, form_city, form_notes],
    )

    new_chat_btn.click(
        new_chat,
        inputs=[downloads_state],
        outputs=chat_outputs,
    )

    # Data source handlers
    scrape_btn.click(
        scrape_url,
        inputs=[url_input, downloads_state],
        outputs=[scrape_preview, scrape_status, loaded_context_state,
                 downloads_state, downloads_files_out],
    )
    scrape_clear_btn.click(
        clear_scrape,
        outputs=[url_input, scrape_preview, scrape_status, loaded_context_state],
    )

    pdf_extract_btn.click(
        extract_pdf,
        inputs=[pdf_input, downloads_state],
        outputs=[pdf_preview, pdf_status, loaded_context_state,
                 downloads_state, downloads_files_out],
    )
    pdf_clear_btn.click(
        clear_pdf,
        outputs=[pdf_input, pdf_preview, pdf_status, loaded_context_state],
    )

    csv_load_btn.click(
        load_spreadsheet,
        inputs=[csv_input, downloads_state],
        outputs=[csv_preview, csv_status, loaded_context_state,
                 downloads_state, downloads_files_out],
    )
    csv_clear_btn.click(
        clear_spreadsheet,
        outputs=[csv_input, csv_preview, csv_status, loaded_context_state],
    )

    ml_load_btn.click(
        load_ml_examples,
        inputs=[downloads_state],
        outputs=[ml_preview, ml_status, loaded_context_state,
                 downloads_state, downloads_files_out],
    )
    ml_clear_btn.click(
        clear_ml_examples,
        outputs=[ml_preview, ml_status, loaded_context_state],
    )

    # Training handlers (supervised)
    train_btn.click(
        handle_train,
        inputs=[downloads_state],
        outputs=[trained_state, train_status, confusion_out,
                 downloads_state, downloads_files_out],
    )
    train_clear_btn.click(
        clear_training,
        outputs=[trained_state, train_status, confusion_out, predict_out],
    )
    predict_btn.click(
        handle_predict,
        inputs=[trained_state, predict_input, downloads_state],
        outputs=[predict_out, downloads_state, downloads_files_out],
    )
    sup_label_filter.change(
        filter_training_dataset,
        inputs=[sup_label_filter],
        outputs=[sup_dataset_view],
    )

    # Training handlers (unsupervised)
    cluster_btn.click(
        handle_cluster,
        inputs=[cluster_sim, cluster_min, cluster_nnear, cluster_llm_toggle,
                llm_provider_select, llm_key_input, downloads_state],
        outputs=[cluster_out, cluster_status, downloads_state, downloads_files_out],
    )
    cluster_clear_btn.click(
        clear_clustering,
        outputs=[cluster_out, cluster_status],
    )

    # ---- Vector Processing wiring ----
    vectorize_btn.click(
        handle_vectorize_preview,
        inputs=[embedding_provider_select, embedding_key_input, downloads_state],
        outputs=[vectorize_out, vectorize_status,
                 downloads_state, downloads_files_out],
    )
    vectorize_clear_btn.click(
        clear_vectorize_preview,
        outputs=[vectorize_out, vectorize_status],
    )
    vector_index_btn.click(
        handle_vector_index,
        inputs=[embedding_provider_select, embedding_key_input, downloads_state],
        outputs=[vector_index_status, downloads_state, downloads_files_out],
    )
    vector_clear_btn.click(
        handle_vector_clear,
        inputs=[downloads_state],
        outputs=[vector_index_status, downloads_state, downloads_files_out],
    )
    vector_search_btn.click(
        handle_vector_search,
        inputs=[vector_query, vector_n,
                embedding_provider_select, embedding_key_input, downloads_state],
        outputs=[vector_search_out, vector_search_status,
                 downloads_state, downloads_files_out],
    )

    # ---- Workbench wiring ----
    wb_cgt_run.click(
        handle_wb_cgt,
        inputs=[wb_cgt_msg, wb_cgt_sim, wb_cgt_min, wb_cgt_nnear,
                llm_provider_select, llm_key_input,
                loaded_context_state, downloads_state],
        outputs=[wb_cgt_trace, wb_cgt_reply, wb_cgt_sentences,
                 downloads_state, downloads_files_out],
    )

    # ---- CGT Phase 2 Pattern Refinement wiring (Nelson 2020 Step 2) ----
    # Phase 2 consumes wb_cgt_sentences (Phase 1 output) per Option Ξ±:
    # detection is a discrete step whose output feeds refinement.
    cgt_p2_surface_btn.click(
        handle_cgt_p2_surface,
        inputs=[wb_cgt_sentences, cgt_p2_n_exemplars, cgt_p2_reflexivity,
                llm_provider_select, llm_key_input, downloads_state],
        outputs=[cgt_p2_refinement_table, cgt_p2_status,
                 downloads_state, downloads_files_out],
    )
    cgt_p2_save_btn.click(
        handle_cgt_p2_save,
        inputs=[cgt_p2_refinement_table, cgt_p2_reflexivity, downloads_state],
        outputs=[cgt_p2_save_status, downloads_state, downloads_files_out],
    )
    wb_cta_run.click(
        handle_wb_cta,
        inputs=[wb_cta_msg, wb_cta_max,
                llm_provider_select, llm_key_input,
                loaded_context_state, downloads_state],
        outputs=[wb_cta_trace, wb_cta_reply, wb_cta_codes,
                 downloads_state, downloads_files_out],
    )

    # ---- Phase 1 Familiarization wiring ----
    bc_p1_load_test_btn.click(
        handle_p1_load_test_csv,
        inputs=[downloads_state],
        outputs=[bc_corpus_state, bc_p1_corpus_status, bc_p1_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    bc_p1_upload_csv.upload(
        handle_p1_upload_csv,
        inputs=[bc_p1_upload_csv, downloads_state],
        outputs=[bc_corpus_state, bc_p1_corpus_status, bc_p1_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    # ---- G&W at Scale load wiring (writes to gw_corpus_state) ----
    gw_load_test_btn.click(
        handle_p1_load_test_csv,
        inputs=[downloads_state],
        outputs=[gw_corpus_state, gw_load_status, gw_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    gw_upload_csv.upload(
        handle_p1_upload_csv,
        inputs=[gw_upload_csv, downloads_state],
        outputs=[gw_corpus_state, gw_load_status, gw_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    # ---- B&C Workbench load wiring (writes to bc_corpus_state) ----
    bc_load_test_btn.click(
        handle_p1_load_test_csv,
        inputs=[downloads_state],
        outputs=[bc_corpus_state, bc_load_status, bc_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    bc_upload_csv.upload(
        handle_p1_upload_csv,
        inputs=[bc_upload_csv, downloads_state],
        outputs=[bc_corpus_state, bc_load_status, bc_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    # ---- Nelson + Carlsen & Ralund load wiring ----
    cgt_load_test_btn.click(
        handle_p1_load_test_csv,
        inputs=[downloads_state],
        outputs=[cgt_corpus_state, cgt_load_status, cgt_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    cgt_upload_csv.upload(
        handle_p1_upload_csv,
        inputs=[cgt_upload_csv, downloads_state],
        outputs=[cgt_corpus_state, cgt_load_status, cgt_corpus_preview,
                 downloads_state, downloads_files_out],
    )
    bc_p1_build_table_btn.click(
        handle_p1_build_validation_table,
        inputs=[bc_corpus_state,
                bc_p1_facilitator_memo, bc_p1_facilitator_transcript, bc_p1_facilitator_citations,
                bc_p1_companion_challenges, bc_p1_companion_reflexivity, bc_p1_companion_breadth],
        outputs=[bc_p1_validation_table],
    )
    bc_p1_save_btn.click(
        handle_p1_save,
        inputs=[bc_corpus_state,
                bc_p1_facilitator_memo, bc_p1_facilitator_transcript, bc_p1_facilitator_citations,
                bc_p1_companion_challenges, bc_p1_companion_reflexivity, bc_p1_companion_breadth,
                bc_p1_validation_table,
                downloads_state],
        outputs=[bc_p1_save_status, downloads_state, downloads_files_out],
    )

    # ---- Phase 2 Initial Coding wiring ----
    bc_p2_refresh_btn.click(
        handle_p2_refresh_corpus,
        inputs=[bc_corpus_state,
                bc_p1_facilitator_memo, bc_p1_companion_reflexivity, bc_p1_validation_table],
        outputs=[bc_p2_corpus_status, bc_p2_phase1_summary],
    )
    bc_p2_run_iter1_btn.click(
        lambda corpus, codes, codebook, memo, reflex, vtable, prov, key, orient:
            handle_p2_run_iteration(1, corpus, codes, codebook, memo, reflex, vtable, prov, key, orient),
        inputs=[bc_corpus_state, bc_p2_codes_table, bc_p2_codebook_table,
                bc_p1_facilitator_memo, bc_p1_companion_reflexivity, bc_p1_validation_table,
                llm_provider_select, llm_key_input, bc_p2_orientation],
        outputs=[bc_p2_codes_table, bc_p2_codebook_table, bc_p2_iter_status],
    )
    bc_p2_run_iter2_btn.click(
        lambda corpus, codes, codebook, memo, reflex, vtable, prov, key, orient:
            handle_p2_run_iteration(2, corpus, codes, codebook, memo, reflex, vtable, prov, key, orient),
        inputs=[bc_corpus_state, bc_p2_codes_table, bc_p2_codebook_table,
                bc_p1_facilitator_memo, bc_p1_companion_reflexivity, bc_p1_validation_table,
                llm_provider_select, llm_key_input, bc_p2_orientation],
        outputs=[bc_p2_codes_table, bc_p2_codebook_table, bc_p2_iter_status],
    )
    bc_p2_run_iter3_btn.click(
        lambda corpus, codes, codebook, memo, reflex, vtable, prov, key, orient:
            handle_p2_run_iteration(3, corpus, codes, codebook, memo, reflex, vtable, prov, key, orient),
        inputs=[bc_corpus_state, bc_p2_codes_table, bc_p2_codebook_table,
                bc_p1_facilitator_memo, bc_p1_companion_reflexivity, bc_p1_validation_table,
                llm_provider_select, llm_key_input, bc_p2_orientation],
        outputs=[bc_p2_codes_table, bc_p2_codebook_table, bc_p2_iter_status],
    )
    bc_p2_save_btn.click(
        handle_p2_save,
        inputs=[bc_corpus_state, bc_p2_codes_table, bc_p2_codebook_table, downloads_state],
        outputs=[bc_p2_save_status, downloads_state, downloads_files_out],
    )


    # ---- Phase 3 Searching for Themes wiring ----
    bc_p3_run_btn.click(
        handle_p3_run,
        inputs=[
            bc_p2_codebook_table,
            bc_p3_similarity, bc_p3_min_size, bc_p2_orientation,
            bc_p1_companion_reflexivity,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[bc_p3_themes_table, bc_p3_noise_table, bc_p3_status, downloads_state, downloads_files_out],
    )
    bc_p3_save_btn.click(
        handle_p3_save,
        inputs=[bc_p3_themes_table, bc_p3_noise_table, downloads_state],
        outputs=[bc_p3_save_status, downloads_state, downloads_files_out],
    )


    # ---- Phase 4 Reviewing Themes wiring ----
    bc_p4_run_btn.click(
        handle_p4_run,
        inputs=[
            bc_p3_themes_table, bc_p2_codes_table,
            bc_p1_companion_reflexivity,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[bc_p4_review_table, bc_p4_status, downloads_state, downloads_files_out],
    )
    bc_p4_save_btn.click(
        handle_p4_save,
        inputs=[bc_p4_review_table, downloads_state],
        outputs=[bc_p4_save_status, downloads_state, downloads_files_out],
    )


    # ---- Phase 5 Defining and Naming wiring ----
    bc_p5_run_btn.click(
        handle_p5_run,
        inputs=[
            bc_p4_review_table,
            bc_p1_companion_reflexivity,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[bc_p5_def_table, bc_p5_status, downloads_state, downloads_files_out],
    )
    bc_p5_save_btn.click(
        handle_p5_save,
        inputs=[bc_p5_def_table, downloads_state],
        outputs=[bc_p5_save_status, downloads_state, downloads_files_out],
    )


    # ---- Phase 6 Producing the Report wiring ----
    bc_p6_run_btn.click(
        handle_p6_run,
        inputs=[
            bc_p5_def_table, bc_p2_codes_table,
            bc_p6_research_question,
            bc_p1_companion_reflexivity,
            bc_corpus_state,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[bc_p6_report_text, bc_p6_status, downloads_state, downloads_files_out],
    )
    bc_p6_save_btn.click(
        handle_p6_save,
        inputs=[bc_p6_report_text, downloads_state],
        outputs=[bc_p6_save_status, downloads_state, downloads_files_out],
    )


    # ---- Phase 0 Preparation wiring (Moreno-Ortiz 2023; BERTopic_Teen 2025) ----
    # Each button updates gw_corpus_state in-place (so next prep step or
    # Phase 0 Sampling sees the prepared corpus) and refreshes the output
    # table + status. Downloads list accumulates artifact JSONs.
    p0prep_noise_btn.click(
        handle_p0prep_noise_strip,
        inputs=[gw_corpus_state, downloads_state],
        outputs=[gw_corpus_state, p0prep_table, p0prep_status,
                 downloads_state, downloads_files_out],
    )
    p0prep_length_btn.click(
        handle_p0prep_length_filter,
        inputs=[gw_corpus_state, p0prep_min_words, downloads_state],
        outputs=[gw_corpus_state, p0prep_table, p0prep_status,
                 downloads_state, downloads_files_out],
    )
    p0prep_hash_btn.click(
        handle_p0prep_hash_dedup,
        inputs=[gw_corpus_state, p0prep_case_sensitive, downloads_state],
        outputs=[gw_corpus_state, p0prep_table, p0prep_status,
                 downloads_state, downloads_files_out],
    )
    p0prep_semantic_btn.click(
        handle_p0prep_semantic_dedup,
        inputs=[gw_corpus_state, p0prep_semantic_threshold, downloads_state],
        outputs=[gw_corpus_state, p0prep_table, p0prep_status,
                 downloads_state, downloads_files_out],
    )


    # ---- Phase 0 Sampling wiring (Gauthier & Wallace 2022) ----
    # Outputs 6: compression_table, split_proposals_table, compressed_corpus_state,
    #            status, downloads_state, downloads_files_out
    gw_compress_btn.click(
        handle_compression_run,
        inputs=[
            gw_corpus_state,
            gw_sentences_per_cluster,
            gw_min_cluster_size,
            gw_outlier_sample,
            gw_min_cluster_fit,
            downloads_state,
        ],
        outputs=[
            gw_compress_table,
            gw_split_proposals_table,
            gw_compressed_corpus_state,
            gw_compress_status,
            downloads_state,
            downloads_files_out,
        ],
    )

    # Apply researcher split decisions and re-sample
    gw_apply_splits_btn.click(
        handle_apply_split_decisions,
        inputs=[
            gw_corpus_state,
            gw_split_proposals_table,
            gw_sentences_per_cluster,
            gw_min_cluster_size,
            gw_outlier_sample,
            gw_min_cluster_fit,
            downloads_state,
        ],
        outputs=[
            gw_compress_table,
            gw_split_proposals_table,
            gw_compressed_corpus_state,
            gw_compress_status,
            downloads_state,
            downloads_files_out,
        ],
    )

    # ---- Cluster labeling workflow (2 iterations + final commit) ----
    # Phase 2 pattern: DataFrame in, DataFrame out. NO gr.State plumbing β€”
    # that was the cause of the stale-table + flicker bugs.

    gw_label_init_btn.click(
        handle_label_init_cluster_table,
        inputs=[gw_compress_table],
        outputs=[gw_cluster_labels_table, gw_label_status],
    )

    gw_label_iter1_btn.click(
        handle_label_iter1,
        inputs=[
            gw_cluster_labels_table,
            gw_compress_table,
            llm_provider_select,
            llm_key_input,
            downloads_state,
        ],
        outputs=[
            gw_cluster_labels_table,
            gw_label_status, downloads_state, downloads_files_out,
        ],
    )

    gw_label_iter2_btn.click(
        handle_label_iter2,
        inputs=[
            gw_cluster_labels_table,
            gw_compress_table,
            llm_provider_select,
            llm_key_input,
            downloads_state,
        ],
        outputs=[
            gw_cluster_labels_table,
            gw_label_status, downloads_state, downloads_files_out,
        ],
    )

    # Commit handler returns 4 outputs (cluster_df, status, dl, dl).
    # gw_compress_table (Phase 0 Sampling Table) is NOT in outputs β€” one-way
    # pipeline, Phase 0 output stays frozen. Cluster Labeling produces its
    # own artifact; downstream stages join on cluster_id at read-time.
    gw_label_commit_btn.click(
        handle_label_commit_final,
        inputs=[
            gw_cluster_labels_table,
            gw_compress_table,
            downloads_state,
        ],
        outputs=[
            gw_cluster_labels_table,
            gw_label_status, downloads_state, downloads_files_out,
        ],
    )

    # ---- Methodology comparison download buttons (one per workbench) ----
    bc_comparison_dl_btn.click(
        lambda dl: handle_methodology_comparison_download("bc", dl),
        inputs=[downloads_state],
        outputs=[bc_comparison_dl_status, downloads_state, downloads_files_out],
    )
    gw_comparison_dl_btn.click(
        lambda dl: handle_methodology_comparison_download("gw", dl),
        inputs=[downloads_state],
        outputs=[gw_comparison_dl_status, downloads_state, downloads_files_out],
    )
    cgt_comparison_dl_btn.click(
        lambda dl: handle_methodology_comparison_download("cgt", dl),
        inputs=[downloads_state],
        outputs=[cgt_comparison_dl_status, downloads_state, downloads_files_out],
    )

    # ---- Phase 1 Familiarization wiring (G&W path, reuses handle_p1_save) ----
    # Methodological sequence: Phase 0 β†’ researcher edits `selected` column β†’
    # Phase 1 Familiarization reads the researcher-APPROVED sentences (selected=true
    # in the edited gw_compress_table). Phase 1 save ALSO populates
    # gw_approved_corpus_state which Phase 2-6 read from, enforcing the sequence
    # at the wiring level.
    def _gw_p1_save_with_selected_filter(

        compress_table, raw_corpus,

        memo, transcript, citations,

        challenges, reflexivity, breadth,

        valtable, dl,

    ):
        # Determine source β€” edited compression table (preferred) or raw corpus
        source = None
        if isinstance(compress_table, pd.DataFrame) and len(compress_table) > 0:
            if "selected" in compress_table.columns:
                # Normalize selected column: handle both bool and str 'true'/'false'
                sel = compress_table["selected"]
                mask = sel.apply(
                    lambda v: (
                        True if v is True
                        else False if v is False
                        else str(v).strip().lower() in ("true", "1", "yes", "t")
                    )
                )
                filtered = compress_table[mask]
                source = filtered.to_dict("records")
            else:
                source = compress_table.to_dict("records")
        if not source:
            source = raw_corpus or []
        # Call the existing handler
        status, dl_out, dl_files = handle_p1_save(
            source,
            memo, transcript, citations,
            challenges, reflexivity, breadth,
            valtable, dl,
        )
        # Also publish the approved corpus to gw_approved_corpus_state for Phase 2-6
        return status, dl_out, dl_files, source

    gw_p1_save_btn.click(
        _gw_p1_save_with_selected_filter,
        inputs=[gw_compress_table, gw_corpus_state,
                gw_p1_facilitator_memo, gw_p1_facilitator_transcript, gw_p1_facilitator_citations,
                gw_p1_companion_challenges, gw_p1_companion_reflexivity, gw_p1_companion_breadth,
                gw_p1_validation_table,
                downloads_state],
        outputs=[gw_p1_save_status, downloads_state, downloads_files_out, gw_approved_corpus_state],
    )

    # ====================================================================
    # G&W Phase 2-6 wiring β€” reuses B&C handler functions with G&W state
    # objects. Data isolation: every input/output references gw_* widgets.
    # Phase 2 reads gw_approved_corpus_state (populated by G&W Phase 1 save).
    # ====================================================================

    # ---- G&W Phase 2 Initial Coding wiring ----
    gw_p2_refresh_btn.click(
        handle_p2_refresh_corpus,
        inputs=[gw_approved_corpus_state,
                gw_p1_facilitator_memo, gw_p1_companion_reflexivity, gw_p1_validation_table],
        outputs=[gw_p2_corpus_status, gw_p2_phase1_summary],
    )
    gw_p2_run_iter1_btn.click(
        lambda corpus, codes, codebook, memo, reflex, vtable, prov, key, orient:
            handle_p2_run_iteration(1, corpus, codes, codebook, memo, reflex, vtable, prov, key, orient),
        inputs=[gw_approved_corpus_state, gw_p2_codes_table, gw_p2_codebook_table,
                gw_p1_facilitator_memo, gw_p1_companion_reflexivity, gw_p1_validation_table,
                llm_provider_select, llm_key_input, gw_p2_orientation],
        outputs=[gw_p2_codes_table, gw_p2_codebook_table, gw_p2_iter_status],
    )
    gw_p2_run_iter2_btn.click(
        lambda corpus, codes, codebook, memo, reflex, vtable, prov, key, orient:
            handle_p2_run_iteration(2, corpus, codes, codebook, memo, reflex, vtable, prov, key, orient),
        inputs=[gw_approved_corpus_state, gw_p2_codes_table, gw_p2_codebook_table,
                gw_p1_facilitator_memo, gw_p1_companion_reflexivity, gw_p1_validation_table,
                llm_provider_select, llm_key_input, gw_p2_orientation],
        outputs=[gw_p2_codes_table, gw_p2_codebook_table, gw_p2_iter_status],
    )
    gw_p2_run_iter3_btn.click(
        lambda corpus, codes, codebook, memo, reflex, vtable, prov, key, orient:
            handle_p2_run_iteration(3, corpus, codes, codebook, memo, reflex, vtable, prov, key, orient),
        inputs=[gw_approved_corpus_state, gw_p2_codes_table, gw_p2_codebook_table,
                gw_p1_facilitator_memo, gw_p1_companion_reflexivity, gw_p1_validation_table,
                llm_provider_select, llm_key_input, gw_p2_orientation],
        outputs=[gw_p2_codes_table, gw_p2_codebook_table, gw_p2_iter_status],
    )
    gw_p2_save_btn.click(
        handle_p2_save,
        inputs=[gw_approved_corpus_state, gw_p2_codes_table, gw_p2_codebook_table, downloads_state],
        outputs=[gw_p2_save_status, downloads_state, downloads_files_out],
    )

    # ---- G&W Phase 3 Searching for Themes wiring ----
    gw_p3_run_btn.click(
        handle_p3_run,
        inputs=[
            gw_p2_codebook_table,
            gw_p3_similarity, gw_p3_min_size, gw_p2_orientation,
            gw_p1_companion_reflexivity,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[gw_p3_themes_table, gw_p3_noise_table, gw_p3_status, downloads_state, downloads_files_out],
    )
    gw_p3_save_btn.click(
        handle_p3_save,
        inputs=[gw_p3_themes_table, gw_p3_noise_table, downloads_state],
        outputs=[gw_p3_save_status, downloads_state, downloads_files_out],
    )

    # ---- G&W Phase 4 Reviewing Themes wiring ----
    gw_p4_run_btn.click(
        handle_p4_run,
        inputs=[
            gw_p3_themes_table, gw_p2_codes_table,
            gw_p1_companion_reflexivity,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[gw_p4_review_table, gw_p4_status, downloads_state, downloads_files_out],
    )
    gw_p4_save_btn.click(
        handle_p4_save,
        inputs=[gw_p4_review_table, downloads_state],
        outputs=[gw_p4_save_status, downloads_state, downloads_files_out],
    )

    # ---- G&W Phase 5 Defining and Naming wiring ----
    gw_p5_run_btn.click(
        handle_p5_run,
        inputs=[
            gw_p4_review_table,
            gw_p1_companion_reflexivity,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[gw_p5_def_table, gw_p5_status, downloads_state, downloads_files_out],
    )
    gw_p5_save_btn.click(
        handle_p5_save,
        inputs=[gw_p5_def_table, downloads_state],
        outputs=[gw_p5_save_status, downloads_state, downloads_files_out],
    )

    # ---- G&W Phase 6 Producing the Report wiring ----
    gw_p6_run_btn.click(
        handle_p6_run,
        inputs=[
            gw_p5_def_table, gw_p2_codes_table,
            gw_p6_research_question,
            gw_p1_companion_reflexivity,
            gw_approved_corpus_state,
            llm_provider_select, llm_key_input,
            downloads_state,
        ],
        outputs=[gw_p6_report_text, gw_p6_status, downloads_state, downloads_files_out],
    )
    gw_p6_save_btn.click(
        handle_p6_save,
        inputs=[gw_p6_report_text, downloads_state],
        outputs=[gw_p6_save_status, downloads_state, downloads_files_out],
    )


if __name__ == "__main__":
    # Supabase startup check -- create tables if they don't exist
    if DB_OK:
        _db_status = db.startup_check()
        if _db_status["db_available"]:
            print(f"[app.py] Supabase connected. Tables ready: {_db_status['tables_created']}")
        else:
            print(f"[app.py] Supabase not available: {_db_status.get('error')}")
    else:
        print(f"[app.py] database.py not loaded: {_db_err}")

    # ssr_mode=False: Gradio 5/6's Server-Side Rendering breaks demo.launch()
    # on HuggingFace Spaces with the "localhost not accessible" error.
    # Confirmed workaround from HF forums + Gradio Discord.
    demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)