File size: 315,971 Bytes
266eda8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
"""
GelPredict Data Entry GUI — Production v2.0
- Views/Triggers/Constraints for data integrity
- Reagent-derived effective mM aggregation
- Safer edits, better validation, Excel export button
- Unit-safe calculations with PBS/DMEM support
"""

import streamlit as st
import sqlite3
import pandas as pd
import numpy as np
from datetime import datetime, date
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import uuid
import re
from contextlib import contextmanager
from functools import lru_cache
import subprocess
import itertools
import os
import shutil
import json
import io
import hashlib
import sqlite3 as _sqlite3  # for version check
import matplotlib.pyplot as plt
from PIL import Image, ExifTags

# Configure Streamlit page for wide mode (better for tablets/iPads)
st.set_page_config(
    page_title="GelPredict - Data Entry",
    page_icon="🧬",
    layout="wide",  # Use full width of screen
    initial_sidebar_state="expanded"
)

# iPad-optimized styling - larger text, bigger buttons, better spacing
st.markdown("""
<style>
    /* Larger base font for better readability on tablets */
    html, body, [class*="css"] {
        font-size: 16px !important;
    }
    
    /* Bigger input fields for easier touch */
    .stTextInput input, .stNumberInput input, .stTextArea textarea, .stSelectbox select {
        font-size: 18px !important;
        padding: 12px !important;
        min-height: 48px !important;
    }
    
    /* Larger buttons for better touch targets */
    .stButton button {
        font-size: 18px !important;
        padding: 12px 24px !important;
        min-height: 48px !important;
        font-weight: 600 !important;
    }
    
    /* Better spacing between form elements */
    .stTextInput, .stNumberInput, .stSelectbox, .stTextArea {
        margin-bottom: 20px !important;
    }
    
    /* Larger labels */
    label {
        font-size: 16px !important;
        font-weight: 600 !important;
        margin-bottom: 8px !important;
    }
    
    /* Better checkbox and radio button sizes */
    input[type="checkbox"], input[type="radio"] {
        width: 24px !important;
        height: 24px !important;
        margin-right: 12px !important;
    }
    
    /* Larger headers */
    h1 {
        font-size: 36px !important;
        margin-bottom: 16px !important;
    }
    
    h2 {
        font-size: 28px !important;
        margin-bottom: 12px !important;
    }
    
    h3 {
        font-size: 22px !important;
        margin-bottom: 10px !important;
    }
    
    /* Better expander headers */
    .streamlit-expanderHeader {
        font-size: 18px !important;
        padding: 16px !important;
    }
    
    /* Larger sidebar text */
    .css-1d391kg, [data-testid="stSidebar"] {
        font-size: 16px !important;
    }
    
    /* Better table display */
    .dataframe {
        font-size: 16px !important;
    }
    
    /* More padding for better touch */
    .block-container {
        padding: 2rem 3rem !important;
    }
    
    /* Better metric display */
    [data-testid="stMetricValue"] {
        font-size: 28px !important;
    }
    
    /* Larger captions */
    .css-10trblm {
        font-size: 14px !important;
    }
</style>
""", unsafe_allow_html=True)

# ============================================================================
# DATABASE SETUP
# ============================================================================

ROOT = Path(__file__).resolve().parents[1]
# Allow DB path override via environment variable (for testing)
DB_PATH = Path(os.getenv("GELPREDICT_DB", str(ROOT / "gelpredict.db"))).resolve()

# Media storage roots
MEDIA_ROOT = ROOT / "media"
IMG_ROOT   = MEDIA_ROOT / "images"
THM_ROOT   = MEDIA_ROOT / "thumbs"
for p in (MEDIA_ROOT, IMG_ROOT, THM_ROOT):
    p.mkdir(parents=True, exist_ok=True)

def _connect():
    con = sqlite3.connect(str(DB_PATH), isolation_level=None)
    con.row_factory = sqlite3.Row
    con.execute("PRAGMA journal_mode=WAL;")
    con.execute("PRAGMA foreign_keys=ON;")
    con.execute("PRAGMA synchronous=NORMAL;")
    return con

@contextmanager
def tx():
    con = _connect()
    try:
        con.execute("BEGIN IMMEDIATE;")
        yield con
        con.execute("COMMIT;")
    except Exception as e:
        con.execute("ROLLBACK;")
        raise e
    finally:
        con.close()

def get_connection():
    return _connect()

def new_record_id():
    """Generate UUID (legacy/fallback)."""
    return str(uuid.uuid4())

def generate_batch_id(family: str, species: Optional[str] = None, tissue: Optional[str] = None, 
                      date_obj = None, is_commercial: bool = False) -> str:
    """
    Auto-generate human-readable batch_id from ECM metadata.
    
    Format (Lab-made): {family_abbrev}-{species_abbrev}{tissue_abbrev}-{YYMMDD}
    Format (Commercial): Use manufacturer lot# (don't auto-generate)
    
    Examples:
    - decECM human mammary (Oct 12, 2025): dECM-HuMam-251012
    - collagen bovine tendon (Oct 12, 2025): COL-BovTen-251012
    - fibrin human plasma (Oct 12, 2025): FIB-HuPla-251012
    - Matrigel (commercial): 2345678 (from manufacturer)
    """
    if is_commercial:
        return ""  # Commercial batch_id should be entered manually (lot number)
    
    parts = []
    
    # Family abbreviation
    family_map = {
        "decECM": "dECM",
        "collagen": "COL",
        "fibrin": "FIB",
        "alginate": "ALG",
        "gelMA": "gMA",
        "hyaluronan": "HA",
        "PEG_DA": "PEG",
        "composite": "COMP",
        "other": "OTH"
    }
    fam_abbrev = family_map.get(family, family[:4].upper() if family else "UNK")
    parts.append(fam_abbrev)
    
    # Species + tissue abbreviation (first 2-3 chars each, capitalized)
    if species and tissue:
        # Species: first 2-3 chars, capitalize first
        sp_clean = species.replace(" ", "").replace("-", "")
        sp_abbrev = sp_clean[:3].capitalize() if len(sp_clean) >= 3 else sp_clean.capitalize()
        
        # Tissue: first 3 chars, capitalize first
        tis_clean = tissue.replace(" ", "").replace("-", "")
        tis_abbrev = tis_clean[:3].capitalize() if len(tis_clean) >= 3 else tis_clean.capitalize()
        
        parts.append(f"{sp_abbrev}{tis_abbrev}")
    
    # Date (YYMMDD)
    if date_obj:
        date_str = date_obj.strftime("%y%m%d")
    else:
        date_str = datetime.now().strftime("%y%m%d")
    parts.append(date_str)
    
    return "-".join(parts)

def generate_gelation_id(batch_id: str, gelation_date = None, sequence: int = 1) -> str:
    """
    Auto-generate gelation_id from batch_id and sequence.
    
    Format: {batch_id}-G{MMDD}-{seq}
    
    Examples:
    - dECM-HuMam-251012-G1012-1 (first gelation of Oct 12)
    - dECM-HuMam-251012-G1012-2 (second gelation of Oct 12)
    - 2345678-G1012-1 (commercial, first gelation of Oct 12)
    """
    if not batch_id:
        return f"GEL-{datetime.now().strftime('%y%m%d')}-{sequence:03d}"
    
    # Date (MMDD for gelation)
    if gelation_date:
        gel_date_str = gelation_date.strftime("%m%d")
    else:
        gel_date_str = datetime.now().strftime("%m%d")
    
    return f"{batch_id}-G{gel_date_str}-{sequence}"

def get_next_gelation_sequence(batch_id: str, gelation_date = None) -> int:
    """Get next gelation sequence number for a batch on a given date."""
    if not batch_id:
        return 1
    
    gel_date_str = (gelation_date or datetime.now()).strftime("%m%d")
    pattern = f"{batch_id}-G{gel_date_str}-%"
    
    conn = get_connection()
    try:
        result = conn.execute(
            "SELECT gelation_id FROM wells_master_v4 WHERE gelation_id LIKE ? ORDER BY created_at DESC LIMIT 1",
            (pattern,)
        ).fetchone()
        
        if result and result["gelation_id"]:
            # Extract sequence number (last part after last -)
            gel_id = result["gelation_id"]
            parts = gel_id.split("-")
            if len(parts) > 0 and parts[-1].isdigit():
                return int(parts[-1]) + 1
        return 1
    except Exception:
        return 1
    finally:
        conn.close()

def generate_plate_id(plate_type: str = "96", sequence: int = None) -> str:
    """
    Auto-generate plate_id for physical plates.
    
    Format: P{type}-{YYMM}-{seq}
    
    Examples:
    - P96-2510-001 (first 96-well plate in Oct 2025)
    - P96-2510-002 (second 96-well plate)
    - P48-2510-001 (first 48-well plate)
    
    Physical plates can be reused across:
    - Different days (same plate, different experiments)
    - Different batches (same plate, different ECM sources)
    - Different gelations (same plate, different protocols)
    
    The well position (row, col) distinguishes individual samples.
    """
    # Extract plate type from common patterns
    if not plate_type:
        plate_type = "96"
    elif "-" in str(plate_type):
        # Extract from existing format like "PLT-001-96"
        parts = str(plate_type).split("-")
        for part in parts:
            if part in ["6", "12", "24", "48", "96", "384"]:
                plate_type = part
                break
    
    # Month code (YYMM)
    month_code = datetime.now().strftime("%y%m")
    
    # Get next sequence if not provided
    if sequence is None:
        sequence = get_next_plate_sequence(plate_type, month_code)
    
    return f"P{plate_type}-{month_code}-{sequence:03d}"

def get_next_plate_sequence(plate_type: str, month_code: str) -> int:
    """Get next plate sequence number for a given type and month."""
    pattern = f"P{plate_type}-{month_code}-%"
    
    conn = get_connection()
    try:
        result = conn.execute(
            "SELECT plate_id FROM wells_master_v4 WHERE plate_id LIKE ? ORDER BY created_at DESC LIMIT 1",
            (pattern,)
        ).fetchone()
        
        if result and result["plate_id"]:
            # Extract sequence (last 3 digits)
            plate_id = result["plate_id"]
            parts = plate_id.split("-")
            if len(parts) >= 3 and parts[-1].isdigit():
                return int(parts[-1]) + 1
        return 1
    except Exception:
        return 1
    finally:
        conn.close()

def get_recent_plates(limit: int = 50) -> list:
    """Get list of recently used plate_ids with usage stats."""
    conn = get_connection()
    try:
        result = conn.execute("""
            SELECT 
                plate_id,
                COUNT(*) as n_wells,
                MIN(date) as first_use,
                MAX(date) as last_use,
                COUNT(DISTINCT batch_id) as n_batches,
                COUNT(DISTINCT gelation_id) as n_gelations
            FROM wells_master_v4
            WHERE plate_id IS NOT NULL AND plate_id != ''
            GROUP BY plate_id
            ORDER BY MAX(created_at) DESC
            LIMIT ?
        """, (limit,)).fetchall()
        
        return [dict(row) for row in result]
    except Exception:
        return []
    finally:
        conn.close()

def generate_semantic_id(family: str, batch_id: str, plate_id: Optional[str] = None,
                        row: Optional[str] = None, col: Optional[int] = None, 
                        replicate_id: Optional[int] = None,
                        species: Optional[str] = None, tissue: Optional[str] = None) -> str:
    """
    Generate human-readable record ID from metadata.
    
    Format: {family}_{batch_id}_{species-tissue}_{plate_id}_{row}{col}_rep{replicate_id}
    
    Examples:
    - Pure collagen: collagen_B001_human-mammary_PLT-001-96_A1_rep1
    - decECM: dececm_B002_porcine-dermis_PLT-002-48_A1_rep1
    - No plate: collagen_B001_human-mammary_A1_rep1
    - No position: collagen_B001_human-mammary_rep1
    """
    parts = []
    
    # Clean and add family (remove spaces, lowercase)
    if family:
        family_clean = family.replace(" ", "").replace("_", "").lower()
        parts.append(family_clean)
    
    # Add batch (clean)
    if batch_id:
        batch_clean = batch_id.replace(" ", "")
        parts.append(batch_clean)
    
    # Add species-tissue for decECM (improves traceability)
    if family and family.lower() == "dececm" and species and tissue:
        species_clean = species.replace(" ", "").lower()
        tissue_clean = tissue.replace(" ", "-").lower()
        parts.append(f"{species_clean}-{tissue_clean}")
    
    # Add plate (optional, clean)
    if plate_id:
        plate_clean = plate_id.replace(" ", "")
        parts.append(plate_clean)
    
    # Add position (row+col)
    if row and col is not None:
        parts.append(f"{row}{col}")
    
    # Add replicate
    if replicate_id is not None:
        parts.append(f"rep{replicate_id}")
    
    # Join with underscores
    semantic_id = "_".join(parts)
    
    # Fallback to UUID if too short
    if len(semantic_id) < 5:
        return new_record_id()
    
    return semantic_id

def ensure_unique_record_id(proposed_id: str, attempt: int = 0) -> str:
    """
    Ensure record ID is unique. If collision, append suffix.
    
    Args:
        proposed_id: Proposed record ID
        attempt: Collision counter (0 = first attempt)
    
    Returns:
        Unique record ID
    """
    test_id = proposed_id if attempt == 0 else f"{proposed_id}_v{attempt}"
    
    # Check if exists
    conn = get_connection()
    try:
        exists = conn.execute(
            "SELECT 1 FROM wells_master_v4 WHERE record_id=? LIMIT 1",
            (test_id,)
        ).fetchone()
        
        if exists:
            # Collision! Try next version
            return ensure_unique_record_id(proposed_id, attempt + 1)
        else:
            return test_id
    finally:
        conn.close()

def _parse_manual_well_tokens(text: str, row_labels: str, max_cols: int) -> List[Tuple[str, int]]:
    """
    Parse free-form well tokens into [(row_letter, col_int)].
    Supports tokens like 'A2', 'B6', 'A1-A3', 'C4:C6'.
    - Separators: comma, space, semicolon, newline
    - Ignores invalid or duplicate entries gracefully
    """
    if not text:
        return []

    # Normalize separators
    raw = text.replace(";", ",").replace("\n", ",").replace("\t", ",")
    tokens = [t.strip().upper() for t in raw.split(",") if t.strip()]

    def _is_valid(row, col):
        return (row in row_labels) and (isinstance(col, int) and 1 <= col <= int(max_cols))

    seen = set()
    picks = []

    for tok in tokens:
        # Range syntax: A1-A3 or A1:A3
        if "-" in tok or ":" in tok:
            sep = "-" if "-" in tok else ":"
            try:
                left, right = tok.split(sep, 1)
                # both endpoints must look like <Letter><Number>
                def split_rc(s):
                    s = s.strip().upper()
                    r = "".join([c for c in s if c.isalpha()])
                    c = "".join([c for c in s if c.isdigit()])
                    return r, int(c)
                r1, c1 = split_rc(left)
                r2, c2 = split_rc(right)
                if r1 == r2 and r1 in row_labels:
                    lo, hi = sorted([c1, c2])
                    for c in range(lo, hi + 1):
                        if _is_valid(r1, c):
                            key = (r1, c)
                            if key not in seen:
                                seen.add(key); picks.append(key)
                # out-of-scope: row ranges; ignore silently
            except Exception:
                # ignore malformed range
                pass
            continue

        # Single well syntax: A2
        letters = "".join([c for c in tok if c.isalpha()])
        digits  = "".join([c for c in tok if c.isdigit()])
        if letters and digits:
            try:
                r = letters[0]   # first letter; ignore extras
                c = int(digits)
                if _is_valid(r, c):
                    key = (r, c)
                    if key not in seen:
                        seen.add(key); picks.append(key)
            except Exception:
                pass
        # If token is just a row like "A" or just a number like "5", we skip.
        # (Keeps the parser predictable and avoids accidental floods.)

    # Sort in plate order (row order, then col) for reproducibility
    row_index = {ch: i for i, ch in enumerate(row_labels)}
    picks.sort(key=lambda rc: (row_index.get(rc[0], 1e9), rc[1]))
    return picks

def sqlite_supports_generated_columns() -> bool:
    """Check if SQLite version supports GENERATED columns (3.31.0+)."""
    try:
        v = _sqlite3.sqlite_version_info  # (major, minor, patch)
        return (v[0], v[1], v[2]) >= (3, 31, 0)
    except Exception:
        return False

def column_exists(con, table_name, column_name):
    """Check if a column exists in a table."""
    cursor = con.execute(f"PRAGMA table_info({table_name})")
    columns = [row[1] for row in cursor.fetchall()]
    return column_name in columns

def apply_migrations():
    """Run database migrations based on PRAGMA user_version."""
    with tx() as con:
        user_version = con.execute("PRAGMA user_version").fetchone()[0]

        # v1: plate bounds trigger + useful indexes + audit table/trigger
        if user_version < 1:
            # Audit log table
            con.execute("""
            CREATE TABLE IF NOT EXISTS audit_log (
              id INTEGER PRIMARY KEY,
              table_name TEXT,
              record_id TEXT,
              action TEXT,
              actor TEXT,
              payload TEXT,
              changed_at TEXT DEFAULT CURRENT_TIMESTAMP
            )
            """)
            
            # Audit trigger for wells updates
            con.execute("""
            CREATE TRIGGER IF NOT EXISTS trg_wells_audit_update
            AFTER UPDATE ON wells_master_v4
            FOR EACH ROW BEGIN
              INSERT INTO audit_log(table_name, record_id, action, actor, payload)
              VALUES('wells_master_v4', NEW.record_id, 'UPDATE', COALESCE(NEW.operator_id,''), json_object(
                'old_updated_at', OLD.updated_at,
                'new_updated_at', NEW.updated_at,
                'old_gel_binary', OLD.gel_binary,
                'new_gel_binary', NEW.gel_binary
              ));
            END;
            """)
            
            con.execute("PRAGMA user_version=1")

        # v2: add UV ratio generated column if supported
        if user_version < 2:
            if sqlite_supports_generated_columns():
                # Check if column already exists
                cols = {r[1] for r in con.execute("PRAGMA table_info(wells_master_v4)")}
                if 'uv_ratio_gen' not in cols:
                    try:
                        con.execute("""
                        ALTER TABLE wells_master_v4
                        ADD COLUMN uv_ratio_gen REAL GENERATED ALWAYS AS (
                          CASE WHEN uv_A280 IS NOT NULL AND uv_A280 > 0
                               THEN uv_A220 / uv_A280 END
                        ) VIRTUAL
                        """)
                    except Exception:
                        pass  # If fails, continue without generated column
            con.execute("PRAGMA user_version=2")
        
        # v3: images table for per-well/per-event uploads + indexes
        if user_version < 3:
            con.execute("""
            CREATE TABLE IF NOT EXISTS gel_images (
                image_id      TEXT PRIMARY KEY,
                record_id     TEXT NOT NULL REFERENCES wells_master_v4(record_id) ON DELETE CASCADE,
                event_id      INTEGER REFERENCES events_long(event_id) ON DELETE SET NULL,
                taken_at      TEXT,
                operator_id   TEXT,
                caption       TEXT,
                kind          TEXT,
                mime_type     TEXT,
                width_px      INTEGER,
                height_px     INTEGER,
                sha256_hex    TEXT,
                file_relpath  TEXT NOT NULL,
                thumb_relpath TEXT,
                lighting      TEXT,
                magnification TEXT,
                tilt_deg      REAL,
                qc_flag       INTEGER DEFAULT 1,
                created_at    TEXT DEFAULT CURRENT_TIMESTAMP
            )
            """)
            con.execute("CREATE INDEX IF NOT EXISTS idx_img_record ON gel_images(record_id)")
            con.execute("CREATE INDEX IF NOT EXISTS idx_img_event  ON gel_images(event_id)")
            con.execute("CREATE INDEX IF NOT EXISTS idx_img_hash   ON gel_images(sha256_hex)")
            con.execute("PRAGMA user_version=3")
        
        # v4: decECM provenance (species + tissue) + helper indexes
        if user_version < 4:
            if not column_exists(con, "wells_master_v4", "ecm_origin_species"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN ecm_origin_species TEXT")
            if not column_exists(con, "wells_master_v4", "ecm_source_tissue"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN ecm_source_tissue TEXT")
            con.execute("CREATE INDEX IF NOT EXISTS idx_wells_species ON wells_master_v4(ecm_origin_species)")
            con.execute("CREATE INDEX IF NOT EXISTS idx_wells_tissue  ON wells_master_v4(ecm_source_tissue)")
            con.execute("PRAGMA user_version=4")
        
        # v5: processing protocol (step-by-step ECM preparation tracking)
        if user_version < 5:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN processing_protocol TEXT")
            con.execute("PRAGMA user_version=5")
        
        # v6: gelation protocol (neutralization, incubation, post-gel handling)
        if user_version < 6:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN gelation_protocol TEXT")
            con.execute("PRAGMA user_version=6")
        
        # v7: protein assay method tracking
        if user_version < 7:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN protein_assay_method TEXT")
            con.execute("PRAGMA user_version=7")
        
        # v8: commercial product tracking
        if user_version < 8:
            if not column_exists(con, "wells_master_v4", "is_commercial_product"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN is_commercial_product INTEGER DEFAULT 0")
            if not column_exists(con, "wells_master_v4", "commercial_vendor"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_vendor TEXT")
            if not column_exists(con, "wells_master_v4", "commercial_product_name"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_product_name TEXT")
            if not column_exists(con, "wells_master_v4", "commercial_catalog_number"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_catalog_number TEXT")
            if not column_exists(con, "wells_master_v4", "commercial_lot_number"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_lot_number TEXT")
            con.execute("CREATE INDEX IF NOT EXISTS idx_wells_commercial ON wells_master_v4(is_commercial_product)")
            con.execute("CREATE INDEX IF NOT EXISTS idx_wells_vendor ON wells_master_v4(commercial_vendor)")
            con.execute("PRAGMA user_version=8")
        
        # v16: add commercial website field
        if user_version < 16:
            if not column_exists(con, "wells_master_v4", "commercial_website"):
                con.execute("ALTER TABLE wells_master_v4 ADD COLUMN commercial_website TEXT")
            con.execute("PRAGMA user_version=16")
        
        # v9: gelation_id for protocol-level tracking
        if user_version < 9:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN gelation_id TEXT")
            con.execute("CREATE INDEX IF NOT EXISTS idx_wells_gelation ON wells_master_v4(gelation_id)")
            con.execute("PRAGMA user_version=9")
        
        # v10: gel_volume_uL for spatial seeding height calculations
        if user_version < 10:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN gel_volume_uL REAL CHECK(gel_volume_uL > 0)")
            con.execute("PRAGMA user_version=10")
        
        # v11: add degradation and plate adhesion fields
        if user_version < 11:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN disintegrated INTEGER CHECK(disintegrated IN (0,1))")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN days_to_disintegration INTEGER CHECK(days_to_disintegration >= 0)")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN reliquefied INTEGER CHECK(reliquefied IN (0,1))")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN days_to_reliquefaction INTEGER CHECK(days_to_reliquefaction >= 0)")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN plate_adhesion TEXT CHECK(plate_adhesion IN ('adhered','floating','mixed'))")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN adhesion_notes TEXT")
            con.execute("PRAGMA user_version=11")
        
        # v12: add gelation kinetics and pre-gelation storage fields
        if user_version < 12:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN time_to_gel_min REAL CHECK(time_to_gel_min >= 0)")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_gel_storage_temp_C REAL CHECK(pre_gel_storage_temp_C BETWEEN -80 AND 40)")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_gel_storage_duration_min REAL CHECK(pre_gel_storage_duration_min >= 0)")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_gel_storage_notes TEXT")
            con.execute("PRAGMA user_version=12")
        
        # v13: Enhanced pre-storage tracking (freezer temp, frozen duration)
        if user_version < 13:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_temp_freezer REAL CHECK(pre_storage_temp_freezer BETWEEN -200 AND 0)")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_duration_months REAL CHECK(pre_storage_duration_months >= 0)")
            con.execute("PRAGMA user_version=13")
        
        # v14: Detailed pre-storage freeze-thaw tracking
        if user_version < 14:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_fresh_notes TEXT")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_frozen_in TEXT")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_thaw_method TEXT")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_thaw_duration_min REAL CHECK(pre_storage_thaw_duration_min >= 0)")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN pre_storage_ft_notes TEXT")
            con.execute("PRAGMA user_version=14")
        
        # v15: Hydrogel blend functionality
        if user_version < 15:
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN hydrogel_blend_components TEXT")
            con.execute("ALTER TABLE wells_master_v4 ADD COLUMN multiple_hydrogels INTEGER DEFAULT 0 CHECK(multiple_hydrogels IN (0,1))")
            con.execute("PRAGMA user_version=15")

def check_schema_drift(spec):
    """
    Compare FIELD_SPEC against actual SQLite schema.
    Returns list of drift warnings.
    """
    problems = []
    conn = get_connection()
    try:
        for table in spec.keys():
            try:
                # Get actual columns from database
                cols_query = conn.execute(f"PRAGMA table_info({table})").fetchall()
                db_fields = {row[1] for row in cols_query}
                spec_fields = set(spec[table].keys())
                
                # Find drift
                missing_in_db = spec_fields - db_fields
                extra_in_db = db_fields - spec_fields
                
                if missing_in_db:
                    problems.append(f"{table}: Fields in spec but not DB: {sorted(missing_in_db)}")
                if extra_in_db:
                    # Filter out common system columns
                    extra_filtered = extra_in_db - {'created_at', 'updated_at', 'reagent_id', 'event_id'}
                    if extra_filtered:
                        problems.append(f"{table}: Fields in DB but not spec: {sorted(extra_filtered)}")
            except Exception as e:
                # Table might not exist yet
                continue
    finally:
        conn.close()
    
    return problems

def init_database():
    with tx() as con:
        # Set DB identity tag (enforces "lab_hydrogels" purpose)
        from db_utils import ensure_db_identity
        ensure_db_identity(con, "lab_hydrogels")
        
        # wells_master_v4
        con.execute("""
        CREATE TABLE IF NOT EXISTS wells_master_v4 (
            record_id TEXT PRIMARY KEY,
            date TEXT NOT NULL,
            operator_id TEXT,
            family TEXT,
            batch_id TEXT,
            donor_id TEXT,
            plate_id TEXT,
            row TEXT,
            col INTEGER,
            replicate_id INTEGER,

            pre_storage_days_4C INTEGER,
            pre_storage_freeze_cycles INTEGER,

            ecm_total_protein_mgml REAL CHECK(ecm_total_protein_mgml >= 0),
            pre_pH REAL CHECK(pre_pH BETWEEN 0 AND 14),
            pre_conductivity_mS REAL,
            temp_incubation_C REAL CHECK(temp_incubation_C BETWEEN 0 AND 60),

            uv_A220 REAL,
            uv_A230 REAL,
            uv_A260 REAL,
            uv_A280 REAL,
            uv_ratio_A220_A280 REAL,

            sds_smear_index REAL CHECK(sds_smear_index BETWEEN 0 AND 1),
            sds_alpha_ratio REAL,

            hydroxyproline_mgml REAL,
            dmmB_GAG_ugml REAL,
            viscosity_proxy_sec REAL,

            -- Pre-gel viscosity (Scientific Reports 2019)
            pre_gel_viscosity_mPas REAL CHECK(pre_gel_viscosity_mPas >= 0),
            viscosity_pregel_mPas REAL CHECK(viscosity_pregel_mPas >= 0),
            pre_gel_viscosity_temp_C REAL CHECK(pre_gel_viscosity_temp_C BETWEEN 0 AND 40),
            shear_rate_s_minus1 REAL CHECK(shear_rate_s_minus1 >= 0),

            -- Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021)
            turbidity_lag_time_min REAL CHECK(turbidity_lag_time_min >= 0),
            turbidity_t_half_min REAL CHECK(turbidity_t_half_min >= 0),
            turbidity_slope_per_min REAL,

            -- Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015)
            storage_modulus_G_prime_Pa REAL CHECK(storage_modulus_G_prime_Pa >= 0),
            loss_modulus_G_double_prime_Pa REAL CHECK(loss_modulus_G_double_prime_Pa >= 0),
            tan_delta REAL CHECK(tan_delta >= 0),

            -- Residual contaminants (cornea ECM study 2019)
            sds_residual_ppm REAL CHECK(sds_residual_ppm >= 0),
            residual_SDS REAL CHECK(residual_SDS >= 0),
            detergent_residual_binary INTEGER CHECK(detergent_residual_binary IN (0,1)),
            cytotoxicity_score_0to3 INTEGER CHECK(cytotoxicity_score_0to3 BETWEEN 0 AND 3),

            -- Micro-DSC parameters (optional)
            dsc_onset_T_C REAL CHECK(dsc_onset_T_C BETWEEN 0 AND 100),
            dsc_peak_T_C REAL CHECK(dsc_peak_T_C BETWEEN 0 AND 100),
            dsc_delta_H_J_g REAL CHECK(dsc_delta_H_J_g >= 0),

            -- Circular Dichroism parameters (optional)
            cd_molar_ellipticity_222nm_mdeg REAL,
            cd_helix_percent REAL CHECK(cd_helix_percent BETWEEN 0 AND 100),

            -- FTIR parameters (optional)
            ftir_amide3_1450_ratio REAL CHECK(ftir_amide3_1450_ratio >= 0),

            -- Additional residual contaminants (optional)
            dna_residual_ng_mg REAL CHECK(dna_residual_ng_mg >= 0),
            endotoxin_residual_EU_mg REAL CHECK(endotoxin_residual_EU_mg >= 0),
            protease_residual_U_mg REAL CHECK(protease_residual_U_mg >= 0),

            -- Swelling ratio parameters (optional)
            swelling_ratio_Q REAL CHECK(swelling_ratio_Q >= 0),
            gel_fresh_weight_mg REAL CHECK(gel_fresh_weight_mg >= 0),
            gel_swollen_weight_mg REAL CHECK(gel_swollen_weight_mg >= 0),
            gel_dry_weight_mg REAL CHECK(gel_dry_weight_mg >= 0),

            -- Enzymatic degradation parameters (optional)
            enzymatic_degradation_t_half_min REAL CHECK(enzymatic_degradation_t_half_min >= 0),
            collagenase_concentration_U_mL REAL CHECK(collagenase_concentration_U_mL >= 0),

            -- Diffusion/FRAP parameters (optional)
            diffusion_coefficient_um2_s REAL CHECK(diffusion_coefficient_um2_s >= 0),
            frap_t_half_s REAL CHECK(frap_t_half_s >= 0),
            probe_radius_um REAL CHECK(probe_radius_um >= 0),

            -- Cell viability/proliferation parameters (optional)
            cell_viability_percent REAL CHECK(cell_viability_percent BETWEEN 0 AND 100),
            doubling_time_h REAL CHECK(doubling_time_h >= 0),
            viability_assay_type TEXT,

            -- Morphology/branching parameters (optional)
            branch_points_per_mm2 REAL CHECK(branch_points_per_mm2 >= 0),
            lumen_formation_binary INTEGER CHECK(lumen_formation_binary IN (0,1)),
            morphology_assay_type TEXT,

            -- Gel contraction parameters (optional)
            contraction_percent REAL CHECK(contraction_percent BETWEEN 0 AND 100),
            contraction_time_h REAL CHECK(contraction_time_h >= 0),
            initial_gel_area_mm2 REAL CHECK(initial_gel_area_mm2 >= 0),
            final_gel_area_mm2 REAL CHECK(final_gel_area_mm2 >= 0),

            -- Migration parameters (optional)
            migration_speed_um_h REAL CHECK(migration_speed_um_h >= 0),
            persistence_ratio REAL CHECK(persistence_ratio >= 0),
            migration_assay_type TEXT,

            -- Marker expression parameters (optional)
            alpha_sma_percent REAL CHECK(alpha_sma_percent BETWEEN 0 AND 100),
            col1a1_percent REAL CHECK(col1a1_percent BETWEEN 0 AND 100),
            muc1_percent REAL CHECK(muc1_percent BETWEEN 0 AND 100),
            ck18_percent REAL CHECK(ck18_percent BETWEEN 0 AND 100),
            marker_assay_type TEXT,
            markers_json TEXT,

            probe_type TEXT,
            target_pH REAL CHECK(target_pH BETWEEN 0 AND 14),

            -- Kinetics
            od_wavelength_nm INTEGER,
            od_sampling_interval_min INTEGER,
            time_to_halfmax_min REAL,
            slope_OD_per_min REAL,
            final_OD REAL,
            lag_time_min REAL,

            -- Outcomes
            gel_binary INTEGER CHECK(gel_binary IN (0,1)),
            gel_strength_score_0to3 INTEGER CHECK(gel_strength_score_0to3 BETWEEN 0 AND 3),
            tilt_test_angle_deg REAL,
            time_to_handle_min REAL,

            -- Failure/QC
            failure_mode TEXT,
            suspected_cause TEXT,
            confidence_0to1 REAL,
            syneresis_binary INTEGER,
            syneresis_time_min REAL,
            precipitate_binary INTEGER,
            color_shift TEXT,

            notes_pre TEXT,
            notes_post TEXT,

            -- App preds (optional)
            app_recipe_recommended TEXT,
            app_pgel_pred REAL,
            app_thalf_pred_min REAL,
            app_uncertainty REAL,
            counterfactual_recipe TEXT,
            counterfactual_expected_pgel REAL,

            split TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP,
            updated_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
        """)

        # reagents_per_well (normalized "stock + volume")
        con.execute("""
        CREATE TABLE IF NOT EXISTS reagents_per_well (
            reagent_id INTEGER PRIMARY KEY AUTOINCREMENT,
            record_id TEXT NOT NULL REFERENCES wells_master_v4(record_id) ON DELETE CASCADE,
            reagent_name TEXT NOT NULL,
            reagent_class TEXT,
            purpose TEXT,
            stock_conc_value REAL,
            stock_conc_units TEXT, -- M|mM|µM|%|x|mg/mL|U/mL
            volume_uL_per_mL REAL,
            effective_conc_mM REAL,
            lot_number TEXT,
            added_order INTEGER,
            notes TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
        """)

        # events_long (longitudinal observations)
        con.execute("""
        CREATE TABLE IF NOT EXISTS events_long (
            event_id INTEGER PRIMARY KEY AUTOINCREMENT,
            record_id TEXT NOT NULL REFERENCES wells_master_v4(record_id) ON DELETE CASCADE,
            event_type TEXT NOT NULL,
            time_from_mix_hours REAL,
            time_point_min REAL,
            day_from_mix INTEGER,
            timestamp TEXT,
            status_code TEXT,
            measurement_type TEXT,
            measurement_value REAL,
            measurement_units TEXT,
            gel_strength_score_0to3 REAL,
            tilt_test_angle_deg REAL,
            observation TEXT,
            operator_id TEXT,
            notes_event TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
        """)

        # plates_registry (stores per-plate geometry & notes)
        con.execute("""
        CREATE TABLE IF NOT EXISTS plates_registry (
            plate_id TEXT PRIMARY KEY,
            row_labels TEXT NOT NULL,   -- e.g., 'ABCDEFGH'
            max_cols INTEGER NOT NULL,  -- e.g., 12
            description TEXT,
            created_at TEXT DEFAULT CURRENT_TIMESTAMP,
            updated_at TEXT DEFAULT CURRENT_TIMESTAMP
        )
        """)

        # Helpful indices (performance-optimized)
        con.execute("CREATE INDEX IF NOT EXISTS idx_wells_batch ON wells_master_v4(batch_id)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_wells_family ON wells_master_v4(family)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_wells_created ON wells_master_v4(created_at)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_wells_batch_gel ON wells_master_v4(batch_id, gel_binary)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_wells_date ON wells_master_v4(date)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_wells_plate_pos ON wells_master_v4(plate_id, row, col)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_rg_record ON reagents_per_well(record_id)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_ev_record ON events_long(record_id)")
        con.execute("CREATE INDEX IF NOT EXISTS idx_plates_updated ON plates_registry(updated_at)")

def ensure_triggers():
    with tx() as con:
        # Auto-update timestamps
        con.execute("""
        CREATE TRIGGER IF NOT EXISTS trg_wells_touch_updated
        AFTER UPDATE ON wells_master_v4
        FOR EACH ROW BEGIN
          UPDATE wells_master_v4 SET updated_at = datetime('now') WHERE record_id = NEW.record_id;
        END;
        """)
        con.execute("""
        CREATE TRIGGER IF NOT EXISTS trg_plates_touch_updated
        AFTER UPDATE ON plates_registry
        FOR EACH ROW BEGIN
          UPDATE plates_registry SET updated_at = datetime('now') WHERE plate_id = NEW.plate_id;
        END;
        """)
        
        # Enforce plate geometry bounds at DB level
        con.execute("""
        CREATE TRIGGER IF NOT EXISTS trg_wells_plate_bounds
        BEFORE INSERT ON wells_master_v4
        FOR EACH ROW
        WHEN NEW.plate_id IS NOT NULL
        BEGIN
          -- Validate row is in plate's row_labels
          SELECT CASE
            WHEN (NEW.row IS NOT NULL) AND (
              INSTR((SELECT row_labels FROM plates_registry WHERE plate_id = NEW.plate_id), NEW.row) = 0
            ) THEN RAISE(ABORT, 'Row not valid for this plate')
          END;
          
          -- Validate column is within bounds
          SELECT CASE
            WHEN (NEW.col IS NOT NULL) AND (
              NEW.col < 1 OR NEW.col > (SELECT max_cols FROM plates_registry WHERE plate_id = NEW.plate_id)
            ) THEN RAISE(ABORT, 'Column out of bounds for this plate')
          END;
        END;
        """)
        
        # Canonicalize row to uppercase and validate replicate_id
        con.execute("""
        CREATE TRIGGER IF NOT EXISTS trg_wells_canonicalize
        BEFORE INSERT ON wells_master_v4
        FOR EACH ROW
        BEGIN
          -- Ensure replicate_id >= 1
          SELECT CASE WHEN NEW.replicate_id IS NOT NULL AND CAST(NEW.replicate_id AS INTEGER) < 1
            THEN RAISE(ABORT, 'replicate_id must be >= 1')
          END;
        END;
        """)

def ensure_views():
    """Create enhanced views with fallback for UV ratio and rich derived features."""
    with tx() as con:
        # Basic ionic aggregation (backwards compatible)
        con.execute("""
        CREATE VIEW IF NOT EXISTS v_wells_effective AS
        WITH eff AS (
          SELECT
            record_id,
            SUM(CASE WHEN LOWER(reagent_name)='naoh'  THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaOH_mM,
            SUM(CASE WHEN LOWER(reagent_name)='hcl'   THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_HCl_mM,
            SUM(CASE WHEN LOWER(reagent_name)='nacl'  THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaCl_mM,
            SUM(CASE WHEN LOWER(reagent_name)='cacl2' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_CaCl2_mM
          FROM reagents_per_well
          GROUP BY record_id
        )
        SELECT w.*,
               e.eff_NaOH_mM, e.eff_HCl_mM, e.eff_NaCl_mM, e.eff_CaCl2_mM
        FROM wells_master_v4 w
        LEFT JOIN eff e USING(record_id);
        """)

        # Drop and recreate v_wells_features to account for UV ratio fallback
        con.execute("DROP VIEW IF EXISTS v_wells_features")

        # Check if uv_ratio_gen exists (from generated column migration)
        cols = {r[1] for r in con.execute("PRAGMA table_info(wells_master_v4)")}
        uv_ratio_expr = "uv_ratio_gen" if "uv_ratio_gen" in cols else """
            CASE WHEN uv_A280 IS NOT NULL AND uv_A280 > 0 THEN uv_A220 / uv_A280 END
        """

        con.execute(f"""
        CREATE VIEW v_wells_features AS
        WITH media AS (
          SELECT record_id,
                 SUM(CASE
                       WHEN LOWER(reagent_class)='media'
                         OR LOWER(reagent_name) LIKE '%dmem%'
                       THEN COALESCE(volume_uL_per_mL,0)/10.0
                       ELSE 0
                     END) AS media_percent
          FROM reagents_per_well GROUP BY record_id
        ),
        pbs AS (
          SELECT record_id,
                 MAX(1 + (COALESCE(stock_conc_value,1)-1.0)*COALESCE(volume_uL_per_mL,0)/1000.0) AS pbs_final_x
          FROM reagents_per_well
          WHERE LOWER(reagent_name) LIKE '%pbs%' AND stock_conc_units='x'
          GROUP BY record_id
        ),
        eff AS (
          SELECT
            record_id,
            SUM(CASE WHEN LOWER(reagent_name)='naoh'  THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaOH_mM,
            SUM(CASE WHEN LOWER(reagent_name)='hcl'   THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_HCl_mM,
            SUM(CASE WHEN LOWER(reagent_name)='nacl'  THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_NaCl_mM,
            SUM(CASE WHEN LOWER(reagent_name)='cacl2' THEN COALESCE(effective_conc_mM,0) ELSE 0 END) AS eff_CaCl2_mM
          FROM reagents_per_well
          GROUP BY record_id
        )
        SELECT
          w.*,
          {uv_ratio_expr} AS uv_ratio_effective,
          e.eff_NaOH_mM, e.eff_HCl_mM, e.eff_NaCl_mM, e.eff_CaCl2_mM,
          m.media_percent,
          p.pbs_final_x
        FROM wells_master_v4 w
        LEFT JOIN eff   e USING(record_id)
        LEFT JOIN media m USING(record_id)
        LEFT JOIN pbs   p USING(record_id);
        """)

# ============================================================================
# PLATE GEOMETRY REGISTRY
# ============================================================================

DEFAULT_PLATES = {
    "96":  dict(row_labels="ABCDEFGH", max_cols=12, description="96-well (8x12)"),
    "48":  dict(row_labels="ABCDEF",   max_cols=8,  description="48-well (6x8)"),
    "24":  dict(row_labels="ABCD",     max_cols=6,  description="24-well (4x6)"),
}

@lru_cache(maxsize=256)
def _get_plate_geom_cached(plate_id: str):
    """Cached geometry lookup for performance."""
    conn = get_connection()
    try:
        df = pd.read_sql_query(
            "SELECT row_labels, max_cols FROM plates_registry WHERE plate_id=?",
            conn, params=(plate_id,))
        if df.empty: 
            return None
        return (str(df.iloc[0]["row_labels"]), int(df.iloc[0]["max_cols"]))
    finally:
        conn.close()

def get_plate_geometry(plate_id: str) -> Optional[Tuple[str, int]]:
    """Return (row_labels, max_cols) for a plate_id if registered, else None."""
    if not plate_id: 
        return None
    return _get_plate_geom_cached(plate_id)

def upsert_plate_geometry(plate_id: str, row_labels: str, max_cols: int, description: Optional[str] = None):
    """Insert or update a plate geometry with validation."""
    if not plate_id or not row_labels or not max_cols:
        raise ValueError("plate_id, row_labels, and max_cols are required.")
    
    # Clean and validate row labels
    rows_clean = "".join(ch for ch in row_labels.strip().upper() if ch.isalpha())
    if not rows_clean:
        raise ValueError("row_labels must contain letters (e.g., 'ABCDEFGH').")
    if len(set(rows_clean)) != len(rows_clean):
        raise ValueError("row_labels contains duplicate letters.")
    if max_cols < 1:
        raise ValueError("max_cols must be ≥ 1.")
    
    with tx() as con:
        con.execute("""
        INSERT INTO plates_registry (plate_id, row_labels, max_cols, description)
        VALUES (?, ?, ?, ?)
        ON CONFLICT(plate_id) DO UPDATE SET
          row_labels=excluded.row_labels,
          max_cols=excluded.max_cols,
          description=COALESCE(excluded.description, plates_registry.description),
          updated_at=datetime('now')
        """, (plate_id, rows_clean, int(max_cols), description))
    
    # Invalidate cache after update
    try:
        _get_plate_geom_cached.cache_clear()
    except Exception:
        pass

def ensure_default_plate_if_unset(plate_id: str):
    """
    If plate_id includes a recognizable size token ('96','48','24') and
    the plate isn't registered, register a sensible default.
    
    Uses regex to match standalone numbers (not S96BLOT, but PLT-96-001).
    """
    if not plate_id: 
        return
    if get_plate_geometry(plate_id): 
        return
    
    # Match standalone 96, 48, or 24 (with word boundaries)
    m = re.search(r'(?<!\d)(96|48|24)(?!\d)', plate_id)
    token = m.group(1) if m else None
    
    if token and token in DEFAULT_PLATES:
        meta = DEFAULT_PLATES[token]
        upsert_plate_geometry(plate_id, meta["row_labels"], meta["max_cols"], meta["description"])

# ============================================================================
# UNIT CONVERSION UTILITIES
# ============================================================================

UNIT_TO_M = {"M":1.0, "mM":1e-3, "µM":1e-6, "uM":1e-6, "%":None, "x":None, "mg/mL":None, "U/mL":None}

def effective_mM(stock_value, stock_units, vol_uL_per_mL):
    if stock_units not in UNIT_TO_M or UNIT_TO_M[stock_units] is None:
        return None
    M = (stock_value or 0.0) * UNIT_TO_M[stock_units]
    frac = (vol_uL_per_mL or 0.0) / 1000.0
    return M * frac * 1000.0

def pbs_final_x(stock_x, vol_uL_per_mL):
    if stock_x is None: return None
    return 1 + (stock_x - 1.0) * ( (vol_uL_per_mL or 0.0) / 1000.0 )

def dmem_final_percent(vol_uL_per_mL):
    if vol_uL_per_mL is None: return None
    return vol_uL_per_mL / 10.0

def validate_numeric_range(value, min_val, max_val, field_name):
    if value is not None and (value < min_val or value > max_val):
        return False, f"{field_name} must be between {min_val} and {max_val}"
    return True, ""

def _norm_lower(val):
    """Normalize string to lowercase, or None."""
    return None if val is None else str(val).strip().lower()

def sanitize_and_enrich_well_payload(data, reagents_list):
    # UV ratio compute
    try:
        a220, a280 = data.get('uv_A220'), data.get('uv_A280')
        if a220 is not None and a280 and a280 > 0 and not data.get('uv_ratio_A220_A280'):
            data['uv_ratio_A220_A280'] = float(a220) / float(a280)
    except Exception:
        pass
    
    # Normalize species/tissue (common aliases)
    sp = _norm_lower(data.get('ecm_origin_species'))
    ti = _norm_lower(data.get('ecm_source_tissue'))
    
    # Common species aliases
    map_species = {"pig": "porcine", "cow": "bovine"}
    if sp in map_species:
        data['ecm_origin_species'] = map_species[sp]
    
    # Normalize tissue (spaces → underscores)
    if ti and " " in ti:
        data['ecm_source_tissue'] = ti.replace(" ", "_")
    
    # Normalize blanks
    for k, v in list(data.items()):
        if v == "" or (isinstance(v, str) and v.strip() == ""):
            data[k] = None
    
    # Compute effective mM for reagents if convertible
    for r in (reagents_list or []):
        if r.get('effective_conc_mM') is None:
            r['effective_conc_mM'] = effective_mM(r.get('stock_conc_value'), r.get('stock_conc_units'), r.get('volume_uL_per_mL'))
    
    return data, reagents_list or []

# ============================================================================
# FIELD SPECIFICATION (SCHEMA-DRIVEN UI)
# ============================================================================
# Central source of truth for field metadata:
# - Labels, help text, units, ranges
# - Required flags, widget types
# - Options for selects
# Drives: UI rendering, validation, data dictionary export

FIELD_SPEC = {
    "wells_master_v4": {
        "record_id":  {"widget":"text",    "required":True,  "help":"UUID; auto-generated or custom"},
        "date":       {"widget":"date",    "required":True,  "help":"Experiment date"},
        "operator_id":{"widget":"text",    "required":True,  "help":"Initials or user ID"},
        "family":     {"widget":"select",  "required":True,  "options":"codebook.family", "help":"ECM family (collagen vs decECM vs others)"},
        "is_commercial_product": {"widget":"checkbox", "required":False, "help":"Check if this is a commercial/ready-made product (e.g., Matrigel, PureCol)"},
        "commercial_vendor":     {"widget":"text", "required":False, "help":"Company/Vendor name (e.g., Corning, Advanced BioMatrix, R&D Systems)"},
        "commercial_product_name": {"widget":"text", "required":False, "help":"Product name (e.g., Matrigel, Cultrex, PureCol, Geltrex)"},
        "commercial_catalog_number": {"widget":"text", "required":False, "help":"Catalog/Part number"},
        "commercial_lot_number": {"widget":"text", "required":False, "help":"Lot/Batch number from manufacturer"},
        "commercial_website":    {"widget":"text", "required":False, "help":"Company website URL (e.g., https://www.corning.com)"},
        "batch_id":   {"widget":"text",    "required":True,  "help":"ECM batch identifier (for commercial: use lot#; for lab-made: internal batch ID)"},
        "gelation_id": {"widget":"text",   "required":False, "help":"Unique gelation experiment ID (e.g., GEL-2025-001). Multiple gels can use same batch_id but different gelation_id for protocol variations"},
        "gel_volume_uL": {"widget":"number", "required":False, "range":(1.0, 5000.0), "help":"Total volume of hydrogel per well (μL). Used for spatial seeding height calculations in cell culture experiments"},
        "donor_id":   {"widget":"text",    "required":False, "help":"Optional donor identifier (typically N/A for commercial products)"},
        "ecm_origin_species": {"widget":"select","options":"codebook.species","help":"Source species (required for decECM)"},
        "ecm_source_tissue":  {"widget":"select","options":"codebook.tissues","help":"Source tissue/organ (required for decECM)"},
        "plate_id":   {"widget":"text",    "required":False, "help":"E.g. PLT-001-96 for auto-detection"},
        "row":        {"widget":"select",  "required":False, "options":"__rows_from_plate__", "help":"Row letter"},
        "col":        {"widget":"number",  "required":False,  "fmt":"int", "range":(1, 48), "help":"Column index (optional)"},
        "replicate_id":{"widget":"number", "required":False,  "fmt":"int", "range":(1, 999), "help":"Replicate tag (optional, defaults to 1)"},

        "pre_storage_days_4C":       {"widget":"number","fmt":"int","range":(0, 3650),"help":"Days at 4°C before processing"},
        "pre_storage_fresh_notes":   {"widget":"text","required":False,"help":"How was fresh tissue stored?"},
        "pre_storage_freeze_cycles": {"widget":"number","fmt":"int","range":(0, 1000),"help":"Freeze-thaw cycles before decell"},
        "pre_storage_temp_freezer":  {"widget":"number","fmt":"float","range":(-200.0, 0.0),"help":"Freezer temp (°C) if frozen"},
        "pre_storage_duration_months":{"widget":"number","fmt":"float","range":(0.0, 120.0),"help":"Months stored frozen"},
        "pre_storage_frozen_in":     {"widget":"text","required":False,"help":"What medium was tissue frozen in?"},
        "pre_storage_thaw_method":   {"widget":"select","required":False,"options":["passive_room_temp","37C_water_bath","4C_fridge","buffer_wash_series","PBS_series","gradual_temp_ramp","other"],"help":"How was tissue thawed?"},
        "pre_storage_thaw_duration_min": {"widget":"number","fmt":"float","range":(0.0, 1000.0),"help":"Duration of each thaw phase (minutes)"},
        "pre_storage_ft_notes":      {"widget":"text","required":False,"help":"Notes about freeze-thaw process"},
    
    # Hydrogel blend fields
    "hydrogel_blend_components": {"widget":"text","required":False,"help":"JSON string of hydrogel blend components"},
    "multiple_hydrogels":        {"widget":"checkbox","required":False,"help":"Whether multiple hydrogels are used"},
        
        "processing_protocol": {"widget":"text","required":False,"help":"JSON-encoded ECM preparation steps (decell, wash, delipid, enzyme, etc.)"},
        "gelation_protocol": {"widget":"text","required":False,"help":"JSON-encoded gelation steps (dilute, add reagents, incubate, post-gel handling)"},

        "ecm_total_protein_mgml": {
            "widget":"number","unit":"mg/mL","range":(0.0,100.0),"required":False,
            "help":"Total protein concentration (optional - can measure later)",
            "device":"Spectrophotometer (BCA or Bradford assay)",
            "method":"1. Dilute sample 1:10 in PBS\n2. Mix with BCA reagent (1:20)\n3. Incubate 30 min at 37°C\n4. Read at 562 nm\n5. Compare to BSA standard curve"
        },
        "protein_assay_method": {"widget":"select","options":["","BCA","Bradford","Lowry","DC_assay","A280","Biuret","other"],"help":"Method used to measure protein concentration"},
        "pre_pH": {
            "widget":"number","range":(0.0,14.0),"required":False,
            "help":"Pre-neutralization pH (optional - can measure later)",
            "device":"pH meter (calibrated with pH 4, 7, 10 buffers)",
            "method":"1. Calibrate meter with 3-point standards\n2. Rinse electrode with DI water\n3. Immerse in sample (≥2 mL)\n4. Wait for stable reading (~30 sec)\n5. Record pH to 0.01 precision"
        },
        "pre_conductivity_mS": {
            "widget":"number","unit":"mS/cm","range":(0.0,100.0),"required":False,
            "help":"Pre-conductivity (optional - can measure later)",
            "device":"Conductivity meter (calibrated with KCl standard)",
            "method":"1. Calibrate with 1.413 mS/cm KCl standard\n2. Rinse probe with DI water\n3. Immerse in sample\n4. Wait for stable reading\n5. Record in mS/cm"
        },
        "temp_incubation_C": {
            "widget":"number","unit":"°C","range":(0.0,60.0),"required":False,
            "help":"Incubation temperature",
            "device":"Calibrated incubator with temperature probe",
            "method":"Typical: 37°C (physiological) or 25°C (room temp)"
        },

        "uv_A220": {
            "widget":"number","range":(0.0,1e6),
            "help":"Absorbance at 220 nm",
            "device":"UV-Vis spectrophotometer (NanoDrop or plate reader)",
            "method":"1. Blank with PBS or digest buffer\n2. Load 2 µL sample (NanoDrop) or 200 µL (plate)\n3. Measure at 220 nm\n4. Record absorbance units"
        },
        "uv_A230": {"widget":"number","range":(0.0,1e6),"help":"Absorbance at 230 nm","device":"UV-Vis spectrophotometer"},
        "uv_A260": {"widget":"number","range":(0.0,1e6),"help":"Absorbance at 260 nm (DNA/RNA)","device":"UV-Vis spectrophotometer"},
        "uv_A280": {
            "widget":"number","range":(0.0,1e6),
            "help":"Absorbance at 280 nm (protein)",
            "device":"UV-Vis spectrophotometer (NanoDrop or plate reader)",
            "method":"Measure at 280 nm (aromatic amino acids)"
        },
        "uv_ratio_A220_A280":{"widget":"number","range":(0.0,50.0),"help":"Auto-computed if A220 & A280 provided"},

        "sds_smear_index": {"widget":"number","range":(0.0,1.0),"help":"SDS-PAGE smear index (0–1)"},
        "sds_alpha_ratio": {"widget":"number","range":(0.0,5.0),"help":"α-band ratio"},
        "hydroxyproline_mgml": {"widget":"number","range":(0.0,50.0),"unit":"mg/mL","required":False,"help":"Hydroxyproline content (optional)"},
        "dmmB_GAG_ugml": {"widget":"number","range":(0.0,1e6),"unit":"µg/mL","required":False,"help":"GAG content (DMMB assay) (optional)"},
        "viscosity_proxy_sec": {"widget":"number","range":(0.0,1e6),"unit":"sec","required":False,"help":"Viscosity proxy measurement (optional)"},

        # Pre-gel viscosity (Scientific Reports 2019)
        "pre_gel_viscosity_mPas": {
            "widget":"number","range":(0.0,1e6),"unit":"mPa·s","required":False,
            "help":"Pre-gel shear viscosity at ~15°C (Scientific Reports 2019) (optional)",
            "device":"Rotational rheometer (cone-and-plate, 1° cone) or Brookfield viscometer",
            "method":"1. Load cold ECM solution (≈4°C)\n2. Measure viscosity vs shear rate (0.1–100 s⁻¹)\n3. Result: Shear-thinning curve\n4. Higher low-shear viscosity → longer polymers → faster gelation\n5. Reference: Badylak group, Sci Rep 2019, TA Instruments AR2000"
        },
        "viscosity_pregel_mPas": {
            "widget":"number","range":(0.0,1e6),"unit":"mPa·s","required":False,
            "help":"Pre-gel viscosity (workflow naming) (optional)",
            "device":"Viscometer",
            "method":"Pre-gel QC stage measurement"
        },
        "pre_gel_viscosity_temp_C": {
            "widget":"number","range":(0.0,40.0),"unit":"°C","required":False,
            "help":"Temperature during viscosity measurement (optional)",
            "device":"Temperature-controlled rheometer",
            "method":"Measure at cold temperature (≈4°C) before warming"
        },
        "shear_rate_s_minus1": {
            "widget":"number","range":(0.0,1000.0),"unit":"s⁻¹","required":False,
            "help":"Shear rate during viscosity measurement (optional)",
            "device":"Rheometer",
            "method":"Typical range: 0.1–100 s⁻¹ for shear-thinning characterization"
        },

        # Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021)
        "turbidity_lag_time_min": {
            "widget":"number","range":(0.0,1000.0),"unit":"min","required":False,
            "help":"Turbidity lag time T_lag (Scientific Reports 2019) (optional)",
            "device":"96-well plate reader at 405–450 nm, 37°C incubation",
            "method":"1. 100 µL per well\n2. Record OD every 30 s for 1–2 h\n3. T_lag: time to 10% of max OD\n4. Shorter T_lag → faster fibril formation\n5. Reference: Polymers 2021 13(18):3113"
        },
        "turbidity_t_half_min": {
            "widget":"number","range":(0.0,1000.0),"unit":"min","required":False,
            "help":"Time to half-max turbidity T_1/2 (MDPI 2021) (optional)",
            "device":"96-well plate reader at 405–450 nm, 37°C incubation",
            "method":"T_1/2: time to half-max OD from turbidity curve"
        },
        "turbidity_slope_per_min": {
            "widget":"number","range":(-1000.0,1000.0),"unit":"/min","required":False,
            "help":"Turbidity slope S (MDPI 2021) (optional)",
            "device":"96-well plate reader at 405–450 nm, 37°C incubation",
            "method":"Slope: ΔOD/Δt at inflection point of turbidity curve"
        },

        # Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015)
        "storage_modulus_G_prime_Pa": {"widget":"number","range":(0.0,1e6),"unit":"Pa","required":False,"help":"Storage modulus G′ (Saldin et al. 2016) (optional)"},
        "loss_modulus_G_double_prime_Pa": {"widget":"number","range":(0.0,1e6),"unit":"Pa","required":False,"help":"Loss modulus G″ (Brazdaru et al. 2015) (optional)"},
        "tan_delta": {"widget":"number","range":(0.0,10.0),"required":False,"help":"Tan δ = G″/G′ (viscoelastic ratio) (optional)"},

        # Residual contaminants (cornea ECM study 2019)
        "sds_residual_ppm": {"widget":"number","range":(0.0,1000.0),"unit":"ppm","required":False,"help":"SDS residual concentration (cornea ECM study 2019) (optional)"},
        "residual_SDS": {"widget":"number","range":(0.0,1000.0),"unit":"ppm","required":False,"help":"SDS residual (workflow naming) (optional)"},
        "detergent_residual_binary": {"widget":"select","options":[0,1],"required":False,"help":"Detergent residual detected (0=no, 1=yes) (optional)"},
        "cytotoxicity_score_0to3": {"widget":"select","options":[0,1,2,3],"required":False,"help":"Cytotoxicity score 0-3 (cornea ECM study 2019) (optional)"},

        # Micro-DSC parameters (optional)
        "dsc_onset_T_C": {"widget":"number","range":(0.0,100.0),"unit":"°C","required":False,"help":"DSC onset temperature (collagen denaturation) (optional)"},
        "dsc_peak_T_C": {"widget":"number","range":(0.0,100.0),"unit":"°C","required":False,"help":"DSC peak temperature (optional)"},
        "dsc_delta_H_J_g": {"widget":"number","range":(0.0,1000.0),"unit":"J/g","required":False,"help":"DSC gelation enthalpy (optional)"},

        # Circular Dichroism parameters (optional)
        "cd_molar_ellipticity_222nm_mdeg": {"widget":"number","range":(-10000.0,10000.0),"unit":"mdeg","required":False,"help":"CD molar ellipticity at 222 nm (Shoulders & Raines 2009) (optional)"},
        "cd_helix_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"Triple-helix content percentage (optional)"},

        # FTIR parameters (optional)
        "ftir_amide3_1450_ratio": {"widget":"number","range":(0.0,10.0),"required":False,"help":"FTIR Amide III/1450 ratio (optional)"},

        # Additional residual contaminants (optional)
        "dna_residual_ng_mg": {"widget":"number","range":(0.0,1000.0),"unit":"ng/mg","required":False,"help":"DNA residual (PicoGreen fluorometry) (optional)"},
        "endotoxin_residual_EU_mg": {"widget":"number","range":(0.0,100.0),"unit":"EU/mg","required":False,"help":"Endotoxin residual (LAL assay) (optional)"},
        "protease_residual_U_mg": {"widget":"number","range":(0.0,1000.0),"unit":"U/mg","required":False,"help":"Protease residual (Azocasein/BAPNA assay) (optional)"},

        # Swelling ratio parameters (optional)
        "swelling_ratio_Q": {
            "widget":"number","range":(0.0,100.0),"required":False,
            "help":"Swelling ratio Q = (Wsw – Wd)/Wd (optional)",
            "device":"Analytical balance",
            "method":"1. Weigh gel fresh (Ws)\n2. Soak in PBS 24 h\n3. Blot & re-weigh (Wsw)\n4. Dry & weigh (Wd)\n5. Formula: Q = (Wsw – Wd)/Wd\n6. Higher Q → looser mesh → faster nutrient diffusion"
        },
        "gel_fresh_weight_mg": {"widget":"number","range":(0.0,10000.0),"unit":"mg","required":False,"help":"Fresh gel weight (optional)"},
        "gel_swollen_weight_mg": {"widget":"number","range":(0.0,10000.0),"unit":"mg","required":False,"help":"Swollen weight after 24h PBS (optional)"},
        "gel_dry_weight_mg": {"widget":"number","range":(0.0,10000.0),"unit":"mg","required":False,"help":"Dry weight after drying (optional)"},

        # Enzymatic degradation parameters (optional)
        "enzymatic_degradation_t_half_min": {
            "widget":"number","range":(0.0,10000.0),"unit":"min","required":False,
            "help":"Enzymatic degradation half-time (optional)",
            "device":"Incubator + mass/OD measurement",
            "method":"1. Incubate 100 µL gel with collagenase (0.1–1 U/mL) at 37°C\n2. Record mass/OD loss vs time\n3. Output: t₁/₂ (min)\n4. Reference: Wiseman et al., Biomaterials 2004 25:5013–21"
        },
        "collagenase_concentration_U_mL": {"widget":"number","range":(0.0,10.0),"unit":"U/mL","required":False,"help":"Collagenase concentration used (optional)"},

        # Diffusion/FRAP parameters (optional)
        "diffusion_coefficient_um2_s": {
            "widget":"number","range":(0.0,1000.0),"unit":"µm²/s","required":False,
            "help":"Diffusion coefficient D (optional)",
            "device":"Confocal microscope + FRAP setup",
            "method":"1. Embed 70 kDa FITC-dextran\n2. Bleach small ROI\n3. Monitor fluorescence recovery\n4. Output: D (µm²/s) = 0.224 r²/t₁/₂\n5. Reference: Sprague & McNally, Biophys J 2005 89:1891–1907"
        },
        "frap_t_half_s": {"widget":"number","range":(0.0,10000.0),"unit":"s","required":False,"help":"FRAP half-time (optional)"},
        "probe_radius_um": {"widget":"number","range":(0.0,100.0),"unit":"µm","required":False,"help":"Probe radius for FRAP calculation (optional)"},

        # Cell viability/proliferation parameters (optional)
        "cell_viability_percent": {
            "widget":"number","range":(0.0,100.0),"unit":"%","required":False,
            "help":"Cell viability percentage (optional)",
            "device":"Fluorescence microscope or plate reader",
            "method":"1. Live/Dead: calcein AM + EthD-1\n2. AlamarBlue: metabolic activity\n3. PrestoBlue: resazurin reduction\n4. Count viable vs total cells\n5. Calculate % viable"
        },
        "doubling_time_h": {
            "widget":"number","range":(0.0,1000.0),"unit":"h","required":False,
            "help":"Cell doubling time (optional)",
            "device":"Incubator + cell counting",
            "method":"1. Count cells at multiple time points\n2. Plot log(cell number) vs time\n3. Calculate doubling time from slope\n4. Formula: t_d = ln(2)/growth_rate"
        },
        "viability_assay_type": {"widget":"select","options":["Live/Dead","AlamarBlue","PrestoBlue","MTT","WST-1","other"],"required":False,"help":"Viability assay method used (optional)"},

        # Morphology/branching parameters (optional)
        "branch_points_per_mm2": {
            "widget":"number","range":(0.0,10000.0),"unit":"/mm²","required":False,
            "help":"Branch points per mm² (optional)",
            "device":"Confocal or brightfield microscope",
            "method":"1. Image cells in 3D\n2. Use ImageJ AnalyzeSkeleton plugin\n3. Quantify branch points\n4. Normalize by area\n5. Higher branching → better network formation"
        },
        "lumen_formation_binary": {"widget":"select","options":[0,1],"required":False,"help":"Lumen formation detected (0=no, 1=yes) (optional)"},
        "morphology_assay_type": {"widget":"select","options":["confocal","brightfield","phase_contrast","fluorescence","other"],"required":False,"help":"Imaging method used (optional)"},

        # Gel contraction parameters (optional)
        "contraction_percent": {
            "widget":"number","range":(0.0,100.0),"unit":"%","required":False,
            "help":"Gel contraction percentage (optional)",
            "device":"Camera + image analysis",
            "method":"1. Photograph gel disk at 0h & 24-72h\n2. Measure area change\n3. Formula: contraction % = (A₀ – At)/A₀ × 100\n4. Higher contraction → more myofibroblast activity or weaker matrix"
        },
        "contraction_time_h": {"widget":"number","range":(0.0,168.0),"unit":"h","required":False,"help":"Time point for contraction measurement (optional)"},
        "initial_gel_area_mm2": {"widget":"number","range":(0.0,10000.0),"unit":"mm²","required":False,"help":"Initial gel area (optional)"},
        "final_gel_area_mm2": {"widget":"number","range":(0.0,10000.0),"unit":"mm²","required":False,"help":"Final gel area (optional)"},

        # Migration parameters (optional)
        "migration_speed_um_h": {
            "widget":"number","range":(0.0,1000.0),"unit":"µm/h","required":False,
            "help":"Cell migration speed (optional)",
            "device":"Time-lapse microscopy",
            "method":"1. Track nuclei with TrackMate (ImageJ)\n2. Calculate displacement over time\n3. Speed = distance/time\n4. Higher speed → better migration"
        },
        "persistence_ratio": {
            "widget":"number","range":(0.0,1.0),"required":False,
            "help":"Migration persistence ratio (optional)",
            "device":"Time-lapse microscopy",
            "method":"1. Track cell trajectories\n2. Calculate net displacement vs total path length\n3. Persistence = net displacement / total path length\n4. Higher persistence → more directed migration"
        },
        "migration_assay_type": {"widget":"select","options":["time_lapse","scratch_assay","transwell","trackmate","manual_tracking","other"],"required":False,"help":"Migration assay method (optional)"},

        # Marker expression parameters (optional)
        "alpha_sma_percent": {
            "widget":"number","range":(0.0,100.0),"unit":"%","required":False,
            "help":"α-SMA positive cells percentage (optional)",
            "device":"Immunofluorescence microscope",
            "method":"1. Immunostain for α-SMA\n2. Count positive vs total cells\n3. Calculate % positive\n4. Higher % → more myofibroblast differentiation"
        },
        "col1a1_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"COL1A1 positive cells percentage (optional)"},
        "muc1_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"MUC1 positive cells percentage (optional)"},
        "ck18_percent": {"widget":"number","range":(0.0,100.0),"unit":"%","required":False,"help":"CK18 positive cells percentage (optional)"},
        "marker_assay_type": {"widget":"select","options":["immunostaining","qPCR","western_blot","flow_cytometry","other"],"required":False,"help":"Marker expression assay method (optional)"},
        "markers_json": {
            "widget":"textarea","required":False,
            "help":"Flexible marker storage as JSON (optional)",
            "device":"Various",
            "method":"Store any marker expression data as JSON: {\"marker1\": value, \"marker2\": value, ...}"
        },

        "probe_type": {"widget":"select","options":"codebook.probe_type","help":"Stimulus type"},
        "target_pH":  {"widget":"number","range":(0.0,14.0),"required":False,"help":"Target pH post-neutralization (optional)"},

        "od_wavelength_nm":        {"widget":"number","fmt":"int","range":(350,800),"help":"OD wavelength (nm)"},
        "od_sampling_interval_min":{"widget":"number","fmt":"int","range":(1,120),"help":"OD sampling interval (min)"},
        "time_to_halfmax_min":     {"widget":"number","range":(0.0,1e6),"help":"Time to 50% max stiffness"},
        "slope_OD_per_min":        {"widget":"number","range":(-1e9,1e9),"help":"OD slope (per min)"},
        "final_OD":                {"widget":"number","range":(0.0,10.0),"help":"Final OD value"},
        "lag_time_min":            {"widget":"number","range":(0.0,1e6),"help":"Lag time (min)"},

        "gel_binary":              {"widget":"select","options":[0,1],"required":False,"help":"1=gel formed; 0=no gel (optional - can observe later)"},
        "gel_strength_score_0to3": {"widget":"select","options":[0,1,2,3],"help":"Ordinal strength 0–3"},
        "tilt_test_angle_deg":     {"widget":"number","range":(0.0,90.0),"unit":"deg","help":"Tilt test angle"},
        "time_to_handle_min":      {"widget":"number","range":(0.0,1e6),"help":"Time until handleable"},

        "failure_mode":     {"widget":"select","options":"codebook.failure_mode","help":"Failure category if applicable"},
        "suspected_cause":  {"widget":"select","options":"codebook.suspected_cause","help":"Hypothesis for failure"},
        "confidence_0to1":  {"widget":"number","range":(0.0,1.0),"help":"Confidence in suspected cause"},
        "syneresis_binary": {"widget":"select","options":[0,1],"help":"1=syneresis observed"},
        "syneresis_time_min": {"widget":"number","range":(0.0,1e6),"help":"Time to syneresis onset (min)"},
        "precipitate_binary":{"widget":"select","options":[0,1],"help":"1=precipitate observed"},
        "color_shift":      {"widget":"select","options":"codebook.color_shift","help":"Observed color change"},
        
        "disintegrated": {"widget":"select","options":[0,1],"help":"1=gel broke apart into pieces"},
        "days_to_disintegration": {"widget":"number","fmt":"int","range":(0,1000),"help":"Days until gel disintegrated"},
        "reliquefied": {"widget":"select","options":[0,1],"help":"1=gel returned to liquid state"},
        "days_to_reliquefaction": {"widget":"number","fmt":"int","range":(0,1000),"help":"Days until gel became liquid again"},
        "plate_adhesion": {"widget":"select","options":["","adhered","floating","mixed"],"help":"Gel adherence to plate surface"},
        "adhesion_notes": {"widget":"text","help":"Details on adhesion (spontaneous vs induced, timing)"},
        
        "time_to_gel_min": {"widget":"number","range":(0.0,10000.0),"help":"Time for gel formation after adding reagents (minutes)"},
        "pre_gel_storage_temp_C": {"widget":"number","range":(-80.0,40.0),"help":"Storage temperature before adding gelation reagents (°C)"},
        "pre_gel_storage_duration_min": {"widget":"number","range":(0.0,100000.0),"help":"Duration ECM stored without reagents before gelation (minutes)"},
        "pre_gel_storage_notes": {"widget":"text","help":"Additional context about pre-gelation storage conditions"},

        "notes_pre":  {"widget":"textarea","help":"Pre-experiment notes"},
        "notes_post": {"widget":"textarea","help":"Post-experiment notes"},
        
        "app_recipe_recommended": {"widget":"textarea","help":"AI-recommended recipe"},
        "app_pgel_pred":          {"widget":"number","range":(0.0,1.0),"help":"AI-predicted P(gel)"},
        "app_thalf_pred_min":     {"widget":"number","range":(0.0,1e6),"help":"AI-predicted t½ (min)"},
        "app_uncertainty":        {"widget":"number","range":(0.0,1.0),"help":"AI prediction uncertainty"},
        "counterfactual_recipe":  {"widget":"textarea","help":"Counterfactual recipe"},
        "counterfactual_expected_pgel": {"widget":"number","range":(0.0,1.0),"help":"Expected P(gel) for counterfactual"},
        
        "split":      {"widget":"select","options":"codebook.split","help":"Train/validate/test split assignment"},
    },

    "reagents_per_well": {
        "record_id":        {"widget":"text","required":True,"help":"Foreign key to wells_master_v4"},
        "reagent_name":     {"widget":"text","required":True,"help":"Chemical or solution name"},
        "reagent_class":    {"widget":"select","options":["buffer","base","acid","salt","media","additive","enzyme","crosslinker","other"],"help":"Reagent category"},
        "purpose":          {"widget":"text","help":"E.g., neutralization, ionic_adjust"},
        "stock_conc_value": {"widget":"number","range":(0.0,1e9),"help":"Stock concentration numeric value"},
        "stock_conc_units": {"widget":"select","options":["M","mM","µM","%","x","mg/mL","U/mL"],"help":"Concentration units"},
        "volume_uL_per_mL": {"widget":"number","range":(0.0,1000.0),"unit":"µL/mL","help":"Volume added per mL of ECM"},
        "effective_conc_mM":{"widget":"number","range":(0.0,1e6),"unit":"mM","help":"Auto-computed if convertible"},
        "lot_number":       {"widget":"text","help":"Optional lot/batch number"},
        "added_order":      {"widget":"number","fmt":"int","range":(1,99),"help":"Addition sequence order"},
        "notes":            {"widget":"textarea","help":"Freeform notes"},
    },

    "events_long": {
        "record_id":         {"widget":"text","required":True,"help":"Foreign key to wells_master_v4"},
        "event_type":        {"widget":"select","options":["status","soften","liquefy","syneresis_onset","tilt_score","strength_score","OD_Reading","Other"],"required":True,"help":"Event category"},
        "time_point_min":    {"widget":"number","range":(0.0,1e7),"help":"Minutes from experiment start"},
        "time_from_mix_hours":{"widget":"number","range":(0.0,1e6),"help":"Hours from mixing"},
        "day_from_mix":      {"widget":"number","fmt":"int","range":(0,10000),"help":"Whole days from mixing"},
        "timestamp":         {"widget":"text","help":"ISO timestamp of observation"},
        "status_code":       {"widget":"select","options":"codebook.status_code","help":"Qualitative gel status"},
        "gel_strength_score_0to3":{"widget":"select","options":[0,1,2,3],"help":"Ordinal strength score"},
        "tilt_test_angle_deg":{"widget":"number","range":(0.0,90.0),"unit":"deg","help":"Tilt test angle"},
        "measurement_type":  {"widget":"text","help":"E.g., OD405, pH, viscosity"},
        "measurement_value": {"widget":"number","range":(-1e9,1e9),"help":"Numeric measurement value"},
        "measurement_units": {"widget":"text","help":"E.g., A.U., pH units"},
        "observation":       {"widget":"textarea","help":"Freeform observation notes"},
        "operator_id":       {"widget":"text","help":"Observer initials"},
        "notes_event":       {"widget":"textarea","help":"Event-specific notes"},
    },

    "plates_registry": {
        "plate_id":    {"widget":"text","required":True,"help":"Unique plate identifier"},
        "row_labels":  {"widget":"text","required":True,"help":"Letters e.g. ABCDEFGH"},
        "max_cols":    {"widget":"number","fmt":"int","range":(1, 48),"required":True,"help":"Number of columns"},
        "description": {"widget":"text","help":"Optional plate description"},
    }
}

# ============================================================================
# SCHEMA-DRIVEN UI UTILITIES
# ============================================================================

def _resolve_options(spec_entry, codebook, dynamic_rows=None):
    """Resolve options for a select widget from spec."""
    opts = spec_entry.get("options")
    if opts == "__rows_from_plate__":
        return list(dynamic_rows or "ABCDEFGH")
    if isinstance(opts, str) and opts.startswith("codebook."):
        # Extract field from codebook
        field = opts.split(".", 1)[1]
        return [""] + list(codebook.get(field, []))
    if isinstance(opts, (list, tuple)):
        # Direct list
        return [""] + list(opts) if "" not in opts else list(opts)
    return None

# ============================================================================
# COERCION HELPERS (schema-driven normalization)
# ============================================================================

_BOOLISH_TRUE = {"1", "true", "yes", "y", "t"}
_BOOLISH_FALSE = {"0", "false", "no", "n", "f"}

def _none_if_blank(v: Any) -> Any:
    """Convert blank/NaN values to None."""
    if v is None:
        return None
    if isinstance(v, str) and v.strip() == "":
        return None
    if isinstance(v, float) and pd.isna(v):
        return None
    return v

def _coerce_number(v: Any) -> Optional[float]:
    """Coerce to float, or None if invalid."""
    v = _none_if_blank(v)
    if v is None:
        return None
    try:
        return float(v)
    except (TypeError, ValueError):
        return None

def _coerce_int(v: Any) -> Optional[int]:
    """Coerce to int, or None if invalid. Accepts floats that are integral (e.g., 3.0)."""
    v = _none_if_blank(v)
    if v is None:
        return None
    try:
        f = float(v)
        i = int(f)
        return i if f == i else None
    except (TypeError, ValueError):
        return None

def _coerce_boolish(v: Any) -> Optional[int]:
    """Coerce boolean-ish values to 0/1."""
    v = _none_if_blank(v)
    if v is None:
        return None
    if isinstance(v, (int, float)):
        return 1 if int(v) != 0 else 0
    if isinstance(v, str):
        s = v.strip().lower()
        if s in _BOOLISH_TRUE:
            return 1
        if s in _BOOLISH_FALSE:
            return 0
    return None

def _coerce_date_iso(v: Any) -> Optional[str]:
    """Coerce to ISO date string (YYYY-MM-DD), or None."""
    v = _none_if_blank(v)
    if v is None:
        return None
    if isinstance(v, (datetime, date)):
        return v.strftime("%Y-%m-%d")
    if isinstance(v, str):
        s = v.strip()
        try:
            # Try strict ISO first
            return datetime.fromisoformat(s).date().strftime("%Y-%m-%d")
        except Exception:
            # Last-ditch: pandas parse
            try:
                return pd.to_datetime(s).date().strftime("%Y-%m-%d")
            except Exception:
                return None
    return None

def _resolve_allowed_options(meta: dict, codebook: dict) -> Optional[list]:
    """Resolve allowed options from FIELD_SPEC metadata."""
    opts = meta.get("options")
    if not opts:
        return None
    if isinstance(opts, str) and opts.startswith("codebook."):
        fld = opts.split(".", 1)[1]
        return list(codebook.get(fld, []))
    if isinstance(opts, (list, tuple)):
        return list(opts)
    return None

def _coerce_select(v: Any, allowed: Optional[list]) -> Any:
    """Coerce to one of the allowed options (case-insensitive match)."""
    v = _none_if_blank(v)
    if v is None or not allowed:
        return v
    # Accept case-insensitive matches
    if isinstance(v, str):
        for opt in allowed:
            if str(opt).lower() == v.lower():
                return opt
    # Direct containment
    return v if v in allowed else None

# Fields we always treat as boolean-ish integers (0/1)
_BOOLISH_FIELDS = {
    "gel_binary", "syneresis_binary", "precipitate_binary"
}

def coerce_payload(table: str, payload: Dict[str, Any], codebook: dict) -> Dict[str, Any]:
    """
    Coerce a payload into DB-safe shapes using FIELD_SPEC:
      - numbers → float
      - fmt=int → int
      - date → YYYY-MM-DD
      - selects → snap to allowed options
      - blanks/NaN → None
      - boolish → 0/1
    
    Args:
        table: Table name (e.g., "wells_master_v4")
        payload: Raw data dictionary
        codebook: Codebook dictionary for select options
    
    Returns:
        Coerced payload dictionary
    """
    spec = FIELD_SPEC.get(table, {})
    out = {}
    
    for field, val in payload.items():
        meta = spec.get(field, {})
        w = meta.get("widget")
        fmt = meta.get("fmt")
        out_val = _none_if_blank(val)

        # Bool-like override first
        if field in _BOOLISH_FIELDS:
            out_val = _coerce_boolish(val)
        elif w == "date":
            out_val = _coerce_date_iso(val)
        elif fmt == int:
            out_val = _coerce_int(val)
        elif w == "number":
            out_val = _coerce_number(val)
        
        # Snap selects to allowed values
        if meta.get("widget") == "select":
            allowed = _resolve_allowed_options(meta, codebook)
            out_val = _coerce_select(out_val, allowed)

        out[field] = out_val
    
    return out

def validate_against_spec(table: str, spec: dict, payload: dict) -> List[str]:
    """
    Validate a payload against field specification.
    
    Args:
        table: Table name (e.g., "wells_master_v4")
        spec: FIELD_SPEC dictionary
        payload: Data dictionary to validate
    
    Returns:
        List of error messages (empty if valid)
    """
    errors = []
    for field, meta in spec.get(table, {}).items():
        val = payload.get(field)
        
        # Required field check
        if meta.get("required") and (val is None or (isinstance(val, str) and val.strip() == "") or val == ""):
            errors.append(f"{field} is required")
        
        # Range validation for numbers
        if val is not None and val != "" and meta.get("range"):
            lo, hi = meta["range"]
            try:
                num = float(val)
                if num < lo or num > hi:
                    errors.append(f"{field} must be between {lo} and {hi}")
            except (ValueError, TypeError):
                pass
        
        # Integer format check
        if meta.get("fmt") == "int" and val not in (None, "", 0):
            try:
                int(val)
            except (ValueError, TypeError):
                errors.append(f"{field} must be an integer")
    
    return errors

def export_data_dictionary(spec: dict, path: Path):
    """
    Export field specifications to CSV data dictionary.
    
    Args:
        spec: FIELD_SPEC dictionary
        path: Output CSV file path
    """
    rows = []
    for table, fields in spec.items():
        for name, meta in fields.items():
            opts = meta.get("options", "")
            if isinstance(opts, list):
                opts_str = ", ".join([str(o) for o in opts])
            elif isinstance(opts, str):
                opts_str = opts
            else:
                opts_str = "<dynamic>"
            
            rows.append({
                "table": table,
                "field": name,
                "widget": meta.get("widget", ""),
                "required": "Yes" if meta.get("required") else "No",
                "range": str(meta.get("range", "")) if meta.get("range") else "",
                "unit": meta.get("unit", ""),
                "options": opts_str,
                "help": meta.get("help", "")
            })
    
    df = pd.DataFrame(rows)
    df.to_csv(path, index=False)
    return df

# ============================================================================
# CODEBOOK
# ============================================================================

@st.cache_data
def load_codebook():
    codebook = {
        'family': [
            'collagen',         # Pure collagen (split from decECM)
            'decECM',           # Decellularized ECM (requires species + tissue)
            'fibrin', 'alginate', 'gelMA', 'hyaluronan', 'PEG_DA', 'composite'
        ],
        'species': [
            'human', 'porcine', 'bovine', 'rat', 'mouse', 'avian', 'other'
        ],
        'tissues': [
            'mammary', 'dermis', 'small_intestine_submucosa', 'myocardium', 'pericardium',
            'liver', 'lung', 'kidney', 'bladder', 'tendon', 'cartilage', 'meniscus',
            'adipose', 'placenta', 'amniotic_membrane', 'esophagus', 'cornea', 'other'
        ],
        'probe_type': ['pH_pulse', 'ionic_pulse', 'crosslinker_pulse', 'light_dose', 'temperature_shift'],
        'gel_binary': [0, 1],
        'gel_strength_score_0to3': [0, 1, 2, 3],
        'failure_mode': ['none', 'no_set', 'partial_set', 'delayed_set', 'collapse',
                         'overcrosslink_brittle', 'phase_separation', 'opalescence', 'bubble_issue'],
        'suspected_cause': ['over_digest', 'under_digest', 'low_pH', 'high_pH', 'low_ionic',
                            'high_ionic', 'low_temp', 'high_temp', 'lipid_contam', 'detergent_contam',
                            'chaotrope_residual', 'air_entrainment', 'photoinitiator_low',
                            'photodose_low', 'photodose_high', 'unknown'],
        'color_shift': ['none', 'yellowing', 'browning', 'pink_loss', 'other'],
        'split': ['train', 'validate', 'test', 'holdout_batch'],
        'status_code': ["liquid","viscous","weak_gel","soft_gel","stiff_gel","softened","partial_liquid","liquidated"]
    }
    # Optional: extend from CSVs if present
    try:
        df_cb = pd.read_csv(ROOT / "data" / "ecm_gelation_codebook.csv")
        for _, row in df_cb.iterrows():
            if pd.notna(row.get('allowed_values')) and pd.notna(row.get('field')):
                codebook[row['field']] = [v.strip() for v in str(row['allowed_values']).split('|')]
    except Exception:
        pass
    return codebook

# ============================================================================
# CRUD
# ============================================================================

def create_well(data, reagents_list=None):
    rid = data.get("record_id") or new_record_id()
    data["record_id"] = rid
    data['created_at'] = datetime.now().isoformat()
    data['updated_at'] = datetime.now().isoformat()

    with tx() as con:
        cols = list(data.keys())
        vals = [data[k] for k in cols]
        con.execute(f"INSERT INTO wells_master_v4 ({','.join(cols)}) VALUES ({','.join(['?']*len(vals))})", vals)

        if reagents_list:
            for r in reagents_list:
                r = {k:v for k,v in r.items() if v not in ("",)}  # strip empties
                r["record_id"] = rid
                if "created_at" not in r: r["created_at"] = datetime.now().isoformat()
                r_cols = list(r.keys()); r_vals = [r[k] for k in r_cols]
                con.execute(f"INSERT INTO reagents_per_well ({','.join(r_cols)}) VALUES ({','.join(['?']*len(r_vals))})", r_vals)
    return rid

def read_wells(filters=None, use_effective_view=True):
    conn = get_connection()
    table = "v_wells_effective" if use_effective_view else "wells_master_v4"
    q = f"SELECT * FROM {table}"
    params = []
    if filters:
        cond = []
        for k,v in filters.items():
            if v not in (None,""):
                cond.append(f"{k}=?")
                params.append(v)
        if cond: q += " WHERE " + " AND ".join(cond)
    q += " ORDER BY created_at DESC"
    df = pd.read_sql_query(q, conn, params=params if params else None)
    conn.close()
    return df

def update_well(record_id, data, expected_updated_at=None):
    with tx() as con:
        if expected_updated_at:
            cur = con.execute("SELECT updated_at FROM wells_master_v4 WHERE record_id=?", (record_id,)).fetchone()
            if not cur:
                raise ValueError("Record not found.")
            if cur["updated_at"] != expected_updated_at:
                raise RuntimeError("This record was edited by someone else. Reload and try again.")
        sets = ",".join([f"{k}=?" for k in data.keys()])
        con.execute(f"UPDATE wells_master_v4 SET {sets} WHERE record_id=?", [*data.values(), record_id])

def delete_well(record_id):
    with tx() as con:
        con.execute("DELETE FROM wells_master_v4 WHERE record_id = ?", (record_id,))

def add_reagent(data):
    if 'created_at' not in data:
        data['created_at'] = datetime.now().isoformat()
    with tx() as con:
        cols = ",".join(data.keys())
        con.execute(f"INSERT INTO reagents_per_well ({cols}) VALUES ({','.join(['?']*len(data))})", list(data.values()))

def get_reagents(record_id):
    conn = get_connection()
    df = pd.read_sql_query("SELECT * FROM reagents_per_well WHERE record_id=? ORDER BY added_order", conn, params=(record_id,))
    conn.close()
    return df

def delete_reagent(reagent_id):
    with tx() as con:
        con.execute("DELETE FROM reagents_per_well WHERE reagent_id=?", (reagent_id,))

def add_event(data):
    if 'created_at' not in data: data['created_at'] = datetime.now().isoformat()
    if 'timestamp' not in data or not data['timestamp']: data['timestamp'] = datetime.now().isoformat()
    with tx() as con:
        cols = ",".join(data.keys())
        con.execute(f"INSERT INTO events_long ({cols}) VALUES ({','.join(['?']*len(data))})", list(data.values()))

def get_events(record_id):
    conn = get_connection()
    df = pd.read_sql_query("SELECT * FROM events_long WHERE record_id=? ORDER BY time_point_min", conn, params=(record_id,))
    conn.close()
    return df

def delete_event(event_id):
    with tx() as con:
        con.execute("DELETE FROM events_long WHERE event_id=?", (event_id,))

def backup_database():
    """
    Create a timestamped backup of the database and optionally VACUUM.
    
    Returns:
        Path to backup file
    """
    import shutil
    
    backup_dir = ROOT / "backups"
    backup_dir.mkdir(exist_ok=True)
    
    ts = datetime.now().strftime("%Y%m%d_%H%M")
    backup_path = backup_dir / f"gelpredict_{ts}.db"
    
    # Copy database
    shutil.copy2(DB_PATH, backup_path)
    
    # Vacuum original to reclaim space (optional)
    try:
        conn = get_connection()
        conn.execute("VACUUM;")
        conn.close()
    except Exception:
        pass  # VACUUM not critical
    
    return backup_path

# ============================================================================
# IMAGE PROCESSING HELPERS
# ============================================================================

def _sha256_bytes(b: bytes) -> str:
    """Calculate SHA256 hash of bytes."""
    h = hashlib.sha256()
    h.update(b)
    return h.hexdigest()

def _safe_ext(mime: str) -> str:
    """Get file extension from MIME type."""
    return {
        "image/jpeg": ".jpg",
        "image/png": ".png",
        "image/tiff": ".tif",
        "image/webp": ".webp"
    }.get(mime, ".bin")

def _exif_datetime(img: Image.Image) -> Optional[str]:
    """Extract datetime from EXIF data, return ISO format or None."""
    try:
        exif = img.getexif()
        if not exif:
            return None
        tagmap = {ExifTags.TAGS.get(k, k): v for k, v in exif.items()}
        dt = tagmap.get("DateTimeOriginal") or tagmap.get("DateTime")
        # EXIF format "YYYY:MM:DD HH:MM:SS"
        if isinstance(dt, str) and len(dt) >= 19 and dt[4] == ":":
            y, M, d = dt[0:4], dt[5:7], dt[8:10]
            h, m, s = dt[11:13], dt[14:16], dt[17:19]
            return f"{y}-{M}-{d}T{h}:{m}:{s}"
    except Exception:
        return None
    return None

def _save_thumbnail(src_bytes: bytes, thumb_path: Path, max_px=512) -> Tuple[int, int]:
    """
    Create and save thumbnail from image bytes.
    
    Returns:
        (width, height) of thumbnail
    """
    im = Image.open(io.BytesIO(src_bytes))
    im = im.convert("RGB")
    im.thumbnail((max_px, max_px))
    thumb_path.parent.mkdir(parents=True, exist_ok=True)
    im.save(thumb_path, format="JPEG", quality=85)
    return im.size[0], im.size[1]

def _probe_dims(src_bytes: bytes) -> Tuple[int, int]:
    """Get image dimensions without full load."""
    im = Image.open(io.BytesIO(src_bytes))
    return im.size[0], im.size[1]

# ============================================================================
# IMAGE CRUD
# ============================================================================

def add_image_record(payload: dict):
    """Add an image record to gel_images table."""
    with tx() as con:
        cols = ",".join(payload.keys())
        placeholders = ",".join(["?"] * len(payload))
        con.execute(
            f"INSERT INTO gel_images ({cols}) VALUES ({placeholders})",
            list(payload.values())
        )

def get_images_for_record(record_id: str):
    """Get all images for a specific well record."""
    conn = get_connection()
    try:
        df = pd.read_sql_query(
            "SELECT * FROM gel_images WHERE record_id=? ORDER BY created_at DESC",
            conn, params=(record_id,)
        )
        return df
    finally:
        conn.close()

def delete_image(image_id: str):
    """Delete image record and associated files."""
    with tx() as con:
        row = con.execute(
            "SELECT file_relpath, thumb_relpath FROM gel_images WHERE image_id=?",
            (image_id,)
        ).fetchone()
        con.execute("DELETE FROM gel_images WHERE image_id=?", (image_id,))
    
    # Remove files outside the transaction
    if row:
        for rel in (row["file_relpath"], row["thumb_relpath"]):
            if rel:
                p = ROOT / rel
                try:
                    p.unlink(missing_ok=True)
                except Exception:
                    pass

# ============================================================================
# CLONE / BULK HELPERS
# ============================================================================

CLONE_EXCLUDE_FIELDS = {
    "record_id","created_at","updated_at",
    "gel_binary","gel_strength_score_0to3","tilt_test_angle_deg","time_to_handle_min",
    "app_recipe_recommended","app_pgel_pred","app_thalf_pred_min","app_uncertainty",
    "counterfactual_recipe","counterfactual_expected_pgel","notes_post"
}

def get_well(record_id: str) -> Optional[dict]:
    """Get a single well record by ID."""
    conn = get_connection()
    try:
        row = pd.read_sql_query("SELECT * FROM wells_master_v4 WHERE record_id=?", conn, params=(record_id,))
        if row.empty: return None
        return row.iloc[0].to_dict()
    finally:
        conn.close()

def copy_well_payload(well: dict, *, new_record_id: str, date_override: Optional[str] = None,
                      operator_override: Optional[str] = None, plate_id: Optional[str] = None,
                      row_letter: Optional[str] = None, col_num: Optional[int] = None,
                      replicate_id: Optional[int] = None, batch_id: Optional[str] = None) -> dict:
    """
    Copy a well payload, excluding outcome fields and updating positional fields.
    
    Args:
        well: Source well dictionary
        new_record_id: UUID for the new record
        date_override: Override date
        operator_override: Override operator_id
        plate_id: Override plate_id
        row_letter: Override row (A-H)
        col_num: Override column (1-12)
        replicate_id: Override replicate_id
        batch_id: Override batch_id
    
    Returns:
        New well payload dictionary
    """
    base = {k: v for k, v in well.items() if k not in CLONE_EXCLUDE_FIELDS}
    base["record_id"] = new_record_id
    if date_override: base["date"] = date_override
    if operator_override: base["operator_id"] = operator_override
    if batch_id: base["batch_id"] = batch_id
    if plate_id is not None: base["plate_id"] = plate_id
    if row_letter is not None: base["row"] = row_letter
    if col_num is not None: base["col"] = int(col_num)
    if replicate_id is not None: base["replicate_id"] = int(replicate_id)
    
    # Wipe kinetic/outcome fields that shouldn't be cloned
    for k in ("time_to_halfmax_min","slope_OD_per_min","final_OD","lag_time_min"):
        if k in base:
            base[k] = None
    
    return base

def get_reagents_template(record_id: str) -> List[dict]:
    """Get reagents from a well as a template list (without reagent_id)."""
    df = get_reagents(record_id)
    if df.empty: return []
    keep_cols = ["reagent_name","reagent_class","purpose","stock_conc_value","stock_conc_units",
                 "volume_uL_per_mL","effective_conc_mM","lot_number","added_order","notes"]
    cols = [c for c in keep_cols if c in df.columns]
    rows = df[cols].to_dict(orient="records")
    return rows

def likely_duplicate_exists(plate_id, row, col, lookback_hours=12):
    """
    Check if a well with same plate/row/col was recently created.
    
    Args:
        plate_id: Plate identifier
        row: Row letter (A-H)
        col: Column number (1-12)
        lookback_hours: How far back to check (default 12 hours)
    
    Returns:
        bool: True if likely duplicate exists
    """
    if not plate_id or not row or not col:
        return False
    conn = get_connection()
    try:
        df = pd.read_sql_query(
            "SELECT record_id, created_at FROM wells_master_v4 WHERE plate_id=? AND row=? AND col=? "
            "AND datetime(created_at) > datetime('now', ?)",
            conn, params=(plate_id, row, int(col), f'-{int(lookback_hours)} hours')
        )
        return not df.empty
    finally:
        conn.close()

def bulk_create_wells(template_well: dict, positions: list, 
                      reagents_template: Optional[list] = None,
                      date_override: Optional[str] = None, operator_override: Optional[str] = None, 
                      batch_id: Optional[str] = None) -> list:
    """
    Bulk create wells from a template.
    
    Args:
        template_well: Template well dictionary
        positions: List of (row_letter, col_num, replicate_id) tuples
        reagents_template: Optional reagents to copy to each well
        date_override: Override date for all wells
        operator_override: Override operator_id
        batch_id: Override batch_id
    
    Returns:
        List of new record_ids created
    """
    rids = []
    for (r, c, rep) in positions:
        rid = new_record_id()
        payload = copy_well_payload(
            template_well, new_record_id=rid, date_override=date_override,
            operator_override=operator_override, plate_id=template_well.get("plate_id"),
            row_letter=r, col_num=c, replicate_id=rep, batch_id=batch_id
        )
        create_well(payload, reagents_list=reagents_template)
        rids.append(rid)
    return rids

# ============================================================================
# UI
# ============================================================================

def show_plates_viewer():
    """Show all plates with their wells and experiments."""
    st.header("🧪 Plates Viewer")
    st.caption("View all plates and their experimental data")
    
    # Connect to database
    conn = get_connection()
    
    # Get all unique plates
    plates_df = pd.read_sql_query("""
        SELECT DISTINCT plate_id, 
               COUNT(*) as well_count,
               MIN(date) as first_date,
               MAX(date) as last_date,
               COUNT(DISTINCT batch_id) as unique_batches,
               COUNT(DISTINCT operator_id) as unique_operators
        FROM wells_master_v4 
        WHERE plate_id IS NOT NULL
        GROUP BY plate_id
        ORDER BY last_date DESC
    """, conn)
    
    if plates_df.empty:
        st.info("No plates found in the database.")
        conn.close()
        return
    
    st.write(f"**Total Plates:** {len(plates_df)}")
    
    # Filters
    with st.expander("🔍 Filter Plates", expanded=False):
        col1, col2 = st.columns(2)
        with col1:
            filter_plate_id = st.text_input("Plate ID contains")
            filter_operator = st.selectbox("Operator", ["All"] + sorted(plates_df['unique_operators'].dropna().unique().tolist()))
        with col2:
            min_wells = st.number_input("Min wells", min_value=0, value=0)
    
    # Apply filters
    filtered_df = plates_df.copy()
    if filter_plate_id:
        filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate_id, case=False, na=False)]
    if min_wells > 0:
        filtered_df = filtered_df[filtered_df['well_count'] >= min_wells]
    
    # Display plates
    for idx, row in filtered_df.iterrows():
        with st.expander(f"🧪 **{row['plate_id']}** ({row['well_count']} wells)", expanded=False):
            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("Wells", row['well_count'])
                st.metric("Batches", row['unique_batches'])
            with col2:
                st.metric("First Date", row['first_date'])
                st.metric("Last Date", row['last_date'])
            with col3:
                st.metric("Operators", row['unique_operators'])
            
            # Show wells for this plate
            if st.button(f"🔍 View Wells", key=f"view_wells_{row['plate_id']}"):
                st.session_state[f"show_wells_{row['plate_id']}"] = True
            
            if st.session_state.get(f"show_wells_{row['plate_id']}"):
                wells_df = pd.read_sql_query("""
                    SELECT record_id, row, col, batch_id, family, operator_id, date,
                           gel_binary, gel_strength_score_0to3, temp_incubation_C, target_pH
                    FROM wells_master_v4 
                    WHERE plate_id = ?
                    ORDER BY row, col
                """, conn, params=(row['plate_id'],))
                
                st.dataframe(wells_df, use_container_width=True)
    
    conn.close()

def show_gelation_viewer():
    """Show all gelation experiments with filtering and analysis."""
    st.header("🧬 Gelation Experiments Viewer")
    st.caption("View and analyze gelation experiments")
    
    # Connect to database
    conn = get_connection()
    
    # Get gelation experiments
    gelation_df = pd.read_sql_query("""
        SELECT record_id, date, operator_id, family, batch_id, plate_id, row, col,
               gelation_id, temp_incubation_C, target_pH, gel_volume_uL,
               gel_binary, gel_strength_score_0to3, time_to_gel_min,
               disintegrated, days_to_disintegration, reliquefied, days_to_reliquefaction,
               plate_adhesion, created_at
        FROM wells_master_v4 
        WHERE gelation_id IS NOT NULL
        ORDER BY date DESC, created_at DESC
    """, conn)
    
    if gelation_df.empty:
        st.info("No gelation experiments found in the database.")
        conn.close()
        return
    
    st.write(f"**Total Gelation Experiments:** {len(gelation_df)}")
    
    # Filters
    with st.expander("🔍 Filter Experiments", expanded=False):
        col1, col2, col3 = st.columns(3)
        with col1:
            filter_batch = st.text_input("Batch ID contains")
            filter_family = st.selectbox("ECM Family", ["All"] + sorted(gelation_df['family'].dropna().unique().tolist()))
        with col2:
            filter_operator = st.selectbox("Operator", ["All"] + sorted(gelation_df['operator_id'].dropna().unique().tolist()))
            filter_gelation_id = st.text_input("Gelation ID contains")
        with col3:
            filter_outcome = st.selectbox("Gel Outcome", ["All", "Gel", "No Gel"])
            filter_plate = st.text_input("Plate ID contains")
    
    # Apply filters
    filtered_df = gelation_df.copy()
    if filter_batch:
        filtered_df = filtered_df[filtered_df['batch_id'].str.contains(filter_batch, case=False, na=False)]
    if filter_family != "All":
        filtered_df = filtered_df[filtered_df['family'] == filter_family]
    if filter_operator != "All":
        filtered_df = filtered_df[filtered_df['operator_id'] == filter_operator]
    if filter_gelation_id:
        filtered_df = filtered_df[filtered_df['gelation_id'].str.contains(filter_gelation_id, case=False, na=False)]
    if filter_outcome == "Gel":
        filtered_df = filtered_df[filtered_df['gel_binary'] == 1]
    elif filter_outcome == "No Gel":
        filtered_df = filtered_df[filtered_df['gel_binary'] == 0]
    if filter_plate:
        filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate, case=False, na=False)]
    
    st.write(f"**Filtered Results:** {len(filtered_df)} experiments")
    
    # Summary statistics
    if not filtered_df.empty:
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            gel_rate = filtered_df['gel_binary'].mean() * 100 if 'gel_binary' in filtered_df.columns else 0
            st.metric("Gel Rate", f"{gel_rate:.1f}%")
        with col2:
            avg_strength = filtered_df['gel_strength_score_0to3'].mean() if 'gel_strength_score_0to3' in filtered_df.columns else 0
            st.metric("Avg Strength", f"{avg_strength:.1f}")
        with col3:
            avg_temp = filtered_df['temp_incubation_C'].mean() if 'temp_incubation_C' in filtered_df.columns else 0
            st.metric("Avg Temp", f"{avg_temp:.1f}°C")
        with col4:
            avg_time = filtered_df['time_to_gel_min'].mean() if 'time_to_gel_min' in filtered_df.columns else 0
            st.metric("Avg Time to Gel", f"{avg_time:.1f} min")
    
    # Display experiments
    st.dataframe(filtered_df, use_container_width=True)
    
    conn.close()

def show_cell_growth_viewer():
    """Show cell growth experiments from the cell growth database."""
    st.header("🧫 Cell Growth Viewer")
    st.caption("View cell growth experiments and their results")
    
    # Try to connect to cell growth database
    try:
        LAB_CELL_DB = ROOT / "cellgrowth_lab.sqlite"
        if not LAB_CELL_DB.exists():
            st.info("No cell growth database found. Create some cell growth experiments first!")
            return
        
        conn = sqlite3.connect(str(LAB_CELL_DB))
        
        # Get cell growth runs
        runs_df = pd.read_sql_query("""
            SELECT run_id, date, operator_id, plate_id, plate_type, 
                   created_at, updated_at
            FROM cell_runs 
            ORDER BY date DESC, created_at DESC
        """, conn)
        
        if runs_df.empty:
            st.info("No cell growth experiments found.")
            conn.close()
            return
        
        st.write(f"**Total Cell Growth Runs:** {len(runs_df)}")
        
        # Filters
        with st.expander("🔍 Filter Runs", expanded=False):
            col1, col2 = st.columns(2)
            with col1:
                filter_operator = st.selectbox("Operator", ["All"] + sorted(runs_df['operator_id'].dropna().unique().tolist()))
                filter_plate = st.text_input("Plate ID contains")
            with col2:
                filter_plate_type = st.selectbox("Plate Type", ["All"] + sorted(runs_df['plate_type'].dropna().unique().tolist()))
        
        # Apply filters
        filtered_df = runs_df.copy()
        if filter_operator != "All":
            filtered_df = filtered_df[filtered_df['operator_id'] == filter_operator]
        if filter_plate:
            filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate, case=False, na=False)]
        if filter_plate_type != "All":
            filtered_df = filtered_df[filtered_df['plate_type'] == filter_plate_type]
        
        # Display runs
        for idx, row in filtered_df.iterrows():
            with st.expander(f"🧫 **Run {row['run_id'][:12]}...** ({row['plate_type']})", expanded=False):
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.write(f"**Date:** {row['date']}")
                    st.write(f"**Operator:** {row['operator_id']}")
                with col2:
                    st.write(f"**Plate ID:** {row['plate_id']}")
                    st.write(f"**Plate Type:** {row['plate_type']}")
                with col3:
                    st.write(f"**Created:** {row['created_at']}")
                
                # Try to get media formulation data
                try:
                    media_df = pd.read_sql_query("""
                        SELECT * FROM media_per_run 
                        WHERE run_id = ?
                    """, conn, params=(row['run_id'],))
                    
                    if not media_df.empty:
                        st.write("**Media Formulation:**")
                        st.dataframe(media_df, use_container_width=True)
                except:
                    pass
        
        conn.close()
        
    except Exception as e:
        st.error(f"Error accessing cell growth database: {e}")
        st.info("Make sure the cell growth database exists and is accessible.")

def show_morphology_viewer():
    """Show morphology observations from the morphology database."""
    st.header("🔬 Morphology Viewer")
    st.caption("View morphology observations and measurements")
    
    # Try to connect to morphology database
    try:
        MORPH_DB = ROOT / "morphology_lab.sqlite"
        if not MORPH_DB.exists():
            st.info("No morphology database found. Create some morphology experiments first!")
            return
        
        conn = sqlite3.connect(str(MORPH_DB))
        
        # Get morphology observations
        morph_df = pd.read_sql_query("""
            SELECT observation_id, date, operator_id, well_id, plate_id,
                   observation_type, measurement_value, measurement_units,
                   observation_notes, created_at
            FROM morphology_observations 
            ORDER BY date DESC, created_at DESC
        """, conn)
        
        if morph_df.empty:
            st.info("No morphology observations found.")
            conn.close()
            return
        
        st.write(f"**Total Morphology Observations:** {len(morph_df)}")
        
        # Filters
        with st.expander("🔍 Filter Observations", expanded=False):
            col1, col2 = st.columns(2)
            with col1:
                filter_operator = st.selectbox("Operator", ["All"] + sorted(morph_df['operator_id'].dropna().unique().tolist()))
                filter_well = st.text_input("Well ID contains")
            with col2:
                filter_type = st.selectbox("Observation Type", ["All"] + sorted(morph_df['observation_type'].dropna().unique().tolist()))
                filter_plate = st.text_input("Plate ID contains")
        
        # Apply filters
        filtered_df = morph_df.copy()
        if filter_operator != "All":
            filtered_df = filtered_df[filtered_df['operator_id'] == filter_operator]
        if filter_well:
            filtered_df = filtered_df[filtered_df['well_id'].str.contains(filter_well, case=False, na=False)]
        if filter_type != "All":
            filtered_df = filtered_df[filtered_df['observation_type'] == filter_type]
        if filter_plate:
            filtered_df = filtered_df[filtered_df['plate_id'].str.contains(filter_plate, case=False, na=False)]
        
        # Summary statistics
        if not filtered_df.empty:
            col1, col2, col3 = st.columns(3)
            with col1:
                unique_wells = filtered_df['well_id'].nunique()
                st.metric("Unique Wells", unique_wells)
            with col2:
                unique_plates = filtered_df['plate_id'].nunique()
                st.metric("Unique Plates", unique_plates)
            with col3:
                avg_value = filtered_df['measurement_value'].mean() if 'measurement_value' in filtered_df.columns else 0
                st.metric("Avg Measurement", f"{avg_value:.2f}")
        
        # Display observations
        st.dataframe(filtered_df, use_container_width=True)
        
        conn.close()
        
    except Exception as e:
        st.error(f"Error accessing morphology database: {e}")
        st.info("Make sure the morphology database exists and is accessible.")

def main():
    st.set_page_config(page_title="GelPredict Data Entry", page_icon="🧪", layout="wide")
    st.title("🧪 GelPredict Data Entry System")
    st.caption("Normalized logging of wells, reagents, and longitudinal events with export for PIs & training.")

    init_database()
    apply_migrations()  # Run migrations with user_version
    ensure_triggers()
    ensure_views()
    
    codebook = load_codebook()
    
    # Database scope badge
    st.sidebar.caption("**📊 Dataset Scope:**")
    st.sidebar.success("✅ **LAB - Hydrogels**\n\n`gelpredict.db`")
    st.sidebar.caption("Your experimental data.\nTraining-ready.")
    st.sidebar.markdown("---")
    
    # Check for schema drift (warn if found)
    drift = check_schema_drift(FIELD_SPEC)
    if drift:
        with st.sidebar.expander("⚠️ Schema Drift Detected"):
            for problem in drift:
                st.warning(problem)
            st.caption("Some fields in FIELD_SPEC don't match database. Update spec or database.")

    page = st.sidebar.radio(
        "Navigation", 
        ["🧪 Hydrogels", "🧫 Cell Growth", "🔬 Morphology", 
         "📊 View/Edit Data", "📚 Lit Review Tracker", "🧪 Media Tracker", "📂 Import CSV", "📋 Export Data", "🔄 Sync Manager", "🤖 AI Ecosystem"]
    )

    if page == "🧪 Hydrogels":
        # Hydrogel tracking with LAB/Literature toggle
        hydrogel_mode = st.sidebar.radio("Dataset", ["LAB", "Literature"], horizontal=True, key="hydrogel_mode")
        
        if hydrogel_mode == "LAB":
            # LAB Hydrogels submenu
            lab_page = st.sidebar.radio(
                "LAB Hydrogels",
                ["🧬 ECM Batches", "🧪 Gelation Tests", "📝 Quick Entry (Legacy)", 
                 "🧫 Reagents", "📈 Events", 
                 "🧩 Plate Wizard", "🧱 Plates", "📷 Images"],
                key="lab_hydrogel_page"
            )
            
            if lab_page == "🧬 ECM Batches":
                try:
                    from batch_creation_lab import show_batch_creation_form
                    show_batch_creation_form(codebook)
                except ImportError as e:
                    st.error(f"Batch Creation Lab module not available: {e}")
                    st.info("This module may not be available in the cloud deployment.")
            elif lab_page == "🧪 Gelation Tests":
                try:
                    from gelation_lab import show_gelation_form
                    show_gelation_form(codebook)
                except ImportError as e:
                    st.error(f"Gelation Lab module not available: {e}")
                    st.info("This module may not be available in the cloud deployment.")
            elif lab_page == "📝 Quick Entry (Legacy)":
                st.info("💡 **Legacy Mode:** All-in-one entry. For new workflows, use **ECM Batches** → **Gelation Tests**")
                show_new_entry_form(codebook)
            elif lab_page == "🧫 Reagents":
                show_reagents_manager(codebook)
            elif lab_page == "📈 Events":
                show_events_logger(codebook)
            elif lab_page == "🧩 Plate Wizard":
                show_plate_map_wizard(codebook)
            elif lab_page == "🧱 Plates":
                show_plates_registry()
            elif lab_page == "📷 Images":
                show_images_manager(codebook)
        else:
            # Literature Hydrogels submenu
            lit_page = st.sidebar.radio(
                "Literature Hydrogels",
                ["🧬 ECM Batches", "🧪 Gelation Data", "📝 Quick Entry (Legacy)"],
                key="lit_hydrogel_page"
            )
            
            if lit_page == "🧬 ECM Batches":
                try:
                    from batch_creation_lit import show_lit_batch_form
                    show_lit_batch_form(codebook)
                except ImportError as e:
                    st.error(f"Batch Creation Literature module not available: {e}")
                    st.info("This module may not be available in the cloud deployment.")
            elif lit_page == "🧪 Gelation Data":
                try:
                    from gelation_lit import show_lit_gelation_form
                    show_lit_gelation_form(codebook)
                except ImportError as e:
                    st.error(f"Gelation Literature module not available: {e}")
                    st.info("This module may not be available in the cloud deployment.")
            elif lit_page == "📝 Quick Entry (Legacy)":
                st.info("💡 **Legacy Mode:** All-in-one entry. For new workflows, use **ECM Batches** → **Gelation Data**")
                try:
                    from literature_gui import show_literature_app
                    show_literature_app()
                except ImportError as e:
                    st.error(f"Literature GUI module not available: {e}")
                    st.info("This module may not be available in the cloud deployment.")
    
    elif page == "📊 View/Edit Data":
        # View/Edit Data with sub-sections for each data type
        view_mode = st.sidebar.radio("Data Type", ["📊 Raw Wells Data", "📚 Literature Database", "🧫 Cell Growth", "🔬 Morphology", "📚 Batch Library", "🧪 Plates", "🧬 Gelation"], horizontal=False, key="view_mode")
        
        if view_mode == "📊 Raw Wells Data":
            show_view_edit_page(codebook)
        elif view_mode == "📚 Literature Database":
            show_literature_database_viewer()
        elif view_mode == "🧫 Cell Growth":
            show_cell_growth_viewer()
        elif view_mode == "🔬 Morphology":
            show_morphology_viewer()
        elif view_mode == "📚 Batch Library":
            try:
                from batch_creation_lab import show_batch_library
                show_batch_library()
            except ImportError as e:
                st.error(f"Batch Library module not available: {e}")
                st.info("This module may not be available in the cloud deployment.")
        elif view_mode == "🧪 Plates":
            show_plates_viewer()
        elif view_mode == "🧬 Gelation":
            show_gelation_viewer()
    
    elif page == "🧫 Cell Growth":
        # Cell growth with LAB/Literature toggle
        cell_mode = st.sidebar.radio("Dataset", ["LAB", "Literature"], horizontal=True, key="cell_mode")
        
        if cell_mode == "LAB":
            try:
                from cell_growth_lab_gui import show_app as show_lab_cells
                show_lab_cells()
            except ImportError as e:
                st.error(f"Cell Growth Lab module not available: {e}")
                st.info("This module may not be available in the cloud deployment.")
        else:
            try:
                from cell_growth_literature_gui import show_app as show_lit_cells
                show_lit_cells()
            except ImportError as e:
                st.error(f"Cell Growth Literature module not available: {e}")
                st.info("This module may not be available in the cloud deployment.")
    
    elif page == "🔬 Morphology":
        # Morphology tracking with LAB/Literature toggle
        morph_mode = st.sidebar.radio("Dataset", ["LAB", "Literature"], horizontal=True, key="morph_mode")
        
        if morph_mode == "LAB":
            try:
                from morphology_lab_gui import show_app as show_lab_morph
                show_lab_morph()
            except ImportError as e:
                st.error(f"Morphology Lab module not available: {e}")
                st.info("This module may not be available in the cloud deployment.")
        else:
            try:
                from morphology_literature_gui import show_app as show_lit_morph
                show_lit_morph()
            except ImportError as e:
                st.error(f"Morphology Literature module not available: {e}")
                st.info("This module may not be available in the cloud deployment.")
    
    elif page == "📚 Lit Review Tracker":
        try:
            from lit_review_tracker import show_app as show_tracker
            show_tracker()
        except ImportError as e:
            st.error(f"Literature Review Tracker module not available: {e}")
            st.info("This module may not be available in the cloud deployment.")
        
        # Add literature integration status
        try:
            from literature_integration import get_literature_review_summary
            st.markdown("---")
            st.subheader("🔗 Literature Integration Status")
            
            summary = get_literature_review_summary()
            
            col1, col2, col3, col4 = st.columns(4)
            with col1:
                st.metric("Total Papers", summary["total_tracked_papers"])
            with col2:
                st.metric("With Data", summary["papers_with_data"])
            with col3:
                st.metric("Auto-Generated", summary["auto_generated_papers"])
            with col4:
                total_data = summary["total_hydrogels_logged"] + summary["total_cell_runs_logged"] + summary["total_morphology_logged"]
                st.metric("Total Entries", total_data)
            
            if summary["papers_by_status"]:
                st.markdown("**Status Breakdown:**")
                for status, count in summary["papers_by_status"].items():
                    st.write(f"• {status.replace('_', ' ').title()}: {count}")
            
            if summary["recent_activity"]:
                st.markdown("**Recent Activity:**")
                for activity in summary["recent_activity"][:3]:
                    st.caption(f"• {activity['author']} ({activity['year']}) - {activity['title']}")
                    
        except ImportError:
            st.caption("ℹ️ Literature integration status not available")
        except Exception as e:
            st.caption(f"ℹ️ Literature integration status error: {e}")
    
    elif page == "📂 Import CSV":
        try:
            from csv_importer import show_csv_importer
            show_csv_importer()
        except ImportError as e:
            st.error(f"CSV Importer module not available: {e}")
            st.info("This module may not be available in the cloud deployment.")
    
    elif page == "📋 Export Data":
        show_export_page()
    
    elif page == "🧪 Media Tracker":
        try:
            from media_formulation_tracker import show_app
            show_app()
        except ImportError as e:
            st.error(f"Media Formulation Tracker module not available: {e}")
            st.info("This module may not be available in the cloud deployment.")
    
    elif page == "🔄 Sync Manager":
        try:
            from sync_manager import show_sync_app
            show_sync_app()
        except ImportError as e:
            st.error(f"Sync Manager module not available: {e}")
            st.info("This module may not be available in the cloud deployment.")
    
    elif page == "🤖 AI Ecosystem":
        # AI Ecosystem with subpages
        ai_page = st.sidebar.radio(
            "AI Components",
            ["🏠 AI Overview", "🔮 Recipe Optimizer", "📊 Batch Analysis", "🧠 Model Training", "🔍 Inference Tools", "📈 Performance Metrics"],
            key="ai_ecosystem_page"
        )
        
        if ai_page == "🏠 AI Overview":
            show_ai_ecosystem_overview()
        elif ai_page == "🔮 Recipe Optimizer":
            try:
                from unified_app import show_ai_optimizer_page, load_models
                clf, reg = load_models()
                show_ai_optimizer_page(clf, reg, codebook)
            except ImportError as e:
                st.error(f"AI Recipe Optimizer module not available: {e}")
                st.info("This module may not be available in the cloud deployment.")
        elif ai_page == "📊 Batch Analysis":
            try:
                from unified_app import show_batch_analysis_page, load_models
                clf, reg = load_models()
                show_batch_analysis_page(clf, reg)
            except ImportError as e:
                st.error(f"Batch Analysis module not available: {e}")
                st.info("This module may not be available in the cloud deployment.")
        elif ai_page == "🧠 Model Training":
            show_ai_model_training_page()
        elif ai_page == "🔍 Inference Tools":
            show_ai_inference_tools_page()
        elif ai_page == "📈 Performance Metrics":
            show_ai_performance_metrics_page()

# ============================================================================
# AI ECOSYSTEM FUNCTIONS
# ============================================================================

def show_ai_ecosystem_overview():
    """Show overview of all AI components and capabilities."""
    st.title("🤖 AI Ecosystem Overview")
    
    st.markdown("""
    ## 🧠 GelPredict AI/ML System
    
    GelPredict includes a comprehensive AI ecosystem designed to predict and optimize ECM gelation experiments.
    """)
    
    # Model Status
    st.subheader("📊 Current Model Status")
    try:
        from unified_app import load_models
        clf, reg = load_models()
        
        col1, col2 = st.columns(2)
        with col1:
            if clf is not None:
                st.success("✅ **Classification Model**: Loaded and ready")
                st.caption("Predicts gelation probability (gel/no-gel)")
            else:
                st.warning("⚠️ **Classification Model**: Not trained")
                st.caption("Train with `python src/train_baseline.py`")
        
        with col2:
            if reg is not None:
                st.success("✅ **Regression Model**: Loaded and ready")
                st.caption("Predicts time-to-gelation")
            else:
                st.info("ℹ️ **Regression Model**: Optional")
                st.caption("Provides gelation time estimates")
    except Exception as e:
        st.error(f"Could not load models: {e}")
    
    # AI Components Overview
    st.subheader("🔧 AI Components")
    
    components = [
        {
            "name": "🔮 Recipe Optimizer",
            "description": "Real-time recipe optimization using grid search over pH, ionic strength, and temperature",
            "features": ["P(gel) predictions", "Time-to-gelation estimates", "Alternative conditions", "Save recommendations"]
        },
        {
            "name": "📊 Batch Analysis", 
            "description": "AI-powered analysis of experimental batches and performance comparison",
            "features": ["Batch effect analysis", "Failure mode prediction", "Performance metrics", "Cross-validation"]
        },
        {
            "name": "🧠 Model Training",
            "description": "Automated training pipeline for classification and regression models",
            "features": ["Data preprocessing", "Cross-validation", "Feature engineering", "Model persistence"]
        },
        {
            "name": "🔍 Inference Tools",
            "description": "Command-line and API tools for batch predictions and optimization",
            "features": ["CLI predictions", "JSON output", "Grid search", "Utility scoring"]
        },
        {
            "name": "📈 Performance Metrics",
            "description": "Comprehensive model evaluation and performance tracking",
            "features": ["ROC-AUC scores", "R² metrics", "MAE analysis", "Calibration plots"]
        }
    ]
    
    for component in components:
        with st.expander(f"**{component['name']}**"):
            st.write(component['description'])
            st.markdown("**Features:**")
            for feature in component['features']:
                st.markdown(f"• {feature}")
    
    # Quick Actions
    st.subheader("🚀 Quick Actions")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("🔮 Get Recipe Recommendation", use_container_width=True):
            st.session_state.ai_page = "🔮 Recipe Optimizer"
            st.rerun()
    
    with col2:
        if st.button("📊 Analyze Batches", use_container_width=True):
            st.session_state.ai_page = "📊 Batch Analysis"
            st.rerun()
    
    with col3:
        if st.button("🧠 Train Models", use_container_width=True):
            st.session_state.ai_page = "🧠 Model Training"
            st.rerun()
    
    # Data Requirements
    st.subheader("📋 Data Requirements")
    
    st.markdown("""
    **To enable AI predictions, you need:**
    
    ✅ **Minimum 20-30 experiments** (mix of successful and failed gels)  
    ✅ **12 core features** (protein concentration, pH, conductivity, etc.)  
    ✅ **Binary outcomes** (gel_binary: 0/1)  
    ✅ **Time-to-gelation** (for regression model)  
    
    **Optional but recommended:**
    
    🔸 **Batch metadata** (batch_id, family, donor_id)  
    🔸 **Failure documentation** (failure_mode, suspected_cause)  
    🔸 **Advanced assays** (hydroxyproline, GAG content, viscosity)  
    🔸 **Quality metrics** (UV ratios, SDS-PAGE data)
    """)
    
    # Training Instructions
    with st.expander("🎓 How to Train Your First AI Model"):
        st.markdown("""
        ### Step 1: Collect Data
        1. Enter experimental data using the **📝 New Data Entry** forms
        2. Include both successful and failed gelation attempts
        3. Document failure modes and suspected causes
        
        ### Step 2: Export Training Data
        1. Go to **📋 Export Data**
        2. Download the **Training Dataset (CSV)**
        3. Save as `data/ecm_runs.csv`
        
        ### Step 3: Train Models
        ```bash
        python src/train_baseline.py
        ```
        
        ### Step 4: Use AI Predictions
        1. Refresh this page to see updated model status
        2. Use **🔮 Recipe Optimizer** for recommendations
        3. Run experiments based on AI suggestions
        4. Record outcomes to improve the model
        """)

def show_ai_model_training_page():
    """Show model training interface and instructions."""
    st.title("🧠 AI Model Training")
    
    st.markdown("""
    ## 📊 Training Pipeline
    
    GelPredict uses automated machine learning to train both classification and regression models
    from your experimental data.
    """)
    
    # Current training data status
    st.subheader("📋 Training Data Status")
    
    try:
        df_wells = read_wells(use_effective_view=True)
        
        if df_wells.empty:
            st.warning("⚠️ No experimental data found. Enter some experiments first!")
            return
        
        # Count experiments with required data
        has_gel_binary = len(df_wells[df_wells['gel_binary'].notna()])
        has_time_to_halfmax = len(df_wells[df_wells['time_to_halfmax_min'].notna()])
        has_required_features = len(df_wells[df_wells['ecm_total_protein_mgml'].notna()])
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("Total Experiments", len(df_wells))
        
        with col2:
            st.metric("With Gel Outcomes", has_gel_binary)
        
        with col3:
            st.metric("With Timing Data", has_time_to_halfmax)
        
        # Check if ready for training
        if has_gel_binary >= 20 and has_required_features >= 20:
            st.success("✅ **Ready for training!** You have sufficient data.")
        elif has_gel_binary >= 10:
            st.warning("⚠️ **Minimum data available.** Consider collecting more experiments for better performance.")
        else:
            st.error("❌ **Insufficient data.** Need at least 20 experiments with gel outcomes.")
        
    except Exception as e:
        st.error(f"Error checking training data: {e}")
    
    # Training instructions
    st.subheader("🎯 Training Instructions")
    
    st.markdown("""
    ### Option 1: Export and Train Manually
    
    1. **Export your data**:
       - Go to **📋 Export Data**
       - Download **Training Dataset (CSV)**
       - Save as `data/ecm_runs.csv`
    
    2. **Run training**:
       ```bash
       python src/train_baseline.py
       ```
    
    3. **Check results**:
       - Models saved to `models/` directory
       - Check console for performance metrics
    
    ### Option 2: Command Line Training
    
    ```bash
    # Train with default settings
    python src/train_baseline.py
    
    # Train with custom CSV file
    python src/train_baseline.py --csv data/my_data.csv
    
    # Check model performance
    python src/infer_recipe.py --json inputs.json
    ```
    """)
    
    # Model architecture
    st.subheader("🏗️ Model Architecture")
    
    st.markdown("""
    **Classification Model (Gel/No-Gel)**:
    - **Algorithm**: Logistic Regression with Isotonic Calibration
    - **Features**: 12 core experimental parameters
    - **Output**: Probability of successful gelation (0-1)
    - **Evaluation**: ROC-AUC, Average Precision, F1-Score
    
    **Regression Model (Time-to-Gelation)**:
    - **Algorithm**: Random Forest Regressor (300 trees)
    - **Features**: Same 12 parameters
    - **Output**: Estimated time to half-maximum gelation (minutes)
    - **Evaluation**: R², Mean Absolute Error
    """)
    
    # Feature importance
    st.subheader("📊 Feature Engineering")
    
    st.markdown("""
    **Core Features Used**:
    - `ecm_total_protein_mgml` - Total protein concentration
    - `pre_pH` - Initial pH before neutralization
    - `pre_conductivity_mS` - Conductivity measurements
    - `temp_incubation_C` - Incubation temperature
    - `uv_ratio_A220_A280` - UV absorbance ratio
    - `sds_smear_index` - SDS-PAGE degradation proxy
    - `sds_alpha_ratio` - Collagen chain ratio
    - `target_pH` - Target neutralization pH
    - `NaCl_mM_added` - Additional NaCl concentration
    - `CaCl2_mM_added` - CaCl2 concentration
    - `DMEM_percent` - DMEM media percentage
    - `PBS_10x_uL_per_mL` - PBS volume added
    """)

def show_ai_inference_tools_page():
    """Show command-line inference tools and usage."""
    st.title("🔍 AI Inference Tools")
    
    st.markdown("""
    ## 💻 Command-Line AI Tools
    
    GelPredict provides powerful command-line tools for batch predictions and recipe optimization.
    """)
    
    # CLI Tools
    st.subheader("🛠️ Available Tools")
    
    tools = [
        {
            "name": "`src/infer_recipe.py`",
            "description": "Single recipe optimization and prediction",
            "usage": "python src/infer_recipe.py --json inputs.json",
            "output": "JSON with recommended recipe and predictions"
        },
        {
            "name": "`src/train_baseline.py`",
            "description": "Train classification and regression models",
            "usage": "python src/train_baseline.py --csv data/ecm_runs.csv",
            "output": "Trained models saved to models/ directory"
        },
        {
            "name": "`app/streamlit_app.py`",
            "description": "Standalone AI prediction interface",
            "usage": "streamlit run app/streamlit_app.py",
            "output": "Web interface for real-time predictions"
        }
    ]
    
    for tool in tools:
        with st.expander(f"**{tool['name']}**"):
            st.write(tool['description'])
            st.code(tool['usage'], language="bash")
            st.caption(f"Output: {tool['output']}")
    
    # Input format
    st.subheader("📝 Input Format")
    
    st.markdown("""
    ### JSON Input File (`inputs.json`)
    
    ```json
    {
        "ecm_total_protein_mgml": 7.5,
        "pre_pH": 4.2,
        "pre_conductivity_mS": 3.1,
        "temp_incubation_C": 37.0,
        "uv_ratio_A220_A280": 5.2,
        "sds_smear_index": 0.3,
        "sds_alpha_ratio": 0.9,
        "DMEM_percent": 0.0,
        "PBS_10x_uL_per_mL": 0.0,
        "NaCl_mM_added": 120.0,
        "CaCl2_mM_added": 0.0,
        "target_pH": 7.2
    }
    ```
    """)
    
    # Example usage
    st.subheader("🎯 Example Usage")
    
    st.markdown("""
    ### 1. Create Input File
    ```bash
    # Create inputs.json with your ECM batch characteristics
    echo '{
        "ecm_total_protein_mgml": 7.5,
        "pre_pH": 4.2,
        "pre_conductivity_mS": 3.1,
        "temp_incubation_C": 37.0,
        "uv_ratio_A220_A280": 5.2,
        "sds_smear_index": 0.3,
        "sds_alpha_ratio": 0.9,
        "DMEM_percent": 0.0,
        "PBS_10x_uL_per_mL": 0.0,
        "NaCl_mM_added": 120.0,
        "CaCl2_mM_added": 0.0,
        "target_pH": 7.2
    }' > inputs.json
    ```
    
    ### 2. Run Optimization
    ```bash
    python src/infer_recipe.py --json inputs.json
    ```
    
    ### 3. Interpret Results
    ```json
    {
        "recommended": {
            "target_pH": 7.35,
            "PBS_10x_uL_per_mL": 12.5,
            "temp_incubation_C": 37.0
        },
        "predictions": {
            "P_gel": 0.847,
            "t_half_min": 18.3,
            "utility": 0.801
        }
    }
    ```
    """)
    
    # Batch processing
    st.subheader("📦 Batch Processing")
    
    st.markdown("""
    ### Process Multiple Batches
    
    ```bash
    # Create multiple input files
    for i in {1..10}; do
        python src/infer_recipe.py --json batch_${i}.json > results_${i}.json
    done
    
    # Combine results
    cat results_*.json > all_recommendations.json
    ```
    
    ### Integration with Data Pipeline
    
    ```bash
    # Export data → Train → Predict → Update database
    python src/train_baseline.py
    python src/infer_recipe.py --json new_batch.json
    # Use results to populate database with predictions
    ```
    """)

def show_ai_performance_metrics_page():
    """Show model performance metrics and evaluation."""
    st.title("📈 AI Performance Metrics")
    
    st.markdown("""
    ## 📊 Model Evaluation
    
    Track and analyze the performance of your AI models with comprehensive metrics.
    """)
    
    # Check if models exist
    models_dir = Path("models")
    clf_path = models_dir / "gel_classifier.joblib"
    reg_path = models_dir / "thalf_regressor.joblib"
    
    if not clf_path.exists():
        st.warning("⚠️ No trained models found. Train models first using the Model Training page.")
        return
    
    try:
        import joblib
        clf = joblib.load(clf_path)
        reg = joblib.load(reg_path) if reg_path.exists() else None
        
        st.success("✅ Models loaded successfully!")
        
        # Model info
        st.subheader("🧠 Model Information")
        
        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown("**Classification Model**")
            st.caption(f"Algorithm: {type(clf['model']).__name__}")
            st.caption(f"Features: {len(clf['features'])} parameters")
            st.caption("Purpose: Predict gelation probability")
        
        with col2:
            if reg:
                st.markdown("**Regression Model**")
                st.caption(f"Algorithm: {type(reg['model']).__name__}")
                st.caption(f"Features: {len(reg['features'])} parameters")
                st.caption("Purpose: Predict time-to-gelation")
            else:
                st.info("Regression model not available")
        
        # Performance metrics
        st.subheader("📊 Performance Metrics")
        
        # Get training data for evaluation
        df_wells = read_wells(use_effective_view=True)
        
        if df_wells.empty:
            st.warning("No data available for evaluation")
            return
        
        # Classification metrics
        st.markdown("### Classification Model Performance")
        
        df_cls = df_wells.dropna(subset=['gel_binary'])
        if len(df_cls) >= 4:
            # Simulate predictions (in real implementation, you'd load actual metrics)
            st.info("💡 **Note**: Actual performance metrics are computed during training.")
            st.markdown("""
            **Typical Performance**:
            - **ROC-AUC**: 0.75-0.90 (depending on data quality)
            - **Average Precision**: 0.70-0.85
            - **F1-Score**: 0.65-0.80
            
            **Interpretation**:
            - ROC-AUC > 0.8: Good discrimination
            - AP > 0.7: Good precision-recall balance
            - F1 > 0.7: Good overall performance
            """)
        else:
            st.warning("Insufficient data for classification evaluation")
        
        # Regression metrics
        if reg:
            st.markdown("### Regression Model Performance")
            
            df_reg = df_wells.dropna(subset=['time_to_halfmax_min', 'gel_binary'])
            df_reg_ok = df_reg[df_reg['gel_binary'] == 1]
            
            if len(df_reg_ok) >= 5:
                st.info("💡 **Note**: Actual performance metrics are computed during training.")
                st.markdown("""
                **Typical Performance**:
                - **R²**: 0.60-0.85 (depending on data quality)
                - **MAE**: 5-15 minutes
                - **RMSE**: 8-20 minutes
                
                **Interpretation**:
                - R² > 0.7: Good predictive power
                - MAE < 10 min: Accurate timing predictions
                - RMSE < 15 min: Low prediction error
                """)
            else:
                st.warning("Insufficient successful gels for regression evaluation")
        
        # Feature importance
        st.subheader("🔍 Feature Importance")
        
        st.markdown("""
        **Key Features for Gelation Prediction**:
        
        1. **Protein Concentration** - Primary driver of gel strength
        2. **pH Conditions** - Critical for neutralization
        3. **Ionic Strength** - Affects gelation kinetics
        4. **Temperature** - Influences gelation rate
        5. **UV Ratios** - Protein quality indicators
        6. **SDS-PAGE Metrics** - Degradation assessment
        
        **Model Interpretability**:
        - Feature importance scores available in trained models
        - Partial dependence plots show parameter effects
        - SHAP values explain individual predictions
        """)
        
        # Model validation
        st.subheader("✅ Model Validation")
        
        st.markdown("""
        **Validation Strategy**:
        
        - **Train/Test Split**: 75% training, 25% testing
        - **Cross-Validation**: 5-fold CV for robust estimates
        - **Batch Validation**: Holdout batches for generalization
        - **Time-based Split**: Recent data for temporal validation
        
        **Quality Checks**:
        
        ✅ **Data Quality**: Missing values, outliers, consistency  
        ✅ **Feature Engineering**: Proper scaling, encoding  
        ✅ **Model Calibration**: Probability calibration  
        ✅ **Overfitting**: Training vs. validation performance  
        """)
        
        # Recommendations
        st.subheader("💡 Model Improvement Recommendations")
        
        st.markdown("""
        **To Improve Performance**:
        
        1. **Collect More Data**:
           - Aim for 50+ experiments for robust training
           - Include diverse ECM sources and conditions
           - Document failure modes systematically
        
        2. **Feature Engineering**:
           - Add proteomics data (hydroxyproline, GAG content)
           - Include rheological measurements
           - Add batch metadata (donor, processing details)
        
        3. **Advanced Models**:
           - Try ensemble methods (XGBoost, LightGBM)
           - Implement deep learning for complex patterns
           - Add physics-informed constraints
        
        4. **Validation**:
           - Use stratified sampling for balanced splits
           - Implement time-series validation
           - Test on completely new ECM sources
        """)
        
    except Exception as e:
        st.error(f"Error loading models: {e}")

# ============================================================================
# VISUAL QC HELPERS
# ============================================================================

def render_plate_heatmap(plate_id: str, date_str: Optional[str] = None):
    """
    Render a plate heatmap showing gel_strength_score_0to3 for visual QC.
    
    Args:
        plate_id: Plate ID to visualize
        date_str: Optional date filter (YYYY-MM-DD)
    """
    if not plate_id:
        st.info("Enter a plate_id to view heatmap.")
        return
    
    g = get_plate_geometry(plate_id)
    if not g:
        st.info(f"Plate '{plate_id}' not registered. Register it first in Plates Registry.")
        return
    
    rows, max_cols = g
    
    # Pull wells for this plate (optionally same date)
    filters = {"plate_id": plate_id}
    df = read_wells(filters, use_effective_view=True)
    
    if date_str:
        df = df[df["date"] == date_str]
    
    if df.empty:
        st.warning(f"No wells found for plate '{plate_id}'" + (f" on {date_str}" if date_str else ""))
        return
    
    # Build grid of gel_strength_score_0to3 (NaN → -1)
    r_index = {ch: i for i, ch in enumerate(rows)}
    grid = np.full((len(rows), int(max_cols)), -1.0)
    
    for _, r in df.iterrows():
        if pd.isna(r.get("row")) or pd.isna(r.get("col")): 
            continue
        rr = str(r["row"])
        cc = int(r["col"])
        if rr in r_index and 1 <= cc <= int(max_cols):
            val = r.get("gel_strength_score_0to3")
            grid[r_index[rr], cc - 1] = -1 if pd.isna(val) else float(val)
    
    # Create heatmap
    fig, ax = plt.subplots(figsize=(min(10, 0.6 * int(max_cols) + 2), min(8, 0.4 * len(rows) + 2)))
    cax = ax.imshow(grid, aspect="auto", interpolation="nearest", cmap="RdYlGn", vmin=-1, vmax=3)
    
    ax.set_xticks(range(int(max_cols)))
    ax.set_xticklabels([str(i) for i in range(1, int(max_cols) + 1)], rotation=0)
    ax.set_yticks(range(len(rows)))
    ax.set_yticklabels(list(rows))
    ax.set_xlabel("Column")
    ax.set_ylabel("Row")
    
    title = f"Plate {plate_id} — Gel Strength"
    if date_str:
        title += f" ({date_str})"
    ax.set_title(title)
    
    cbar = fig.colorbar(cax, ax=ax)
    cbar.set_label("Gel Strength (−1=missing, 0-3=score)")
    
    st.pyplot(fig)
    plt.close(fig)
    
    # Show summary stats
    valid_scores = grid[grid >= 0]
    if len(valid_scores) > 0:
        col1, col2, col3, col4 = st.columns(4)
        col1.metric("Wells tested", len(valid_scores))
        col2.metric("Mean strength", f"{valid_scores.mean():.2f}")
        col3.metric("Gelled (≥1)", f"{(valid_scores >= 1).sum()}")
        col4.metric("Strong (≥2)", f"{(valid_scores >= 2).sum()}")

# ============================================================================
# UI HELPER: MEASUREMENT PROTOCOLS
# ============================================================================

def show_measurement_protocol(field_name: str, table: str = "wells_master_v4"):
    """
    Display device and method information for a field if available in FIELD_SPEC.
    
    Args:
        field_name: Field name to show protocol for
        table: Table name (default: wells_master_v4)
    """
    if table not in FIELD_SPEC or field_name not in FIELD_SPEC[table]:
        return
    
    field_spec = FIELD_SPEC[table][field_name]
    device = field_spec.get("device")
    method = field_spec.get("method")
    
    if device or method:
        with st.expander(f"ℹ️ How to measure {field_name}", expanded=False):
            if device:
                st.markdown(f"**Device:** {device}")
            if method:
                st.markdown("**Protocol:**")
                st.text(method)

# ============================================================================
# UI PAGE FUNCTIONS
# ============================================================================

def show_new_entry_form(codebook):
    st.header("Create New Well Entry")
    
    # Initialize session state for selected wells
    if 'selected_wells' not in st.session_state:
        st.session_state.selected_wells = []

    # Metadata section (regular inputs - not in form)
    st.subheader("📋 Metadata")
    
    # First row: Date, Operator, Family (horizontal)
    m1, m2, m3 = st.columns(3)
    with m1:
        date_input = st.date_input("Date*", value=date.today())
    with m2:
        operator_id = st.text_input("Operator ID*", help="Your initials")
    with m3:
        family = st.selectbox(
            "ECM Family*", 
            options=[""] + codebook['family'],
            index=2 if "decECM" in codebook['family'] else 0  # Default to "decECM"
        )
    
    # Commercial Product Checkbox (needs to come early)
    is_commercial = st.checkbox(
        "🏭 Commercial/Ready-Made Product",
        value=False,
        help="Check if this is a commercial product (e.g., Matrigel, PureCol, Cultrex, Geltrex)"
    )
    
    # Commercial Product Details (show only if commercial)
    if is_commercial:
        st.markdown("**🏷️ Commercial Product Details**")
        st.caption("For commercial products, use manufacturer's lot number as Batch ID")
        
        # Common products dropdown + custom option
        COMMON_COMMERCIAL_PRODUCTS = {
            "Matrigel": {"vendor": "Corning", "family_hint": "collagen"},
            "Matrigel GFR": {"vendor": "Corning", "family_hint": "collagen"},
            "Cultrex": {"vendor": "R&D Systems", "family_hint": "collagen"},
            "Cultrex BME": {"vendor": "R&D Systems", "family_hint": "collagen"},
            "Geltrex": {"vendor": "Thermo Fisher", "family_hint": "collagen"},
            "PureCol": {"vendor": "Advanced BioMatrix", "family_hint": "collagen"},
            "VitroCol": {"vendor": "Advanced BioMatrix", "family_hint": "collagen"},
            "Rat Tail Collagen I": {"vendor": "Corning", "family_hint": "collagen"},
            "Collagen I": {"vendor": "Invitrogen", "family_hint": "collagen"},
            "Custom/Other": {"vendor": "", "family_hint": ""}
        }
        
        comm_col1, comm_col2 = st.columns(2)
        with comm_col1:
            product_name = st.selectbox(
                "Product Name*",
                options=[""] + list(COMMON_COMMERCIAL_PRODUCTS.keys()),
                help="Select a common product or choose Custom/Other"
            )
            if product_name and product_name != "Custom/Other":
                # Auto-fill vendor
                vendor = COMMON_COMMERCIAL_PRODUCTS[product_name]["vendor"]
            else:
                vendor = st.text_input("Vendor Name*", help="e.g., Corning, Advanced BioMatrix, R&D Systems")
        
        with comm_col2:
            if product_name == "Custom/Other":
                custom_product = st.text_input("Custom Product Name*")
            else:
                custom_product = None
            catalog_num = st.text_input("Catalog/Part Number", help="e.g., 354234, 3432-005-01")
        
        website = st.text_input("Company Website", placeholder="https://www.corning.com", help="Company website URL")
        
        lot_num = st.text_input("Lot/Batch Number*", help="From manufacturer label - will be used as Batch ID")
        
        st.caption("⚠️ Note: ECM Provenance and Processing Protocol are typically N/A for commercial products")
    else:
        # Initialize variables if not commercial
        product_name = None
        vendor = None
        custom_product = None
        catalog_num = None
        website = None
        lot_num = None
    
    # ECM Provenance (species and tissue origin) - BEFORE batch_id generation
    st.markdown("**🧬 ECM Provenance** (species and tissue origin)")
    if is_commercial:
        st.caption("⚠️ For commercial products: check product datasheet for source species/tissue if available")
    
    prov_col1, prov_col2 = st.columns(2)
    with prov_col1:
        dec_species = st.selectbox(
            "Origin species*" if family == "decECM" else "Origin species", 
            [""] + codebook['species'],
            index=1 if "human" in codebook['species'] else 0,  # Default to "human"
            help="Required for decECM, optional for other ECM types. For commercial: see datasheet."
        )
    with prov_col2:
        dec_tissue = st.selectbox(
            "Source tissue/organ*" if family == "decECM" else "Source tissue/organ", 
            [""] + codebook['tissues'],
            index=1 if "mammary" in codebook['tissues'] else 0,  # Default to "mammary"
            help="Required for decECM, optional for other ECM types. For commercial: see datasheet."
        )
    
    st.markdown("---")
    
    # ========== CITATION INTEGRATION ==========
    st.subheader("📚 Literature Integration (Optional)")
    st.caption("Link this lab experiment to relevant literature for context and comparison")
    
    # Citation parser section
    st.markdown("### 🔍 Quick Add from Citation")
    st.caption("Paste full citation to auto-extract fields")
    
    citation_input = st.text_area(
        "Paste Citation",
        placeholder="""Example:
Smith J, Jones K. (2023). Decellularized mammary ECM promotes organoid formation. Biomaterials. DOI: 10.1016/j.biomaterials.2023.001

Or:
Smith et al. Decellularized mammary ECM promotes organoid formation. Biomaterials, 2023. https://doi.org/10.1016/j.biomaterials.2023.001""",
        height=100,
        key="lab_citation_paste"
    )
    
    if st.button("🔍 Parse Citation", type="secondary", key="lab_parse"):
        if citation_input:
            try:
                from literature_gui import parse_citation
                parsed = parse_citation(citation_input)
                st.session_state["lab_parsed_citation"] = parsed
                
                # Show what was extracted
                st.success("✅ Citation parsed! Fields auto-filled below:")
                col_p1, col_p2, col_p3 = st.columns(3)
                with col_p1:
                    if parsed.get("first_author"):
                        st.info(f"Author: {parsed['first_author']}")
                with col_p2:
                    if parsed.get("publication_year"):
                        st.info(f"Year: {parsed['publication_year']}")
                with col_p3:
                    if parsed.get("doi"):
                        st.info(f"DOI: {parsed['doi'][:20]}...")
                
                if parsed.get("paper_title"):
                    st.info(f"Title: {parsed['paper_title'][:80]}...")
            except Exception as e:
                st.error(f"Failed to parse citation: {e}")
    
    # Get parsed values if available
    parsed = st.session_state.get("lab_parsed_citation", {})
    
    # Source tracking fields
    st.markdown("**📖 Source Information**")
    source_col1, source_col2, source_col3 = st.columns(3)
    with source_col1:
        first_author = st.text_input(
            "First Author (optional)", 
            value=parsed.get("first_author", "") or "",
            placeholder="Smith", 
            help="Last name of first author for reference"
        )
        publication_year = st.number_input(
            "Publication Year (optional)", 
            min_value=1950, 
            max_value=2030, 
            value=parsed.get("publication_year") or None, 
            step=1,
            help="Year of publication for reference"
        )
    with source_col2:
        paper_title = st.text_input(
            "Paper Title (optional)", 
            value=parsed.get("paper_title", "") or "",
            placeholder="ECM gelation kinetics", 
            help="Brief description or title for reference"
        )
        source_label = st.text_input(
            "Source Label (optional)", 
            value=parsed.get("source_label", "") or "",
            placeholder="Smith2023_Fig2A", 
            help="Short reference ID"
        )
    with source_col3:
        doi = st.text_input(
            "DOI (optional)", 
            value=parsed.get("doi", "") or "",
            placeholder="10.1234/journal.2023.0001",
            help="Digital Object Identifier"
        )
    
    citation = st.text_area("Full Citation (optional)", height=60, 
                           placeholder="Smith J, Doe A, et al. (2023). Journal of ECM Research. 15:123-145.",
                           help="Complete citation for reference")
    
    st.markdown("---")
    
    # Batch & Gelation ID section (auto-generated for lab-made)
    st.markdown("**🧪 Batch & Gelation Identifiers**")
    
    # For commercial products, batch_id comes from lot number
    if is_commercial and lot_num:
        batch_id = lot_num
        st.info(f"📦 Batch ID (from lot#): **{batch_id}**")
    else:
        # Auto-generate batch_id for lab-made ECM
        if family and dec_species and dec_tissue:
            suggested_batch_id = generate_batch_id(family, dec_species, dec_tissue, date_input, is_commercial)
            batch_id = st.text_input(
                "Batch ID*", 
                value=suggested_batch_id,
                help="Auto-generated from family-species-tissue-date. Can override."
            )
        else:
            batch_id = st.text_input(
                "Batch ID*",
                help="Fill in Family, Species, and Tissue above for auto-generation"
            )
    
    # Auto-generate gelation_id
    if batch_id:
        next_seq = get_next_gelation_sequence(batch_id, date_input)
        suggested_gelation_id = generate_gelation_id(batch_id, date_input, next_seq)
        
        gel_col1, gel_col2 = st.columns([3, 1])
        with gel_col1:
            gelation_id = st.text_input(
                "Gelation ID*",
                value=suggested_gelation_id,
                help="Auto-generated. Multiple gelations can share same batch_id."
            )
        with gel_col2:
            if st.button("🔄 Next Seq"):
                # Increment sequence
                current_parts = gelation_id.split("-")
                if len(current_parts) > 0 and current_parts[-1].isdigit():
                    new_seq = int(current_parts[-1]) + 1
                    st.session_state["custom_gelation_seq"] = new_seq
                    st.rerun()
        
        st.caption(f"💡 Same batch → different gelation IDs for protocol variants")
    else:
        gelation_id = ""
        st.warning("⚠️ Set Batch ID first to auto-generate Gelation ID")
    
    # Plate ID Selection (reuse or create new)
    st.markdown("**🧫 Plate Selection**")
    st.caption("Physical plates can be reused across days and batches")
    
    # Load recent plates
    recent_plates = get_recent_plates(limit=50)
    
    plate_mode = st.radio(
        "Plate Option",
        ["Reuse Existing Plate", "Create New Plate"],
        horizontal=True,
        help="Reuse a physical plate for new experiments or generate a new plate ID"
    )
    
    if plate_mode == "Reuse Existing Plate" and recent_plates:
        # Show recent plates with usage stats
        st.caption("**Select from recently used plates:**")
        
        plate_options = [""] + [
            f"{p['plate_id']} (Used: {p['first_use']} to {p['last_use']}, {p['n_wells']} wells, {p['n_batches']} batches)"
            for p in recent_plates
        ]
        plate_ids_list = [""] + [p['plate_id'] for p in recent_plates]
        
        selected_idx = st.selectbox(
            "Select Plate*",
            range(len(plate_options)),
            format_func=lambda i: plate_options[i]
        )
        
        plate_id = plate_ids_list[selected_idx] if selected_idx > 0 else ""
        
        if plate_id:
            # Show plate history
            plate_info = recent_plates[selected_idx - 1]
            st.info(f"""
            📊 **Plate History:**
            - First used: {plate_info['first_use']}
            - Last used: {plate_info['last_use']}
            - Total wells: {plate_info['n_wells']}
            - Batches used: {plate_info['n_batches']}
            - Gelations: {plate_info['n_gelations']}
            """)
            st.success(f"✅ Reusing plate: **{plate_id}**")
    
    elif plate_mode == "Reuse Existing Plate" and not recent_plates:
        st.warning("No existing plates found. Create a new one below.")
        plate_id = ""
    
    else:  # Create New Plate
        st.caption("**Generate new physical plate ID:**")
        
        new_plate_col1, new_plate_col2, new_plate_col3 = st.columns([2, 2, 1])
        with new_plate_col1:
            plate_type = st.selectbox(
                "Plate Type*",
                ["6", "12", "24", "48", "96", "384"],
                index=4,  # Default to 96-well
                help="Number of wells in the physical plate"
            )
        with new_plate_col2:
            suggested_plate_id = generate_plate_id(plate_type)
            plate_id = st.text_input(
                "Plate ID*",
                value=suggested_plate_id,
                help="Auto-generated. Can override."
            )
        with new_plate_col3:
            if st.button("🔄 Next"):
                # Increment sequence
                parts = plate_id.split("-")
                if len(parts) == 3 and parts[-1].isdigit():
                    new_seq = int(parts[-1]) + 1
                    plate_id = f"{parts[0]}-{parts[1]}-{new_seq:03d}"
                    st.rerun()
        
        st.success(f"✅ New plate: **{plate_id}**")
    
    # Load plate geometry (must happen before we use row_labels/max_cols)
    if plate_id:
        ensure_default_plate_if_unset(plate_id)
        geom = get_plate_geometry(plate_id)
        if geom:
            row_labels, max_cols = geom
        else:
            row_labels, max_cols = "ABCDEFGH", 12  # Default fallback
    else:
        row_labels, max_cols = "ABCDEFGH", 12  # Default if no plate selected
    
    # Donor ID
    donor_id = st.text_input("Donor ID (optional)")
    
    # Replicate ID
    replicate_id = st.number_input("Replicate ID", min_value=1, value=1)
    
    # Auto-generate semantic ID preview (using first selected well if available)
    if family and batch_id and st.session_state.selected_wells:
        first_well = st.session_state.selected_wells[0]
        preview_row = first_well[0]
        preview_col = int(first_well[1:])
        preview_id = generate_semantic_id(
            family, batch_id, plate_id, preview_row, preview_col, replicate_id,
            species=dec_species, tissue=dec_tissue
        )
        st.info(f"📝 Record ID preview: **{preview_id}**")
        st.caption("(Auto-generated from metadata above. Each selected well gets a unique ID.)")
    elif family and batch_id:
        st.info("📝 Fill in well positions above to see record ID preview")
    else:
        st.warning("⚠️ Fill in Family and Batch ID to generate record ID")
    
    # Inline plate geometry editor
    if plate_id:
        with st.expander("⚙️ Plate geometry (register / edit)", expanded=False):
            pg1, pg2 = st.columns([2,1])
            with pg1:
                new_rows = st.text_input("Row labels", value=row_labels, help="Continuous string, e.g., ABCDEFGH")
            with pg2:
                new_cols = st.number_input("Max columns", min_value=1, max_value=48, value=int(max_cols))
            desc = st.text_input("Description", value="")
            if st.button("💾 Save plate geometry"):
                try:
                    upsert_plate_geometry(plate_id, new_rows.strip(), int(new_cols), description=(desc or None))
                    st.success("✅ Plate geometry saved.")
                    # Refresh local vars
                    row_labels, max_cols = new_rows.strip(), int(new_cols)
                except Exception as e:
                    st.error(f"❌ Failed to save geometry: {e}")
    
    # Well selection (now that plate and geometry are defined)
    st.subheader("📍 Select Well Positions")
    st.caption(f"💡 Using plate **{plate_id or '(not selected)'}** with geometry: {row_labels} × {max_cols}")
    
    if not plate_id:
        st.warning("⚠️ Please select or create a plate above before selecting wells")
    else:
        # Well selection interface
        well_col1, well_col2, well_col3 = st.columns([2, 2, 1])
        with well_col1:
            selected_row = st.selectbox("Select Row", options=[""] + list(row_labels), key="well_row",
                                       help=f"Available rows for {plate_id}: {row_labels}")
        with well_col2:
            selected_col = st.selectbox("Select Column", options=[""] + [str(i) for i in range(1, int(max_cols)+1)], key="well_col",
                                       help=f"Available columns: 1-{max_cols}")
        with well_col3:
            add_well = st.button("➕ Add", type="secondary")
        
        # Add well to selection
        if add_well and selected_row and selected_col:
            well_id = f"{selected_row}{selected_col}"
            if well_id not in st.session_state.selected_wells:
                st.session_state.selected_wells.append(well_id)
                st.rerun()
            else:
                st.warning(f"⚠️ Well {well_id} is already selected")
        
        # Display selected wells
        if st.session_state.selected_wells:
            st.write(f"**Selected Wells ({len(st.session_state.selected_wells)}):**")
            well_display_cols = st.columns(6)  # Display wells in columns
            for i, well in enumerate(st.session_state.selected_wells):
                col_idx = i % 6
                with well_display_cols[col_idx]:
                    if st.button(f"❌ {well}", key=f"remove_{well}", help=f"Remove {well}"):
                        st.session_state.selected_wells.remove(well)
                        st.rerun()
            
            # Clear all button
            if st.button("🗑️ Clear All Wells"):
                st.session_state.selected_wells = []
                st.rerun()
        else:
            st.info("👆 Select rows and columns above to add wells to this entry")
    
    st.markdown("---")  # Visual separator

    st.subheader("🧊 Pre-Processing Tissue Storage")
    st.caption("⚠️ **BEFORE** any decellularization or ECM processing began (raw tissue storage)")
    st.info("💡 This is NOT the freeze-thaw decell technique (add that as a Protocol Step below). This tracks how the original tissue was stored.")
    
    # Pre-storage temperature and duration
    c1a, c1b = st.columns(2)
    with c1a:
        pre_storage_temp = st.selectbox("Storage temp (°C)", ["", "4°C (fridge)", "-20°C (freezer)", "-80°C (ultra-freezer)", "-196°C (LN2)", "Other"], 
                                        help="Temperature at which tissue was stored before processing", key="pre_storage_temp")
        if pre_storage_temp == "Other":
            pre_storage_temp_custom = st.number_input("Custom temp (°C)", -200.0, 50.0, 0.0, 1.0, key="pre_storage_temp_custom")
        else:
            pre_storage_temp_custom = None
        unk_days = st.checkbox("Unknown", key="unk_pre_days", help="Check if not reported/unknown")
        pre_storage_days = st.number_input("Days stored", min_value=0, value=0, 
                                          disabled=unk_days,
                                          help="Duration of storage at selected temperature")
        if unk_days:
            pre_storage_days = None
    with c1b:
        pre_storage_fresh_notes = st.text_input("Storage notes", placeholder="e.g., in PBS, in culture media", 
                                                help="Optional: how was tissue stored?")
    
    # Frozen storage
    st.markdown("**Frozen Storage (long-term):**")
    c2, c3, c4 = st.columns(3)
    with c2:
        unk_frozen_months = st.checkbox("Unknown", key="unk_pre_frozen_mo", help="Check if not reported/unknown")
        pre_storage_duration_months = st.number_input("Frozen duration (months)", 0.0, 120.0, 0.0, 0.5,
                                                      disabled=unk_frozen_months,
                                                      help="How long tissue was stored frozen BEFORE starting processing")
        if unk_frozen_months:
            pre_storage_duration_months = None
    with c3:
        unk_freezer_temp = st.checkbox("Unknown", key="unk_pre_frz_temp", help="Check if not reported/unknown")
        pre_storage_temp_freezer = st.number_input("Freezer temp (°C)", -200.0, 0.0, -80.0, 10.0,
                                                   disabled=unk_freezer_temp,
                                                   help="Storage temp: -20°C (standard), -80°C (long-term), -196°C (LN2)")
        if unk_freezer_temp:
            pre_storage_temp_freezer = None
    with c4:
        pre_storage_frozen_in = st.text_input("Frozen in", placeholder="e.g., dry, in buffer, with cryoprotectant",
                                              help="Optional: what medium was tissue frozen in?")
    
    # Freeze-thaw cycles during storage/transport
    st.markdown("**Freeze-Thaw Cycles (during storage/transport):**")
    st.caption("💡 NOT the intentional freeze-thaw decell technique - this is accidental/transport cycles")
    
    ft1, ft2, ft3, ft4 = st.columns(4)
    with ft1:
        unk_pre_ft_cycles = st.checkbox("Unknown", key="unk_pre_ft_cyc", help="Check if not reported/unknown")
        pre_storage_freeze_cycles = st.number_input("# Cycles", min_value=0, value=0,
                                                    disabled=unk_pre_ft_cycles,
                                                    help="# times frozen then thawed during storage/shipping")
        if unk_pre_ft_cycles:
            pre_storage_freeze_cycles = None
    with ft2:
        pre_storage_thaw_method = st.selectbox("Thaw method", 
                                               ["","passive_room_temp","37C_water_bath","4C_fridge",
                                                "buffer_wash_series","PBS_series","gradual_temp_ramp","other"],
                                               help="How was tissue thawed each time?")
    with ft3:
        unk_thaw_dur = st.checkbox("Unk", key="unk_pre_thaw_dur", help="Unknown/not reported")
        pre_storage_thaw_duration_min = st.number_input("Thaw duration (min)", 0.0, 1000.0, 30.0, 5.0,
                                                        disabled=unk_thaw_dur,
                                                        help="Duration of each thaw phase")
        if unk_thaw_dur:
            pre_storage_thaw_duration_min = None
    with ft4:
        pre_storage_ft_notes = st.text_input("Freeze-thaw notes", 
                                             placeholder="e.g., thawed in series of PBS washes, slow thaw at 4°C",
                                             help="Describe your thaw process")
    
    st.caption("📌 **Example 1:** Tissue excised, frozen dry at -80°C for 3 months, never thawed → Frozen duration: 3, Temp: -80°C, Cycles: 0")
    st.caption("📌 **Example 2:** Tissue frozen at -80°C, shipped on dry ice (thawed once during receipt), then refrozen → Cycles: 1, Thaw method: passive_room_temp")
    st.caption("📌 **Example 3 (Your workflow):** Frozen at -80°C, thawed via series of PBS washes before decell → Cycles: 1, Thaw method: buffer_wash_series, Notes: '3× PBS washes, 15min each'")
    st.caption("✅ **For literature:** Check 'Unknown' for parameters not reported in the paper")
    
    # Protocol Builder (OUTSIDE form - uses buttons)
    st.markdown("---")
    st.subheader("🔬 ECM Processing Protocol (Optional)")
    st.caption("Build your ECM preparation protocol step-by-step")
    
    # Initialize session state for processing steps
    if "proc_steps" not in st.session_state:
        st.session_state.proc_steps = []
    
    # Buttons to add different step types
    st.caption("**Add Processing Steps:**")
    row1_cols = st.columns(6)
    with row1_cols[0]:
        if st.button("➕ Decell", key="add_decell_exp"):
            st.session_state.proc_steps.append({"type": "decell", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row1_cols[1]:
        if st.button("➕ Wash", key="add_wash_exp"):
            st.session_state.proc_steps.append({"type": "wash", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row1_cols[2]:
        if st.button("➕ Delipid", key="add_delipid_exp"):
            st.session_state.proc_steps.append({"type": "delipid", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row1_cols[3]:
        if st.button("➕ Enzyme", key="add_enzyme_exp"):
            st.session_state.proc_steps.append({"type": "enzyme", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row1_cols[4]:
        if st.button("➕ Homogenize", key="add_homog_exp"):
            st.session_state.proc_steps.append({"type": "homogenize", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row1_cols[5]:
        if st.button("➕ Grind/Mill", key="add_grind_exp"):
            st.session_state.proc_steps.append({"type": "grind", "id": len(st.session_state.proc_steps)})
            st.rerun()
    
    row2_cols = st.columns(6)
    with row2_cols[0]:
        if st.button("➕ Freeze-Thaw", key="add_freeze_exp"):
            st.session_state.proc_steps.append({"type": "freeze_thaw", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row2_cols[1]:
        if st.button("➕ Lyophilize", key="add_lyoph_exp"):
            st.session_state.proc_steps.append({"type": "lyophilize", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row2_cols[2]:
        if st.button("➕ Reconstitute", key="add_recon_exp"):
            st.session_state.proc_steps.append({"type": "reconstitute", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row2_cols[3]:
        if st.button("➕ pH Adjust", key="add_ph_exp"):
            st.session_state.proc_steps.append({"type": "ph_adjust", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row2_cols[4]:
        if st.button("➕ Dialysis", key="add_dialysis_exp"):
            st.session_state.proc_steps.append({"type": "dialysis", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row2_cols[5]:
        if st.button("➕ Filtration", key="add_filter_exp"):
            st.session_state.proc_steps.append({"type": "filtration", "id": len(st.session_state.proc_steps)})
            st.rerun()
    
    row3_cols = st.columns(6)
    with row3_cols[0]:
        if st.button("➕ Centrifuge", key="add_centrifuge_exp"):
            st.session_state.proc_steps.append({"type": "centrifuge", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row3_cols[1]:
        if st.button("➕ Storage", key="add_storage_exp"):
            st.session_state.proc_steps.append({"type": "storage", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row3_cols[2]:
        if st.button("➕ Other", key="add_other_exp"):
            st.session_state.proc_steps.append({"type": "other", "id": len(st.session_state.proc_steps)})
            st.rerun()
    with row3_cols[5]:
        if st.button("🗑️ Clear All", key="clear_all_steps_exp"):
            st.session_state.proc_steps = []
            st.rerun()
    
    if st.session_state.proc_steps:
        st.caption(f"**{len(st.session_state.proc_steps)} step(s) added**")
    
    # Display and edit each step
    processing_steps = []
    for i, step in enumerate(st.session_state.proc_steps):
        with st.expander(f"Step {i+1}: {step['type'].title()}", expanded=True):
            col1, col2, col3 = st.columns([3, 3, 1])
            
            if step["type"] == "decell":
                try:
                    from shared_parameters import DECELL_AGENTS
                except ImportError:
                    DECELL_AGENTS = ["Trypsin", "Collagenase", "Dispase", "Accutase", "Other"]
                dcol1, dcol2, dcol3, dcol4 = st.columns(4)
                with dcol1:
                    reagent_sel = st.selectbox("Reagent", DECELL_AGENTS, key=f"decell_reag_sel_exp_{step['id']}")
                    if reagent_sel == "Other":
                        reagent = st.text_input("Specify reagent", placeholder="e.g., custom detergent", key=f"decell_reag_other_exp_{step['id']}")
                    else:
                        reagent = reagent_sel
                with dcol2:
                    unk_conc = st.checkbox("Unk", key=f"unk_decell_conc_exp_{step['id']}", help="Unknown/not reported")
                    conc_val = st.number_input("Concentration", 0.0, 100.0, 1.0, 0.1, disabled=unk_conc, key=f"decell_conc_exp_{step['id']}")
                    conc_unit = st.selectbox("Units", ["%","M","mM","mg/mL","v/v"], disabled=unk_conc, key=f"decell_unit_exp_{step['id']}")
                    if unk_conc:
                        conc_val, conc_unit = None, None
                with dcol3:
                    unk_dur = st.checkbox("Unk", key=f"unk_decell_dur_exp_{step['id']}", help="Unknown/not reported")
                    duration = st.number_input("Duration (hours)", 0.0, 1000.0, 24.0, 0.5, disabled=unk_dur, key=f"decell_dur_exp_{step['id']}")
                    if unk_dur:
                        duration = None
                    unk_temp = st.checkbox("Unk", key=f"unk_decell_temp_exp_{step['id']}", help="Unknown/not reported")
                    temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, disabled=unk_temp, key=f"decell_temp_exp_{step['id']}", 
                                          help="e.g., 4°C (fridge), 22°C (room temp), 37°C")
                    if unk_temp:
                        temp = None
                with dcol4:
                    unk_chg = st.checkbox("Unk", key=f"unk_decell_chg_exp_{step['id']}", help="Unknown/not reported")
                    changes = st.number_input("# Changes", 1, 100, 3, 1, disabled=unk_chg, key=f"decell_chg_exp_{step['id']}", 
                                             help="Solution changes")
                    if unk_chg:
                        changes = None
                notes = st.text_input("Notes (optional)", placeholder="e.g., gentle agitation, sterile conditions", key=f"decell_notes_exp_{step['id']}")
                processing_steps.append({"type": "decell", "reagent": reagent, "concentration": conc_val, 
                                       "conc_units": conc_unit, "duration_hours": duration, "temp_C": temp, 
                                       "changes": changes, "notes": notes or None})
            
            elif step["type"] == "wash":
                from shared_parameters import COMMON_BUFFERS
                wcol1, wcol2, wcol3, wcol4 = st.columns(4)
                with wcol1:
                    solution_sel = st.selectbox("Solution", COMMON_BUFFERS + ["DI water"], key=f"wash_sol_sel_exp_{step['id']}")
                    if solution_sel == "Other":
                        solution = st.text_input("Specify solution", placeholder="e.g., custom buffer", key=f"wash_sol_other_exp_{step['id']}")
                    else:
                        solution = solution_sel
                with wcol2:
                    conc_val = st.number_input("Conc", 0.0, 100.0, 1.0, 0.1, key=f"wash_conc_exp_{step['id']}")
                    conc_unit = st.selectbox("Units", ["x","M","mM","%","n/a"], key=f"wash_unit_exp_{step['id']}")
                with wcol3:
                    washes = st.number_input("# Washes", 1, 20, 3, 1, key=f"wash_num_exp_{step['id']}")
                    duration = st.number_input("Duration each (min)", 0.0, 500.0, 15.0, 5.0, key=f"wash_dur_exp_{step['id']}")
                with wcol4:
                    temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"wash_temp_exp_{step['id']}", 
                                          help="Wash temperature")
                notes = st.text_input("Notes (optional)", placeholder="e.g., shaking, flow rate", key=f"wash_notes_exp_{step['id']}")
                processing_steps.append({"type": "wash", "solution": solution, "concentration": conc_val, 
                                       "conc_units": conc_unit, "n_washes": washes, "duration_min": duration, 
                                       "temp_C": temp, "notes": notes or None})
            
            elif step["type"] == "delipid":
                from shared_parameters import DELIPID_SOLVENTS
                dlcol1, dlcol2, dlcol3, dlcol4 = st.columns(4)
                with dlcol1:
                    solvent_sel = st.selectbox("Solvent", DELIPID_SOLVENTS, key=f"delip_solv_sel_exp_{step['id']}")
                    if solvent_sel == "Other":
                        solvent = st.text_input("Specify solvent", placeholder="e.g., custom solvent", key=f"delip_solv_other_exp_{step['id']}")
                    else:
                        solvent = solvent_sel
                with dlcol2:
                    conc_val = st.number_input("Concentration", 0.0, 100.0, 100.0, 1.0, key=f"delip_conc_exp_{step['id']}")
                    conc_unit = st.selectbox("Units", ["%","v/v"], key=f"delip_unit_exp_{step['id']}")
                with dlcol3:
                    duration = st.number_input("Duration (hours)", 0.0, 100.0, 2.0, 0.25, key=f"delip_dur_exp_{step['id']}")
                    temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"delip_temp_exp_{step['id']}", 
                                          help="Room temp, fridge, etc.")
                with dlcol4:
                    times = st.number_input("# Times", 1, 20, 3, 1, key=f"delip_times_exp_{step['id']}", 
                                           help="Number of repetitions")
                notes = st.text_input("Notes (optional)", placeholder="e.g., vortex, solvent grade", key=f"delip_notes_exp_{step['id']}")
                processing_steps.append({"type": "delipid", "solvent": solvent, "concentration": conc_val, 
                                       "conc_units": conc_unit, "duration_hours": duration, "temp_C": temp, 
                                       "n_times": times, "notes": notes or None})
            
            elif step["type"] == "enzyme":
                from shared_parameters import COMMON_ENZYMES
                ecol1, ecol2, ecol3, ecol4 = st.columns(4)
                with ecol1:
                    enzyme_sel = st.selectbox("Enzyme", COMMON_ENZYMES, key=f"enz_name_sel_exp_{step['id']}")
                    if enzyme_sel == "Other":
                        enzyme = st.text_input("Specify enzyme", placeholder="e.g., custom enzyme", key=f"enz_name_other_exp_{step['id']}")
                    else:
                        enzyme = enzyme_sel
                with ecol2:
                    conc = st.number_input("Conc.", 0.0, 100.0, 1.0, 0.1, key=f"enz_conc_exp_{step['id']}")
                    units = st.selectbox("Units", ["mg/mL", "U/mL", "mg/g"], key=f"enz_units_exp_{step['id']}")
                with ecol3:
                    duration = st.number_input("Duration (hours)", 0.0, 500.0, 48.0, 1.0, key=f"enz_dur_exp_{step['id']}")
                with ecol4:
                    temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"enz_temp_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., pH maintained, shaking speed", key=f"enz_notes_exp_{step['id']}")
                processing_steps.append({"type": "enzyme", "enzyme": enzyme, "concentration": conc, 
                                       "conc_units": units, "duration_hours": duration, "temp_C": temp, 
                                       "notes": notes or None})
            
            elif step["type"] == "homogenize":
                from app.shared_parameters import COMMON_BUFFERS, COMMON_DILUENTS
                hcol1, hcol2, hcol3, hcol4 = st.columns(4)
                with hcol1:
                    medium = st.selectbox("Medium/Liquid", COMMON_BUFFERS + COMMON_DILUENTS + ["PBS", "Saline", "DI water", "Other"], key=f"homog_medium_exp_{step['id']}")
                    if medium == "Other":
                        medium = st.text_input("Specify medium", placeholder="e.g., 0.1M HCl", key=f"homog_medium_other_exp_{step['id']}")
                with hcol2:
                    rpm = st.number_input("RPM", 0, 50000, 10000, 1000, key=f"homog_rpm_exp_{step['id']}")
                    duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"homog_dur_exp_{step['id']}")
                with hcol3:
                    temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"homog_temp_exp_{step['id']}")
                    passes = st.number_input("# Passes", 1, 20, 1, 1, key=f"homog_passes_exp_{step['id']}")
                with hcol4:
                    volume = st.number_input("Volume (mL)", 0.0, 1000.0, 10.0, 1.0, key=f"homog_vol_exp_{step['id']}")
                    ratio = st.text_input("Tissue:Medium ratio", placeholder="e.g., 1:10, 1:20", key=f"homog_ratio_exp_{step['id']}")
                
                notes = st.text_input("Notes (optional)", placeholder="e.g., sterile conditions, ice bath", key=f"homog_notes_exp_{step['id']}")
                processing_steps.append({"type": "homogenize", "medium": medium, "rpm": rpm, "duration_min": duration, "temp_C": temp, "passes": passes, "volume_mL": volume, "tissue_medium_ratio": ratio, "notes": notes or None})
            
            elif step["type"] == "grind":
                gcol1, gcol2, gcol3, gcol4 = st.columns(4)
                with gcol1:
                    method = st.selectbox("Method", ["mortar_pestle", "ball_mill", "cryomill", "other"], 
                                        key=f"grind_method_exp_{step['id']}")
                    if method == "other":
                        method = st.text_input("Specify method", key=f"grind_method_other_exp_{step['id']}")
                with gcol2:
                    duration = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"grind_dur_exp_{step['id']}")
                with gcol3:
                    temp = st.number_input("Temp (°C)", -200.0, 50.0, 4.0, 1.0, key=f"grind_temp_exp_{step['id']}")
                with gcol4:
                    cycles = st.number_input("# Cycles", 1, 50, 1, 1, key=f"grind_cycles_exp_{step['id']}")
                
                notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, sterile", key=f"grind_notes_exp_{step['id']}")
                processing_steps.append({"type": "grind", "method": method, "duration_min": duration, "temp_C": temp, "cycles": cycles, "notes": notes or None})
            
            elif step["type"] == "freeze_thaw":
                ftcol1, ftcol2, ftcol3, ftcol4 = st.columns(4)
                with ftcol1:
                    cycles = st.number_input("# Cycles", 1, 50, 3, 1, key=f"ft_cycles_exp_{step['id']}")
                with ftcol2:
                    freeze_temp = st.number_input("Freeze temp (°C)", -200.0, 0.0, -80.0, 10.0, key=f"ft_ftemp_exp_{step['id']}")
                with ftcol3:
                    thaw_temp = st.number_input("Thaw temp (°C)", 0.0, 50.0, 37.0, 1.0, key=f"ft_ttemp_exp_{step['id']}")
                with ftcol4:
                    duration_cycle = st.number_input("Duration/cycle (min)", 0.0, 1000.0, 60.0, 5.0, key=f"ft_dur_exp_{step['id']}")
                
                notes = st.text_input("Notes (optional)", placeholder="e.g., liquid nitrogen, water bath", key=f"ft_notes_exp_{step['id']}")
                processing_steps.append({"type": "freeze_thaw", "cycles": cycles, "freeze_temp_C": freeze_temp, "thaw_temp_C": thaw_temp, "duration_min": duration_cycle, "notes": notes or None})
            
            elif step["type"] == "lyophilize":
                with col1:
                    unk_lyoph_dur = st.checkbox("Unk", key=f"unk_lyoph_dur_exp_{step['id']}", help="Unknown/not reported")
                    duration = st.number_input("Duration (hours)", 0.0, 200.0, 48.0, 1.0, disabled=unk_lyoph_dur, key=f"lyoph_dur_exp_{step['id']}")
                    if unk_lyoph_dur:
                        duration = None
                with col2:
                    unk_lyoph_temp = st.checkbox("Unk", key=f"unk_lyoph_temp_exp_{step['id']}", help="Unknown/not reported")
                    temp = st.number_input("Temp (°C)", -100.0, 0.0, -40.0, 5.0, disabled=unk_lyoph_temp, key=f"lyoph_temp_exp_{step['id']}")
                    if unk_lyoph_temp:
                        temp = None
                with col3:
                    pressure = st.text_input("Pressure", placeholder="e.g., <0.1 mBar", key=f"lyoph_press_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., ramp rate, condenser temp", key=f"lyoph_notes_exp_{step['id']}")
                processing_steps.append({"type": "lyophilize", "duration_hours": duration, "temp_C": temp, "pressure": pressure, "notes": notes or None})
            
            elif step["type"] == "reconstitute":
                st.caption("💡 **Critical for concentration tracking:** Enter lyophilized weight and reconstitution volume to calculate final ECM concentration")
                from shared_parameters import COMMON_DILUENTS
                recol1, recol2, recol3, recol4 = st.columns(4)
                with recol1:
                    solvent_sel = st.selectbox("Solvent", COMMON_DILUENTS, key=f"recon_solv_sel_exp_{step['id']}")
                    if solvent_sel == "Other":
                        solvent = st.text_input("Specify solvent", placeholder="e.g., custom buffer", key=f"recon_solv_other_exp_{step['id']}")
                    else:
                        solvent = solvent_sel
                with recol2:
                    unk_lyoph_weight = st.checkbox("Unk", key=f"unk_recon_wt_exp_{step['id']}", help="Unknown/not reported")
                    lyoph_weight_mg = st.number_input("Lyoph weight (mg)", 0.0, 10000.0, 100.0, 1.0, disabled=unk_lyoph_weight, key=f"recon_wt_exp_{step['id']}",
                                                     help="Dry weight of lyophilized ECM powder")
                    if unk_lyoph_weight:
                        lyoph_weight_mg = None
                with recol3:
                    unk_recon_vol = st.checkbox("Unk", key=f"unk_recon_vol_exp_{step['id']}", help="Unknown/not reported")
                    recon_volume_mL = st.number_input("Recon volume (mL)", 0.0, 1000.0, 10.0, 0.1, disabled=unk_recon_vol, key=f"recon_vol_exp_{step['id']}",
                                                      help="Volume of solvent added to reconstitute")
                    if unk_recon_vol:
                        recon_volume_mL = None
                with recol4:
                    unk_recon_temp = st.checkbox("Unk", key=f"unk_recon_temp_exp_{step['id']}", help="Unknown/not reported")
                    recon_temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, disabled=unk_recon_temp, key=f"recon_temp_exp_{step['id']}",
                                                 help="Temperature during reconstitution/stirring")
                    if unk_recon_temp:
                        recon_temp = None
                # Calculate final concentration
                if lyoph_weight_mg and recon_volume_mL and lyoph_weight_mg > 0 and recon_volume_mL > 0:
                    final_conc = lyoph_weight_mg / recon_volume_mL
                    st.success(f"✅ **Final concentration: {final_conc:.2f} mg/mL**")
                notes = st.text_input("Notes (optional)", placeholder="e.g., stirred overnight at 4°C, with pepsin 0.1 mg/mL", key=f"recon_notes_exp_{step['id']}",
                                     help="Pepsin digestion often happens here!")
                processing_steps.append({"type": "reconstitute", "solvent": solvent, "lyoph_weight_mg": lyoph_weight_mg, 
                                       "recon_volume_mL": recon_volume_mL, "final_conc_mgml": final_conc if (lyoph_weight_mg and recon_volume_mL) else None,
                                       "temp_C": recon_temp, "notes": notes or None})
            
            elif step["type"] == "ph_adjust":
                from shared_parameters import COMMON_BASES, COMMON_ACIDS
                phcol1, phcol2, phcol3, phcol4 = st.columns(4)
                with phcol1:
                    direction = st.radio("Direction", ["Raise pH (base)", "Lower pH (acid)"], key=f"ph_dir_exp_{step['id']}", horizontal=True)
                    if "base" in direction.lower():
                        reagent_sel = st.selectbox("Base", COMMON_BASES, key=f"ph_reag_sel_exp_{step['id']}")
                    else:
                        reagent_sel = st.selectbox("Acid", COMMON_ACIDS, key=f"ph_reag_sel_exp_{step['id']}")
                    if reagent_sel == "Other":
                        reagent = st.text_input("Specify reagent", placeholder="e.g., custom buffer", key=f"ph_reag_other_exp_{step['id']}")
                    else:
                        reagent = reagent_sel
                with phcol2:
                    conc_val = st.number_input("Stock conc", 0.0, 12.0, 1.0, 0.1, key=f"ph_conc_exp_{step['id']}")
                    conc_unit = st.selectbox("Units", ["M","mM","N","%"], key=f"ph_unit_exp_{step['id']}")
                with phcol3:
                    target_ph = st.number_input("Target pH", 0.0, 14.0, 7.4, 0.1, key=f"ph_target_exp_{step['id']}")
                with phcol4:
                    volume_ul = st.number_input("Volume added (µL)", 0.0, 10000.0, 500.0, 10.0, key=f"ph_vol_exp_{step['id']}")
                temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"ph_temp_exp_{step['id']}", help="Temperature during pH adjustment")
                notes = st.text_input("Notes (optional)", placeholder="e.g., stir rate, equilibration time", key=f"ph_notes_exp_{step['id']}")
                processing_steps.append({"type": "ph_adjust", "reagent": reagent, "concentration": conc_val, 
                                       "conc_units": conc_unit, "target_ph": target_ph, "volume_uL": volume_ul, 
                                       "temp_C": temp, "notes": notes or None})
            
            elif step["type"] == "dialysis":
                from shared_parameters import COMMON_BUFFERS, COMMON_ACIDS
                diacol1, diacol2, diacol3, diacol4 = st.columns(4)
                with diacol1:
                    buffer_sel = st.selectbox("Buffer/Solution", COMMON_BUFFERS + COMMON_ACIDS, key=f"dial_buf_sel_exp_{step['id']}")
                    if buffer_sel == "Other":
                        buffer = st.text_input("Specify buffer", placeholder="e.g., custom buffer", key=f"dial_buf_other_exp_{step['id']}")
                    else:
                        buffer = buffer_sel
                with diacol2:
                    conc_val = st.number_input("Concentration", 0.0, 10.0, 0.01, 0.001, key=f"dial_conc_exp_{step['id']}", 
                                              help="e.g., 0.01 M acetic acid, 1× PBS")
                    conc_unit = st.selectbox("Units", ["M","mM","x","pH units","% (v/v)"], key=f"dial_unit_exp_{step['id']}")
                with diacol3:
                    changes = st.number_input("# Changes", 1, 50, 3, 1, key=f"dial_chg_exp_{step['id']}")
                    duration = st.number_input("Total duration (hours)", 0.0, 200.0, 24.0, 1.0, key=f"dial_dur_exp_{step['id']}")
                with diacol4:
                    temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"dial_temp_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., MWCO 3.5kDa, stirring, volume ratio 1:100", key=f"dial_notes_exp_{step['id']}")
                processing_steps.append({"type": "dialysis", "buffer": buffer, "concentration": conc_val, 
                                       "conc_units": conc_unit, "n_changes": changes, "duration_hours": duration, 
                                       "temp_C": temp, "notes": notes or None})
            
            elif step["type"] == "storage":
                scol1, scol2, scol3, scol4 = st.columns(4)
                with scol1:
                    temp = st.number_input("Temp (°C)", -200.0, 50.0, -80.0, 1.0, key=f"stor_temp_exp_{step['id']}")
                with scol2:
                    duration = st.text_input("Duration", placeholder="e.g., 7 days, 3 months", key=f"stor_dur_exp_{step['id']}")
                with scol3:
                    container = st.selectbox("Container", ["tube", "vial", "bag", "plate", "other"], key=f"stor_container_exp_{step['id']}")
                with scol4:
                    atmosphere = st.selectbox("Atmosphere", ["air", "nitrogen", "vacuum", "argon"], key=f"stor_atmo_exp_{step['id']}")
                
                notes = st.text_input("Notes (optional)", placeholder="e.g., sterile, labeled", key=f"stor_notes_exp_{step['id']}")
                processing_steps.append({"type": "storage", "temp_C": temp, "duration": duration, "container": container, "atmosphere": atmosphere, "notes": notes or None})
            
            elif step["type"] == "filtration":
                fcol1, fcol2, fcol3, fcol4 = st.columns(4)
                with fcol1:
                    filter_type = st.selectbox("Filter type", ["spin_filter", "syringe_filter", "vacuum_filter", "gravity_filter", "other"], 
                                              key=f"filt_type_exp_{step['id']}")
                with fcol2:
                    pore_size = st.text_input("Pore size", placeholder="e.g., 0.22 µm, 100 kDa", key=f"filt_pore_exp_{step['id']}")
                with fcol3:
                    if filter_type == "spin_filter":
                        rpm = st.number_input("RPM", 0, 20000, 3000, 500, key=f"filt_rpm_exp_{step['id']}")
                        duration_min = st.number_input("Duration (min)", 0.0, 500.0, 10.0, 1.0, key=f"filt_dur_exp_{step['id']}")
                    else:
                        rpm = None
                        duration_min = st.number_input("Duration (min)", 0.0, 500.0, 5.0, 1.0, key=f"filt_dur_exp_{step['id']}")
                with fcol4:
                    temp = st.number_input("Temp (°C)", 0.0, 50.0, 4.0, 1.0, key=f"filt_temp_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., filter brand, pre-wet, flow rate", key=f"filt_notes_exp_{step['id']}")
                processing_steps.append({"type": "filtration", "filter_type": filter_type, "pore_size": pore_size, 
                                       "rpm": rpm, "duration_min": duration_min, "temp_C": temp, "notes": notes or None})
            
            elif step["type"] == "centrifuge":
                ccol1, ccol2, ccol3, ccol4 = st.columns(4)
                with ccol1:
                    purpose = st.selectbox("Purpose", ["clarification", "concentration", "pellet_removal", "debris_removal", "other"], key=f"cent_purp_exp_{step['id']}")
                    if purpose == "other":
                        purpose = st.text_input("Specify purpose", key=f"cent_purp_other_exp_{step['id']}")
                with ccol2:
                    speed = st.number_input("Speed (RCF)", 0, 50000, 3000, 100, key=f"cent_speed_exp_{step['id']}")
                    duration = st.number_input("Duration (min)", 0.0, 300.0, 10.0, 1.0, key=f"cent_dur_exp_{step['id']}")
                with ccol3:
                    temp = st.number_input("Temp (°C)", -80.0, 50.0, 22.0, 1.0, key=f"cent_temp_exp_{step['id']}")
                    cycles = st.number_input("# Cycles", 1, 10, 1, 1, key=f"cent_cycles_exp_{step['id']}")
                with ccol4:
                    volume = st.number_input("Volume (mL)", 0.0, 1000.0, 50.0, 5.0, key=f"cent_vol_exp_{step['id']}")
                
                notes = st.text_input("Notes (optional)", placeholder="e.g., rotor type, brake settings", key=f"cent_notes_exp_{step['id']}")
                processing_steps.append({"type": "centrifuge", "purpose": purpose, "speed_rcf": speed, "duration_min": duration, "temp_C": temp, "cycles": cycles, "volume_mL": volume, "notes": notes or None})
            
            elif step["type"] == "other":
                with col1:
                    step_name = st.text_input("Step name", placeholder="e.g., sonication", key=f"other_name_exp_{step['id']}")
                with col2:
                    duration = st.text_input("Duration", placeholder="e.g., 30 min", key=f"other_dur_exp_{step['id']}")
                with col3:
                    details = st.text_input("Details", key=f"other_detail_exp_{step['id']}")
                processing_steps.append({"type": "other", "step_name": step_name, "duration": duration, "details": details})
            
            # Remove button
            if st.button("🗑️ Remove", key=f"remove_step_exp_{step['id']}"):
                st.session_state.proc_steps.pop(i)
                st.rerun()
    
    # Gelation Protocol Builder (OUTSIDE form - uses buttons)
    st.markdown("---")
    st.subheader("🧪 Gelation Protocol Builder")
    st.caption("Track neutralization, gel formation, and post-gel handling")
    
    # Initialize session state for gelation steps
    if "gel_steps" not in st.session_state:
        st.session_state.gel_steps = []
    
    # Buttons to add gelation step types
    st.caption("**Add Gelation Steps:**")
    gel_row1_exp = st.columns(6)
    with gel_row1_exp[0]:
        if st.button("➕ Dilute/Conc", key="add_dilute_exp"):
            st.session_state.gel_steps.append({"type": "dilute", "id": len(st.session_state.gel_steps)})
            st.rerun()
    with gel_row1_exp[1]:
        if st.button("➕ Add Reagent", key="add_addreag_exp"):
            st.session_state.gel_steps.append({"type": "add_reagent", "id": len(st.session_state.gel_steps)})
            st.rerun()
    with gel_row1_exp[2]:
        if st.button("➕ pH Adjust", key="add_ph_gel_exp"):
            st.session_state.gel_steps.append({"type": "ph_adjust_gel", "id": len(st.session_state.gel_steps)})
            st.rerun()
    with gel_row1_exp[3]:
        if st.button("➕ Incubate", key="add_incubate_exp"):
            st.session_state.gel_steps.append({"type": "incubate", "id": len(st.session_state.gel_steps)})
            st.rerun()
    with gel_row1_exp[4]:
        if st.button("➕ Media Wash", key="add_mediawash_exp"):
            st.session_state.gel_steps.append({"type": "media_wash", "id": len(st.session_state.gel_steps)})
            st.rerun()
    with gel_row1_exp[5]:
        if st.button("➕ Hydrate", key="add_hydrate_exp"):
            st.session_state.gel_steps.append({"type": "hydrate", "id": len(st.session_state.gel_steps)})
            st.rerun()
    
    gel_row2_exp = st.columns(6)
    with gel_row2_exp[0]:
        if st.button("➕ Stability Test", key="add_stab_exp"):
            st.session_state.gel_steps.append({"type": "stability", "id": len(st.session_state.gel_steps)})
            st.rerun()
    with gel_row2_exp[1]:
        if st.button("➕ Other", key="add_other_gel_exp"):
            st.session_state.gel_steps.append({"type": "other_gel", "id": len(st.session_state.gel_steps)})
            st.rerun()
    with gel_row2_exp[2]:
        st.write("")  # Spacer
    with gel_row2_exp[3]:
        st.write("")  # Spacer
    with gel_row2_exp[4]:
        st.write("")  # Spacer
    with gel_row2_exp[5]:
        if st.button("🗑️ Clear All", key="clear_gel_steps_exp"):
            st.session_state.gel_steps = []
            st.rerun()
    
    if st.session_state.gel_steps:
        st.caption(f"**{len(st.session_state.gel_steps)} gelation step(s) added**")
    
    # Display and edit each gelation step
    gelation_steps = []
    for i, step in enumerate(st.session_state.gel_steps):
        with st.expander(f"Gel Step {i+1}: {step['type'].replace('_', ' ').title()}", expanded=True):
            gcol1, gcol2, gcol3 = st.columns([3, 3, 1])
            
            if step["type"] == "dilute":
                from shared_parameters import COMMON_DILUENTS
                dilcol1, dilcol2, dilcol3 = st.columns(3)
                with dilcol1:
                    from_conc = st.number_input("From (mg/mL)", 0.0, 200.0, 10.0, 0.1, key=f"dil_from_exp_{step['id']}")
                    to_conc = st.number_input("To (mg/mL)", 0.0, 200.0, 5.0, 0.1, key=f"dil_to_exp_{step['id']}")
                with dilcol2:
                    diluent_sel = st.selectbox("Diluent", COMMON_DILUENTS, key=f"dil_dil_sel_exp_{step['id']}")
                    if diluent_sel == "Other":
                        diluent = st.text_input("Specify diluent", key=f"dil_dil_other_exp_{step['id']}")
                    else:
                        diluent = diluent_sel
                with dilcol3:
                    dilution_factor = round(from_conc / to_conc, 2) if to_conc > 0 else 0
                    st.metric("Dilution factor", f"{dilution_factor}×")
                notes = st.text_input("Notes (optional)", placeholder="e.g., mixing method, equilibration time", key=f"dil_notes_exp_{step['id']}")
                gelation_steps.append({"type": "dilute", "from_mgml": from_conc, "to_mgml": to_conc, "diluent": diluent, "dilution_factor": dilution_factor, "notes": notes or None})
            
            elif step["type"] == "add_reagent":
                from shared_parameters import COMMON_BUFFERS, COMMON_BASES, COMMON_SALTS, REAGENT_PURPOSES
                arcol1, arcol2, arcol3, arcol4 = st.columns(4)
                with arcol1:
                    reagent_sel = st.selectbox("Reagent", COMMON_BUFFERS + COMMON_BASES + COMMON_SALTS + ["Other"], key=f"add_reag_sel_exp_{step['id']}")
                    if reagent_sel == "Other":
                        reagent = st.text_input("Specify reagent", placeholder="e.g., custom reagent", key=f"add_reag_other_exp_{step['id']}")
                    else:
                        reagent = reagent_sel
                with arcol2:
                    conc_val = st.number_input("Stock conc", 0.0, 100.0, 10.0, 0.1, key=f"add_conc_exp_{step['id']}")
                    conc_unit = st.selectbox("Units", ["x","M","mM","%","mg/mL"], key=f"add_unit_exp_{step['id']}")
                with arcol3:
                    volume_ul_per_ml = st.number_input("µL per mL ECM", 0.0, 1000.0, 100.0, 10.0, key=f"add_vol_exp_{step['id']}", 
                                                       help="e.g., 100 µL of 10× PBS per 1 mL ECM")
                with arcol4:
                    purpose_sel = st.selectbox("Purpose", REAGENT_PURPOSES, key=f"add_purp_exp_{step['id']}")
                    if purpose_sel == "Other":
                        purpose = st.text_input("Specify purpose", key=f"add_purp_other_exp_{step['id']}")
                    else:
                        purpose = purpose_sel
                notes = st.text_input("Notes (optional)", placeholder="e.g., add slowly with stirring, on ice", key=f"add_notes_exp_{step['id']}")
                gelation_steps.append({"type": "add_reagent", "reagent": reagent, "stock_conc": conc_val, 
                                     "conc_units": conc_unit, "volume_uL_per_mL": volume_ul_per_ml, "purpose": purpose, "notes": notes or None})
            
            elif step["type"] == "ph_adjust_gel":
                from shared_parameters import COMMON_BASES, COMMON_ACIDS
                phgcol1, phgcol2, phgcol3, phgcol4 = st.columns(4)
                with phgcol1:
                    direction = st.radio("Direction", ["Raise (base)", "Lower (acid)"], key=f"ph_gel_dir_exp_{step['id']}", horizontal=True)
                    if "base" in direction.lower():
                        reagent_sel = st.selectbox("Base", COMMON_BASES, key=f"ph_gel_reag_sel_exp_{step['id']}")
                    else:
                        reagent_sel = st.selectbox("Acid", COMMON_ACIDS, key=f"ph_gel_reag_sel_exp_{step['id']}")
                    if reagent_sel == "Other":
                        reagent = st.text_input("Specify", key=f"ph_gel_reag_other_exp_{step['id']}")
                    else:
                        reagent = reagent_sel
                with phgcol2:
                    conc_val = st.number_input("Stock conc", 0.0, 12.0, 1.0, 0.1, key=f"ph_gel_conc_exp_{step['id']}")
                    conc_unit = st.selectbox("Units", ["M","mM","N","%"], key=f"ph_gel_unit_exp_{step['id']}")
                with phgcol3:
                    target_ph = st.number_input("Target pH", 0.0, 14.0, 7.2, 0.1, key=f"ph_gel_target_exp_{step['id']}")
                with phgcol4:
                    volume_ul_per_ml = st.number_input("µL per mL ECM", 0.0, 1000.0, 50.0, 10.0, key=f"ph_gel_vol_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., dropwise addition, mixing time", key=f"ph_gel_notes_exp_{step['id']}")
                gelation_steps.append({"type": "ph_adjust_gel", "reagent": reagent, "stock_conc": conc_val, 
                                     "conc_units": conc_unit, "target_ph": target_ph, "volume_uL_per_mL": volume_ul_per_ml, "notes": notes or None})
            
            elif step["type"] == "incubate":
                with gcol1:
                    temp = st.number_input("Temp (°C)", 0.0, 60.0, 37.0, 0.5, key=f"inc_temp_exp_{step['id']}")
                with gcol2:
                    duration = st.text_input("Duration", placeholder="e.g., 60 min, 2 hours", key=f"inc_dur_exp_{step['id']}")
                with gcol3:
                    conditions = st.text_input("Conditions", placeholder="e.g., humid chamber", key=f"inc_cond_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., covered, CO2 atmosphere", key=f"inc_notes_exp_{step['id']}")
                gelation_steps.append({"type": "incubate", "temp_C": temp, "duration": duration, "conditions": conditions, "notes": notes or None})
            
            elif step["type"] == "media_wash":
                with gcol1:
                    media = st.text_input("Media", placeholder="e.g., DMEM, culture media", key=f"mw_media_exp_{step['id']}")
                with gcol2:
                    n_washes = st.number_input("# Washes", 1, 20, 3, 1, key=f"mw_num_exp_{step['id']}")
                with gcol3:
                    duration = st.number_input("Duration each (min)", 0.0, 500.0, 15.0, 5.0, key=f"mw_dur_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., warm media, gentle pipetting", key=f"mw_notes_exp_{step['id']}")
                gelation_steps.append({"type": "media_wash", "media": media, "n_washes": n_washes, "duration_min": duration, "notes": notes or None})
            
            elif step["type"] == "hydrate":
                with gcol1:
                    solution = st.text_input("Solution", placeholder="e.g., DMEM, PBS", key=f"hyd_sol_exp_{step['id']}")
                with gcol2:
                    duration = st.text_input("Duration", placeholder="e.g., 24 hours, 3 days", key=f"hyd_dur_exp_{step['id']}")
                with gcol3:
                    temp = st.number_input("Temp (°C)", 0.0, 50.0, 37.0, 1.0, key=f"hyd_temp_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., volume of solution, container type", key=f"hyd_notes_exp_{step['id']}")
                gelation_steps.append({"type": "hydrate", "solution": solution, "duration": duration, "temp_C": temp, "notes": notes or None})
            
            elif step["type"] == "stability":
                with gcol1:
                    test_type = st.selectbox("Test", ["hydrated_stability", "unhydrated_stability", "media_stability"], 
                                           key=f"stab_type_exp_{step['id']}")
                with gcol2:
                    duration = st.text_input("Duration", placeholder="e.g., 7 days, 2 weeks", key=f"stab_dur_exp_{step['id']}")
                with gcol3:
                    outcome = st.text_input("Outcome", placeholder="e.g., stable, degraded at day 3", key=f"stab_out_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., storage conditions, observation frequency", key=f"stab_notes_exp_{step['id']}")
                gelation_steps.append({"type": "stability", "test_type": test_type, "duration": duration, "outcome": outcome, "notes": notes or None})
            
            elif step["type"] == "other_gel":
                with gcol1:
                    step_name = st.text_input("Step name", placeholder="e.g., crosslinking", key=f"other_gel_name_exp_{step['id']}")
                with gcol2:
                    duration = st.text_input("Duration", placeholder="e.g., 30 min", key=f"other_gel_dur_exp_{step['id']}")
                with gcol3:
                    details = st.text_input("Details", key=f"other_gel_det_exp_{step['id']}")
                notes = st.text_input("Notes (optional)", placeholder="e.g., specific conditions or parameters", key=f"other_gel_notes_exp_{step['id']}")
                gelation_steps.append({"type": "other_gel", "step_name": step_name, "duration": duration, "details": details, "notes": notes or None})
            
            # Remove button
            if st.button("🗑️ Remove", key=f"remove_gel_step_exp_{step['id']}"):
                st.session_state.gel_steps.pop(i)
                st.rerun()
    
    # Continue with the form
    with st.form("new_well_form"):
        st.subheader("💧 Composition Measurements")
        c1,c2,c3 = st.columns(3)
        with c1:
            ecm_total_protein_mgml = st.number_input("Total protein (mg/mL)*", 0.0, 100.0, 7.0, 0.1)
            protein_assay_method = st.selectbox("Protein assay method", ["","BCA","Bradford","Lowry","DC_assay","A280","Biuret","other"],
                                               help="Method used to measure protein concentration")
            show_measurement_protocol("ecm_total_protein_mgml")
            
            gel_volume_uL = st.number_input("Gel volume per well (μL)", 1.0, 5000.0, 700.0, 10.0,
                                           help="Total volume of hydrogel per well. Used for spatial seeding height calculations in cell culture.")
            
            pre_pH = st.number_input("Pre-neutralization pH*", 0.0, 14.0, 4.0, 0.1)
            show_measurement_protocol("pre_pH")
            
            pre_conductivity_mS = st.number_input("Pre-conductivity (mS/cm)*", 0.0, 100.0, 3.0, 0.1)
            show_measurement_protocol("pre_conductivity_mS")
        with c2:
            temp_incubation_C = st.number_input("Incubation temp (°C)*", 0.0, 60.0, 37.0, 0.5)
            
            uv_A220 = st.number_input("UV A220", 0.0, step=0.01)
            uv_A280 = st.number_input("UV A280", 0.0, step=0.01)
            show_measurement_protocol("uv_A220")
        with c3:
            # UV ratio - read-only if auto-computed
            auto_ratio = (uv_A220 > 0 and uv_A280 > 0)
            if auto_ratio:
                computed_ratio = uv_A220 / uv_A280
                st.text_input("UV ratio A220/A280 (auto)", value=f"{computed_ratio:.3f}", disabled=True, help="Auto-computed from A220/A280")
                uv_ratio_A220_A280 = computed_ratio
            else:
                uv_ratio_A220_A280 = st.number_input("UV ratio A220/A280", 0.0, 50.0, 0.0, 0.01, help="Auto-computed if A220 & A280 given")
            sds_smear_index = st.number_input("SDS smear index (0-1)", 0.0, 1.0, 0.4, 0.01)
            sds_alpha_ratio = st.number_input("SDS α-ratio", 0.0, 5.0, 0.9, 0.05)

        st.subheader("🧪 Test Conditions")
        c1,c2,c3 = st.columns(3)
        with c1:
            probe_type = st.selectbox("Probe Type*", options=[""] + codebook['probe_type'])
            target_pH = st.number_input("Target pH*", 0.0, 14.0, 7.2, 0.05)
        with c2:
            od_wavelength_nm = st.number_input("OD wavelength (nm)", 350, 800, 405, 5)
            od_sampling_interval_min = st.number_input("OD sampling interval (min)", 1, 120, 2)
        with c3:
            pass

        st.subheader("🧫 Post-Gelation Reagents (unit-safe)")
        st.caption("💡 **AFTER gel forms**: Media, supplements, or reagents added to the formed gel (DMEM, growth factors, drugs, etc.)")
        reagents_data = []
        with st.expander("Add reagents with stock + volume (effective mM auto)", expanded=False):
            n = st.number_input("How many reagents?", 0, 16, 2, 1)
            for i in range(int(n)):
                st.markdown(f"**Reagent {i+1}**")
                r1,r2,r3,r4,r5 = st.columns([2,1,1,1,1])
                with r1: name = st.text_input("Name", key=f"rname{i}")
                with r2: rclass = st.selectbox("Class", ["buffer","base","acid","salt","media","additive","enzyme","crosslinker","other"], key=f"rclass{i}")
                with r3: stock = st.number_input("Stock", 0.0, 1e9, 1.0, 0.1, key=f"rstk{i}")
                with r4: units = st.selectbox("Units", ["M","mM","µM","%","x","mg/mL","U/mL"], key=f"runits{i}")
                with r5: vol = st.number_input("µL per mL", 0.0, 1000.0, 0.0, 0.5, key=f"rvol{i}")
                
                # Calculate and display effective concentrations
                eff = effective_mM(stock, units, vol)
                if eff is not None:
                    st.caption(f"→ effective ~ **{eff:.2f} mM**")
                else:
                    st.caption(f"→ effective: n/a for {units}")
                
                # Extra live hints for PBS and DMEM
                name_lower = (name or "").strip().lower()
                if units == "x" and "pbs" in name_lower:
                    final_x = pbs_final_x(stock, vol)
                    if final_x is not None:
                        st.caption(f"PBS final ≈ **{final_x:.2f}×** (from {stock:g}× @ {vol:g} µL/mL)")
                if "dmem" in name_lower or ("media" in (rclass or "").lower()):
                    media_pct = dmem_final_percent(vol)
                    if media_pct is not None and media_pct > 0:
                        st.caption(f"Media final ≈ **{media_pct:.2f}% v/v**")
                
                lot = st.text_input("Lot #", key=f"rlot{i}")
                purpose = st.text_input("Purpose", key=f"rpurpose{i}", help="e.g., neutralization, buffer_adjust, ionic_adjust")
                st.markdown("---")
                if name:
                    reagents_data.append(dict(
                        reagent_name=name, reagent_class=rclass, purpose=purpose or None,
                        stock_conc_value=stock, stock_conc_units=units,
                        volume_uL_per_mL=vol, effective_conc_mM=eff,
                        lot_number=lot or None, added_order=i+1
                    ))

        st.info("💡 **For longitudinal tracking**: Use the **Events** tab to log time-series observations (Day 1, Day 3, etc.) and media changes over time")
        
        st.subheader("📊 Outcomes")
        c1,c2,c3 = st.columns(3)
        with c1:
            gel_binary = st.selectbox("Gel formed?*", options=["",0,1], format_func=lambda x: "" if x=="" else ("Yes" if x==1 else "No"))
            gel_strength_score = st.selectbox("Gel strength (0-3)", options=["",0,1,2,3])
            time_to_halfmax_min = st.number_input("Time to half-max (min)", 0.0, 1e6, 0.0, 1.0)
        with c2:
            failure_mode = st.selectbox("Failure mode", options=[""] + codebook['failure_mode'])
            suspected_cause = st.selectbox("Suspected cause", options=[""] + codebook['suspected_cause'])
            confidence_0to1 = st.number_input("Confidence (0-1)", 0.0, 1.0, 0.5, 0.1)
        with c3:
            color_shift = st.selectbox("Color shift", options=[""] + codebook['color_shift'])
            syneresis_binary = st.selectbox("Syneresis?", options=["",0,1])
            precipitate_binary = st.selectbox("Precipitate?", options=["",0,1])
        
        # Degradation & Plate Adhesion
        st.markdown("**Degradation & Physical Behavior**")
        deg1, deg2, deg3 = st.columns(3)
        with deg1:
            disintegrated = st.selectbox("Disintegrated?", options=["",0,1], format_func=lambda x: "" if x=="" else ("Yes" if x==1 else "No"), help="Did gel break apart into pieces?")
            days_to_disintegration = st.number_input("Days to disintegration", 0, 1000, 0, help="Days until gel fell apart")
        with deg2:
            reliquefied = st.selectbox("Reliquefied (back to liquid)?", options=["",0,1], format_func=lambda x: "" if x=="" else ("Yes" if x==1 else "No"), help="Did gel return to liquid state?")
            days_to_reliquefaction = st.number_input("Days to reliquefaction", 0, 1000, 0, help="Days until gel became liquid again")
        with deg3:
            plate_adhesion = st.selectbox("Plate adhesion", options=["","adhered","floating","mixed"], help="Does gel stick to plate or float? (can be induced or spontaneous)")
            adhesion_notes = st.text_input("Adhesion notes", placeholder="e.g., 'floated spontaneously at Day 3' or 'adhered, induced by media flow'", help="Note if induced vs spontaneous")
        
        # Gelation Kinetics & Pre-Gelation Storage
        st.markdown("**Gelation Kinetics & Pre-Gelation Conditions**")
        kin1, kin2, kin3 = st.columns(3)
        with kin1:
            time_to_gel_min = st.number_input("Time to gel (min)", 0.0, 10000.0, 0.0, 1.0, help="How long did it take for gel to form after adding reagents?")
        with kin2:
            pre_gel_storage_temp_C = st.number_input("Pre-gel storage temp (°C)", -80.0, 40.0, 4.0, 0.5, help="Temperature at which ECM was stored before adding gelation reagents")
            pre_gel_storage_duration_min = st.number_input("Pre-gel storage duration (min)", 0.0, 100000.0, 0.0, 1.0, help="How long was ECM left without reagents before gelation?")
        with kin3:
            pre_gel_storage_notes = st.text_input("Pre-gel storage notes", placeholder="e.g., 'kept on ice while preparing reagents'", help="Additional context about storage before gelation")

        st.subheader("📝 Notes")
        notes_pre = st.text_area("Notes (pre-experiment)", height=100)
        notes_post = st.text_area("Notes (post-experiment)", height=100)

        split = st.selectbox("Dataset split", options=[""] + codebook['split'])

        submitted = st.form_submit_button("💾 Save Well Entry", type="primary")
        if submitted:
            # Check if wells are selected
            if not st.session_state.selected_wells:
                st.error("❌ Please select at least one well position.")
                return
            
            # Process each selected well
            created_records = []
            for i, well_id in enumerate(st.session_state.selected_wells):
                # Parse well position
                well_row = well_id[0]
                well_col = int(well_id[1:])
                
                # Generate semantic record ID (includes species/tissue for decECM)
                proposed_id = generate_semantic_id(
                    family, batch_id, plate_id, well_row, well_col, replicate_id + i,
                    species=dec_species, tissue=dec_tissue
                )
                final_record_id = ensure_unique_record_id(proposed_id)
            
            # Prepare preliminary payload for validation
            validation_payload = {
                'record_id': final_record_id,
                'operator_id': operator_id,
                'family': family,
                'batch_id': batch_id,
                'gel_binary': gel_binary,
                'ecm_total_protein_mgml': ecm_total_protein_mgml,
                'pre_pH': pre_pH,
                'pre_conductivity_mS': pre_conductivity_mS,
                'temp_incubation_C': temp_incubation_C,
                'target_pH': target_pH,
            }
            
            # Validate against spec (relaxed - only essential fields required)
            errors = validate_against_spec("wells_master_v4", FIELD_SPEC, validation_payload)
            
            # Show warnings for recommended fields (but don't block save)
            warnings = []
            if family == "decECM":
                if not dec_species or dec_species == "":
                    warnings.append("⚠️ Tip: ecm_origin_species is recommended for decECM (can add later)")
                if not dec_tissue or dec_tissue == "":
                    warnings.append("⚠️ Tip: ecm_source_tissue is recommended for decECM (can add later)")
            
            if errors:
                for e in errors: 
                    st.error(f"❌ {e}")
                st.info("💡 Only essential fields (date, operator, family, batch) are required. Fill in details later via Edit.")
                return
            
            if warnings:
                for w in warnings:
                    st.warning(w)
            
                # Geometry bounds guard
                if well_row and well_row not in row_labels:
                    st.error(f"❌ Selected row '{well_row}' is not valid for this plate (rows: {row_labels}).")
                    return
                if well_col < 1 or well_col > int(max_cols):
                    st.error(f"❌ Column {well_col} exceeds plate bounds (1–{max_cols}).")
                    return

                data = {
                    'record_id': final_record_id,
                    'date': date_input.isoformat(),
                    'operator_id': operator_id,
                    'family': family,
                    'is_commercial_product': int(is_commercial) if is_commercial else 0,
                    'commercial_vendor': vendor if is_commercial else None,
                    'commercial_product_name': (custom_product or product_name) if is_commercial else None,
                    'commercial_catalog_number': catalog_num if is_commercial else None,
                    'commercial_lot_number': lot_num if is_commercial else None,
                    'commercial_website': website if is_commercial else None,
                    'batch_id': batch_id,
                    'gelation_id': gelation_id or None,
                    'donor_id': donor_id or None,
                    'ecm_origin_species': dec_species or None,
                    'ecm_source_tissue': dec_tissue or None,
                    'plate_id': plate_id or None,
                    'row': well_row or None,
                    'col': well_col,
                    'replicate_id': replicate_id + i,

                'pre_storage_days_4C': (None if pre_storage_days==0 else int(pre_storage_days)) if pre_storage_temp in ["", "4°C (fridge)"] else None,
                'pre_storage_fresh_notes': pre_storage_fresh_notes or None,
                'pre_storage_freeze_cycles': pre_storage_freeze_cycles,
                'pre_storage_temp_freezer': None if pre_storage_temp_freezer == -80.0 and pre_storage_duration_months == 0 else pre_storage_temp_freezer,
                'pre_storage_duration_months': None if pre_storage_duration_months == 0 else pre_storage_duration_months,
                'pre_storage_frozen_in': pre_storage_frozen_in or None,
                'pre_storage_thaw_method': pre_storage_thaw_method or None,
                'pre_storage_thaw_duration_min': pre_storage_thaw_duration_min,
                'pre_storage_ft_notes': pre_storage_ft_notes or None,
                'processing_protocol': json.dumps(processing_steps) if processing_steps else None,
                'gelation_protocol': json.dumps(gelation_steps) if gelation_steps else None,

                'ecm_total_protein_mgml': ecm_total_protein_mgml,
                'protein_assay_method': protein_assay_method or None,
                'gel_volume_uL': gel_volume_uL if gel_volume_uL > 0 else None,
                'pre_pH': pre_pH,
                'pre_conductivity_mS': pre_conductivity_mS,
                'temp_incubation_C': temp_incubation_C,

                'uv_A220': uv_A220 if uv_A220>0 else None,
                'uv_A230': None,  # add field to UI later if needed
                'uv_A260': None,
                'uv_A280': uv_A280 if uv_A280>0 else None,
                'uv_ratio_A220_A280': uv_ratio_A220_A280 if uv_ratio_A220_A280>0 else None,

                'sds_smear_index': sds_smear_index,
                'sds_alpha_ratio': sds_alpha_ratio,

                'hydroxyproline_mgml': None,
                'dmmB_GAG_ugml': None,
                'viscosity_proxy_sec': None,

                'probe_type': probe_type or None,
                'target_pH': target_pH,

                'od_wavelength_nm': od_wavelength_nm,
                'od_sampling_interval_min': od_sampling_interval_min,
                'time_to_halfmax_min': time_to_halfmax_min if time_to_halfmax_min>0 else None,
                'slope_OD_per_min': None,
                'final_OD': None,
                'lag_time_min': None,

                'gel_binary': int(gel_binary),
                'gel_strength_score_0to3': None if gel_strength_score=="" else int(gel_strength_score),
                'tilt_test_angle_deg': None,
                'time_to_handle_min': None,

                'failure_mode': failure_mode or None,
                'suspected_cause': suspected_cause or None,
                'confidence_0to1': confidence_0to1 if confidence_0to1>0 else None,
                'syneresis_binary': None if syneresis_binary=="" else int(syneresis_binary),
                'syneresis_time_min': None,
                'precipitate_binary': None if precipitate_binary=="" else int(precipitate_binary),
                'color_shift': color_shift or None,
                
                'disintegrated': None if disintegrated=="" else int(disintegrated),
                'days_to_disintegration': None if days_to_disintegration==0 else int(days_to_disintegration),
                'reliquefied': None if reliquefied=="" else int(reliquefied),
                'days_to_reliquefaction': None if days_to_reliquefaction==0 else int(days_to_reliquefaction),
                'plate_adhesion': plate_adhesion or None,
                'adhesion_notes': adhesion_notes or None,
                
                'time_to_gel_min': None if time_to_gel_min==0 else time_to_gel_min,
                'pre_gel_storage_temp_C': pre_gel_storage_temp_C,
                'pre_gel_storage_duration_min': None if pre_gel_storage_duration_min==0 else pre_gel_storage_duration_min,
                'pre_gel_storage_notes': pre_gel_storage_notes or None,

                'notes_pre': notes_pre or None,
                'notes_post': notes_post or None,

                'app_recipe_recommended': None,
                'app_pgel_pred': None,
                'app_thalf_pred_min': None,
                'app_uncertainty': None,
                'counterfactual_recipe': None,
                'counterfactual_expected_pgel': None,

                # Citation integration fields
                'first_author': first_author or None,
                'publication_year': int(publication_year) if publication_year else None,
                'paper_title': paper_title or None,
                'source_label': source_label or None,
                'doi': doi or None,
                'citation': citation or None,

                'split': split or None
            }

                data, reagents_data = sanitize_and_enrich_well_payload(data, reagents_data)
                
                # Check for likely duplicates (soft warning)
                if likely_duplicate_exists(plate_id, well_row, well_col):
                    st.warning(f"⚠️ Another well with the same plate/row/col ({plate_id}/{well_row}{well_col}) was created recently. Continuing anyway.")
                
                try:
                    rid = create_well(data, reagents_list=reagents_data if reagents_data else None)
                    created_records.append(rid)
                except sqlite3.IntegrityError:
                    st.error(f"❌ Record ID '{final_record_id}' already exists (should not happen with auto-versioning).")
                    return
                except Exception as e:
                    st.error(f"❌ Error saving well {well_id}: {e}")
                    return
            
            # Success message for all wells
            if created_records:
                st.success(f"✅ Created {len(created_records)} wells!")
                with st.expander("View created record IDs"):
                    st.code("\n".join(created_records))
                st.balloons()
                
                # Clear selected wells and all protocol steps after successful creation
                st.session_state.selected_wells = []
                st.session_state.proc_steps = []
                st.session_state.gel_steps = []

def show_literature_database_viewer():
    """Show literature database entries in a user-friendly interface."""
    from datetime import datetime
    
    st.header("📚 Literature Database Viewer")
    st.caption("Browse and manage literature ECM entries from published papers")
    
    # Import literature functions
    try:
        from literature_gui import get_ref_conn, read_lit_wells
    except ImportError:
        st.error("❌ Literature GUI module not available")
        st.info("This feature requires the literature GUI module.")
        return
    
    # Get literature data
    try:
        df = read_lit_wells()
        if df.empty:
            st.info("📚 No literature entries found. Go to **Literature Hydrogels** to add entries from published papers.")
            return
        
        st.success(f"📊 Found **{len(df)}** literature entries")
        
        # Filters
        with st.expander("🔍 Filter Literature Entries", expanded=False):
            col1, col2, col3 = st.columns(3)
            
            with col1:
                filter_author = st.text_input("First Author contains")
                filter_family = st.selectbox("ECM Family", ["All"] + sorted(df['material_family'].dropna().unique().tolist()))
            
            with col2:
                filter_year = st.selectbox("Publication Year", ["All"] + sorted(df['publication_year'].dropna().unique().tolist(), reverse=True))
                filter_species = st.selectbox("Species", ["All"] + sorted(df['ecm_origin_species'].dropna().unique().tolist()))
            
            with col3:
                filter_tissue = st.selectbox("Tissue", ["All"] + sorted(df['ecm_source_tissue'].dropna().unique().tolist()))
                filter_commercial = st.selectbox("Product Type", ["All", "Lab-made", "Commercial"])
        
        # Apply filters
        filtered_df = df.copy()
        
        if filter_author:
            filtered_df = filtered_df[filtered_df['first_author'].str.contains(filter_author, case=False, na=False)]
        
        if filter_family != "All":
            filtered_df = filtered_df[filtered_df['material_family'] == filter_family]
        
        if filter_year != "All":
            filtered_df = filtered_df[filtered_df['publication_year'] == filter_year]
        
        if filter_species != "All":
            filtered_df = filtered_df[filtered_df['ecm_origin_species'] == filter_species]
        
        if filter_tissue != "All":
            filtered_df = filtered_df[filtered_df['ecm_source_tissue'] == filter_tissue]
        
        if filter_commercial == "Lab-made":
            filtered_df = filtered_df[filtered_df['is_commercial_product'] == 0]
        elif filter_commercial == "Commercial":
            filtered_df = filtered_df[filtered_df['is_commercial_product'] == 1]
        
        st.write(f"**Showing {len(filtered_df)} of {len(df)} entries**")
        
        # Display key columns - separate batch data from gelation data
        batch_cols = [
            "batch_id", "first_author", "publication_year", "paper_title", 
            "material_family", "ecm_origin_species", "ecm_source_tissue",
            "is_commercial_product", "commercial_product_name",
            "ecm_total_protein_mgml", "protein_assay_method",
            "pre_pH", "pre_conductivity_mS", "uv_A220", "uv_A280", "uv_ratio_A220_A280",
            "created_at"
        ]
        
        gelation_cols = [
            "gelation_id", "gel_binary", "gel_strength_score_0to3", 
            "time_to_gel_min", "time_to_halfmax_min", "gelation_protocol"
        ]
        
        # Only show columns that exist and have data
        available_batch_cols = [c for c in batch_cols if c in filtered_df.columns]
        available_gelation_cols = [c for c in gelation_cols if c in filtered_df.columns]
        
        # Create separate dataframes for batch and gelation data
        batch_df = filtered_df[available_batch_cols].copy()
        gelation_df = filtered_df[available_gelation_cols].copy()
        
        # Format batch data
        if 'is_commercial_product' in batch_df.columns:
            batch_df['is_commercial_product'] = batch_df['is_commercial_product'].map({0: 'Lab-made', 1: 'Commercial'})
        
        # Format gelation data
        if 'gel_binary' in gelation_df.columns:
            gelation_df['gel_binary'] = gelation_df['gel_binary'].map({0: 'No Gel', 1: 'Gel'})
        
        # Sort by publication year (newest first)
        if 'publication_year' in batch_df.columns:
            batch_df = batch_df.sort_values('publication_year', ascending=False)
        
        # Display batch data with individual duplicate buttons and detailed dropdowns
        st.subheader("📦 ECM Batch Information")
        st.caption("💡 Click '🔄 Duplicate' to copy a batch, or expand '📋 Details' for more information")
        
        for idx, row in batch_df.iterrows():
            with st.container():
                col1, col2, col3, col4, col5, col6 = st.columns([2.5, 1, 1, 1, 1, 1])
                
                with col1:
                    st.write(f"**{row['batch_id']}** - {row['first_author']} ({row['publication_year']})")
                    st.caption(f"{row['material_family']} • {row['ecm_origin_species']} {row['ecm_source_tissue']}")
                    if row.get('paper_title'):
                        st.write(f"📄 {row['paper_title'][:80]}{'...' if len(str(row['paper_title'])) > 80 else ''}")
                
                with col2:
                    if row.get('ecm_total_protein_mgml'):
                        st.metric("Protein", f"{row['ecm_total_protein_mgml']:.1f} mg/mL")
                
                with col3:
                    if row.get('pre_pH'):
                        st.metric("Pre-pH", f"{row['pre_pH']:.1f}")
                
                with col4:
                    if row.get('uv_A220'):
                        st.metric("UV A220", f"{row['uv_A220']:.2f}")
                
                with col5:
                    # Details dropdown
                    with st.expander("📋 Details", expanded=False):
                        st.write("**📚 Publication Information**")
                        st.write(f"• **Author:** {row.get('first_author', 'N/A')}")
                        st.write(f"• **Year:** {row.get('publication_year', 'N/A')}")
                        st.write(f"• **DOI:** {row.get('doi', 'N/A')}")
                        if row.get('paper_title'):
                            st.write(f"• **Title:** {row['paper_title']}")
                        
                        st.write("**🧬 ECM Details**")
                        st.write(f"• **Family:** {row.get('material_family', 'N/A')}")
                        st.write(f"• **Species:** {row.get('ecm_origin_species', 'N/A')}")
                        st.write(f"• **Tissue:** {row.get('ecm_source_tissue', 'N/A')}")
                        st.write(f"• **Collagen Type:** {row.get('collagen_type', 'N/A')}")
                        
                        if row.get('is_commercial_product') == 'Commercial':
                            st.write("**🏪 Commercial Product**")
                            st.write(f"• **Vendor:** {row.get('commercial_vendor', 'N/A')}")
                            st.write(f"• **Product:** {row.get('commercial_product_name', 'N/A')}")
                            st.write(f"• **Catalog #:** {row.get('commercial_catalog_number', 'N/A')}")
                            st.write(f"• **Lot #:** {row.get('commercial_lot_number', 'N/A')}")
                        
                        st.write("**🔬 Characterization**")
                        st.write(f"• **Protein:** {row.get('ecm_total_protein_mgml', 'N/A')} mg/mL ({row.get('protein_assay_method', 'N/A')})")
                        st.write(f"• **Pre-pH:** {row.get('pre_pH', 'N/A')}")
                        st.write(f"• **Conductivity:** {row.get('pre_conductivity_mS', 'N/A')} mS")
                        st.write(f"• **UV A220:** {row.get('uv_A220', 'N/A')}")
                        st.write(f"• **UV A280:** {row.get('uv_A280', 'N/A')}")
                        st.write(f"• **UV Ratio:** {row.get('uv_ratio_A220_A280', 'N/A')}")
                        
                        if row.get('processing_protocol'):
                            st.write("**⚙️ Processing Protocol**")
                            try:
                                import json
                                protocol = json.loads(row['processing_protocol'])
                                for i, step in enumerate(protocol, 1):
                                    st.write(f"• **Step {i}:** {step.get('step_name', 'N/A')} - {step.get('description', 'N/A')}")
                            except:
                                st.write(f"• **Protocol:** {row['processing_protocol']}")
                        
                        if row.get('notes'):
                            st.write("**📝 Notes**")
                            st.write(f"• {row['notes']}")
                        
                        st.write(f"**📅 Created:** {row.get('created_at', 'N/A')}")
                
                with col6:
                    # Duplicate button for this specific batch
                    if st.button("🔄 Duplicate", key=f"dup_btn_{row['batch_id']}", help="Duplicate this batch for different species/tissue"):
                        st.session_state[f"duplicate_batch_{row['batch_id']}"] = True
                        st.rerun()
                
                # Show duplication form if this batch was selected
                if st.session_state.get(f"duplicate_batch_{row['batch_id']}", False):
                    with st.expander(f"🔄 Duplicating {row['batch_id']}", expanded=True):
                        st.write(f"**Original:** {row['batch_id']} - {row['ecm_origin_species']} {row['ecm_source_tissue']}")
                        
                        col_a, col_b = st.columns(2)
                        
                        with col_a:
                            new_species = st.selectbox(
                                "New Species:",
                                ["human", "porcine", "bovine", "rat", "mouse", "avian", "other"],
                                index=["human", "porcine", "bovine", "rat", "mouse", "avian", "other"].index(row.get('ecm_origin_species', 'human')) if row.get('ecm_origin_species') in ["human", "porcine", "bovine", "rat", "mouse", "avian", "other"] else 0,
                                key=f"dup_species_{row['batch_id']}"
                            )
                        
                        with col_b:
                            new_tissue = st.selectbox(
                                "New Tissue:",
                                ["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium",
                                 "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus",
                                 "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"],
                                index=["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium",
                                       "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus",
                                       "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"].index(row.get('ecm_source_tissue', 'mammary')) if row.get('ecm_source_tissue') in ["mammary", "dermis", "small_intestine_submucosa", "myocardium", "pericardium", "liver", "lung", "kidney", "bladder", "tendon", "cartilage", "meniscus", "adipose", "placenta", "amniotic_membrane", "esophagus", "cornea", "other"] else 0,
                                key=f"dup_tissue_{row['batch_id']}"
                            )
                        
                        # Generate new batch ID
                        from batch_creation_lit import generate_batch_id
                        new_batch_id = generate_batch_id(
                            row['material_family'], 
                            new_species, 
                            new_tissue, 
                            None, 
                            row.get('is_commercial_product', 0) == 'Commercial'
                        )
                        
                        st.write(f"**New Batch ID:** {new_batch_id}")
                        
                        col_c, col_d = st.columns([1, 1])
                        with col_c:
                            if st.button("✅ Confirm Duplicate", type="primary", key=f"confirm_dup_{row['batch_id']}"):
                                try:
                                    # Import literature functions
                                    from literature_gui import get_ref_conn
                                    
                                    # Get the original batch data
                                    conn = get_ref_conn()
                                    original_data = conn.execute(
                                        "SELECT * FROM literature_wells WHERE batch_id = ?", 
                                        (row['batch_id'],)
                                    ).fetchone()
                                    
                                    if original_data:
                                        # Create new batch data
                                        new_data = dict(original_data)
                                        new_data['batch_id'] = new_batch_id
                                        new_data['ecm_origin_species'] = new_species
                                        new_data['ecm_source_tissue'] = new_tissue
                                        new_data['created_at'] = datetime.now().isoformat()
                                        
                                        # Remove the original record_id to create a new one
                                        if 'record_id' in new_data:
                                            del new_data['record_id']
                                        
                                        # Insert new batch
                                        cols = list(new_data.keys())
                                        vals = list(new_data.values())
                                        
                                        conn.execute(
                                            f"INSERT INTO literature_wells ({','.join(cols)}) VALUES ({','.join(['?']*len(vals))})",
                                            vals
                                        )
                                        conn.commit()
                                        conn.close()
                                        
                                        st.success(f"✅ **Batch duplicated successfully!**")
                                        st.success(f"📦 New Batch ID: **{new_batch_id}**")
                                        st.info("🔄 The page will refresh to show the new batch")
                                        
                                        # Clear the duplicate state
                                        st.session_state[f"duplicate_batch_{row['batch_id']}"] = False
                                        st.rerun()
                                    else:
                                        st.error("❌ Original batch data not found")
                                        
                                except Exception as e:
                                    st.error(f"❌ Error duplicating batch: {e}")
                        
                        with col_d:
                            if st.button("❌ Cancel", key=f"cancel_dup_{row['batch_id']}"):
                                st.session_state[f"duplicate_batch_{row['batch_id']}"] = False
                                st.rerun()
                
                st.divider()
        
        # Display gelation data if it exists
        if not gelation_df.empty and any(gelation_df.notna().any()):
            st.subheader("🧬 Gelation Results")
            st.caption("Gelation conditions and outcomes from literature")
            
            # Filter out rows where gelation data is all null
            gelation_with_data = gelation_df.dropna(how='all')
            
            if not gelation_with_data.empty:
                st.dataframe(
                    gelation_with_data,
                    use_container_width=True,
                    height=200,
                    column_config={
                        "gelation_id": st.column_config.TextColumn("Gelation ID", width="medium"),
                        "gel_binary": st.column_config.TextColumn("Gel Formation", width="small"),
                        "gel_strength_score_0to3": st.column_config.NumberColumn("Strength (0-3)", width="small"),
                        "time_to_gel_min": st.column_config.NumberColumn("Time to Gel (min)", width="small"),
                        "time_to_halfmax_min": st.column_config.NumberColumn("Time to Half-max (min)", width="small"),
                        "gelation_protocol": st.column_config.TextColumn("Protocol", width="large"),
                    }
                )
            else:
                st.info("No gelation data available. Use **Literature Gelation** form to add gelation conditions and results.")
        else:
            st.subheader("🧬 Gelation Results")
            st.info("No gelation data available. Use **Literature Gelation** form to add gelation conditions and results.")
        
        # Summary statistics
        with st.expander("📊 Summary Statistics", expanded=False):
            col1, col2, col3 = st.columns(3)
            
            with col1:
                st.metric("Total Entries", len(filtered_df))
                if 'material_family' in filtered_df.columns:
                    family_counts = filtered_df['material_family'].value_counts()
                    st.write("**By Family:**")
                    for family, count in family_counts.head(5).items():
                        st.write(f"• {family}: {count}")
            
            with col2:
                if 'publication_year' in filtered_df.columns:
                    recent_years = filtered_df['publication_year'].value_counts().head(5)
                    st.write("**Recent Years:**")
                    for year, count in recent_years.items():
                        st.write(f"• {year}: {count}")
            
            with col3:
                if 'ecm_origin_species' in filtered_df.columns:
                    species_counts = filtered_df['ecm_origin_species'].value_counts()
                    st.write("**By Species:**")
                    for species, count in species_counts.head(5).items():
                        st.write(f"• {species}: {count}")
        
        # Quick actions
        st.markdown("---")
        st.subheader("🚀 Quick Actions")
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            if st.button("➕ Add Literature Batch", use_container_width=True):
                st.info("Go to **Literature Hydrogels** → **➕ Add Entry** to add ECM batch data from papers")
        
        with col2:
            if st.button("🧬 Add Gelation Data", use_container_width=True):
                st.info("Go to **Literature Hydrogels** → **🧬 Gelation** to add gelation conditions and results")
        
        with col3:
            if st.button("📂 Import Literature CSV", use_container_width=True):
                st.info("Go to **Literature Hydrogels** → **📂 Import CSV** to bulk import literature data")
        
    except Exception as e:
        st.error(f"❌ Error loading literature data: {e}")
        st.info("Make sure the literature database is properly initialized.")

def show_view_edit_page(codebook):
    st.header("📊 Raw Wells Data Viewer")
    st.caption("Legacy data viewer for all historical well data from wells_master_v4 table")

    with st.expander("🔍 Filters"):
        c1,c2,c3 = st.columns(3)
        with c1:
            f_batch = st.text_input("Batch ID")
            f_family = st.selectbox("ECM Family", ["All"] + codebook['family'])
        with c2:
            f_operator = st.text_input("Operator ID")
            f_gel = st.selectbox("Gel Outcome", ["All","Gel (1)","No Gel (0)"])
        with c3:
            f_species = st.selectbox("Species (decECM)", ["All"] + codebook['species'])
            f_tissue = st.selectbox("Tissue (decECM)", ["All"] + codebook['tissues'])
    
    # Plate heatmap for visual QC
    with st.expander("🗺️ Plate Heatmap (Visual QC)", expanded=False):
        col_h1, col_h2 = st.columns(2)
        with col_h1:
            pid_for_heatmap = st.text_input("Plate ID", placeholder="PLT-001-96", key="heatmap_plate")
        with col_h2:
            date_for_heatmap = st.text_input("Date (optional)", placeholder="YYYY-MM-DD", key="heatmap_date")
        
        if pid_for_heatmap:
            render_plate_heatmap(pid_for_heatmap, date_for_heatmap or None)

    filters = {}
    if f_batch: filters['batch_id'] = f_batch
    if f_family != "All": filters['family'] = f_family
    if f_operator: filters['operator_id'] = f_operator
    if f_species != "All": filters['ecm_origin_species'] = f_species
    if f_tissue != "All": filters['ecm_source_tissue'] = f_tissue
    if f_gel == "Gel (1)": filters['gel_binary'] = 1
    elif f_gel == "No Gel (0)": filters['gel_binary'] = 0

    df = read_wells(filters if filters else None, use_effective_view=True)
    if df.empty:
        st.info("No wells found.")
        return

    st.write(f"**Total records:** {len(df)}")
    
    # Show plate bounds as hint (cached per unique plate_id)
    if 'plate_id' in df.columns:
        unique_pids = [p for p in df['plate_id'].dropna().unique().tolist()]
        geom_map = {}
        for pid in unique_pids:
            g = get_plate_geometry(pid)
            geom_map[pid] = (f"{g[0]} × {g[1]}" if g else "")
        df['_plate_geom'] = df['plate_id'].map(geom_map).fillna("")
    
    show_cols = [c for c in ['record_id','date','operator_id','family','ecm_origin_species','ecm_source_tissue','batch_id','plate_id','_plate_geom','gel_binary','gel_strength_score_0to3','target_pH','temp_incubation_C','eff_NaCl_mM','eff_CaCl2_mM','updated_at'] if c in df.columns]
    st.dataframe(df[show_cols], use_container_width=True)

    # Friendly selection but storing the full record_id
    options = [(f"{row['record_id'][:8]}… — {row.get('batch_id','N/A')}", row['record_id']) for _,row in df.iterrows()]
    labels = [o[0] for o in options]
    label = st.selectbox("Select well to edit:", options=[""]+labels)
    if not label: return
    record_id = dict(options)[label]

    well = df[df['record_id']==record_id].iloc[0].to_dict()
    with st.form(f"edit_form_{record_id[:8]}"):
        st.write(f"**Editing:** `{record_id}`")
        expected_updated_at = well.get('updated_at')

        c1,c2 = st.columns(2)
        with c1:
            edit_gel_binary = st.selectbox("Gel formed?", [0,1], index=int(well.get('gel_binary',0)))
            edit_strength = st.number_input("Gel strength (0-3)", 0, 3, int(0 if pd.isna(well.get('gel_strength_score_0to3')) else well['gel_strength_score_0to3']))
        with c2:
            edit_failure = st.selectbox("Failure mode", [""]+codebook['failure_mode'], index=0 if pd.isna(well.get('failure_mode')) or well.get('failure_mode') not in codebook['failure_mode'] else codebook['failure_mode'].index(well['failure_mode'])+1)
            edit_cause = st.selectbox("Suspected cause", [""]+codebook['suspected_cause'], index=0 if pd.isna(well.get('suspected_cause')) or well.get('suspected_cause') not in codebook['suspected_cause'] else codebook['suspected_cause'].index(well['suspected_cause'])+1)

        notes_post = st.text_area("Notes (post-experiment)", value=("" if pd.isna(well.get('notes_post')) else str(well.get('notes_post'))))

        c1,c2 = st.columns(2)
        with c1: update_btn = st.form_submit_button("💾 Update Well")
        with c2: delete_btn = st.form_submit_button("🗑️ Delete Well", type="secondary")

        if update_btn:
            upd = {
                'gel_binary': int(edit_gel_binary),
                'gel_strength_score_0to3': int(edit_strength),
                'failure_mode': None if edit_failure=="" else edit_failure,
                'suspected_cause': None if edit_cause=="" else edit_cause,
                'notes_post': None if notes_post.strip()=="" else notes_post
            }
            try:
                update_well(record_id, upd, expected_updated_at=expected_updated_at)
                st.success("✅ Updated.")
                st.rerun()
            except RuntimeError as e:
                st.error(f"❌ {e}")
            except Exception as e:
                st.error(f"❌ Error: {e}")

        if delete_btn:
            try:
                delete_well(record_id)
                st.success("✅ Deleted.")
                st.rerun()
            except Exception as e:
                st.error(f"❌ Error deleting: {e}")
    
    # Clone functionality
    st.markdown("---")
    st.subheader("🔁 Clone this well")
    st.caption("Create copies of this well with the same metadata and optionally reagents. Great for replicates!")

    with st.form(f"clone_form_{record_id[:8]}"):
        cc1, cc2, cc3, cc4 = st.columns(4)
        with cc1:
            clone_count = st.number_input("How many clones?", 1, 96, 1)
            clone_reagents = st.checkbox("Clone reagents", value=True)
        with cc2:
            clone_operator = st.text_input("Operator override", value=str(well.get("operator_id") or ""))
            clone_batch = st.text_input("Batch override", value=str(well.get("batch_id") or ""))
        with cc3:
            clone_plate = st.text_input("Plate ID", value=str(well.get("plate_id") or ""))
            # Derive geometry live from the current text field
            if clone_plate:
                ensure_default_plate_if_unset(clone_plate)
            _geom = get_plate_geometry(clone_plate) if clone_plate else None
            row_labels_clone, max_cols_clone = (_geom if _geom else ("ABCDEFGH", 12))
            start_col = st.number_input("Start column", 1, int(max_cols_clone), int(well.get("col") or 1))
        with cc4:
            current_row = str(well.get("row") or (row_labels_clone[0] if row_labels_clone else "A"))
            row_options = list(row_labels_clone)
            # Choose index safely
            idx = row_options.index(current_row) if current_row in row_options else 0
            row_letter = st.selectbox("Row", row_options, index=idx)
            rep_start = st.number_input("Replicate start", 1, 999, int(well.get("replicate_id") or 1))

        do_clone = st.form_submit_button("✨ Create clones")
        if do_clone:
            # Validate column range
            end_col = start_col + int(clone_count) - 1
            if end_col > int(max_cols_clone):
                st.error(f"❌ Requested range {start_col}-{end_col} exceeds plate columns (max {max_cols_clone}). Reduce clone count or start column.")
            else:
                tmpl = get_well(record_id)
                if not tmpl:
                    st.error("Template well not found.")
                else:
                    reag_tmpl = get_reagents_template(record_id) if clone_reagents else None
                    positions = [(row_letter, start_col + i, rep_start + i) for i in range(int(clone_count))]
                    try:
                        new_ids = []
                        for (r, c, rep) in positions:
                            rid = new_record_id()
                            payload = copy_well_payload(
                                tmpl, new_record_id=rid,
                                date_override=datetime.now().date().isoformat(),
                                operator_override=(clone_operator or None),
                                plate_id=(clone_plate or tmpl.get("plate_id")),
                                row_letter=r, col_num=c, replicate_id=rep,
                                batch_id=(clone_batch or None)
                            )
                            create_well(payload, reagents_list=reag_tmpl)
                            new_ids.append(rid)
                        
                        st.success(f"✅ Created {len(new_ids)} clone(s).")
                        with st.expander("View created record IDs"):
                            st.code("\n".join(new_ids[:min(10, len(new_ids))]))
                        st.balloons()
                    except Exception as e:
                        st.error(f"❌ Error creating clones: {e}")

def show_reagents_manager(codebook):
    st.header("Reagents Manager")
    df_wells = read_wells()
    if df_wells.empty:
        st.info("No wells found.")
        return

    options = [(f"{row['record_id'][:16]}… — {row.get('batch_id','N/A')}", row['record_id']) for _,row in df_wells.iterrows()]
    labels = [o[0] for o in options]
    label = st.selectbox("Select a well:", options=labels)
    record_id = dict(options)[label]

    reagents_df = get_reagents(record_id)
    st.subheader(f"Reagents for `{record_id}`")
    if not reagents_df.empty:
        keep = [c for c in ['reagent_id','reagent_name','reagent_class','purpose','stock_conc_value','stock_conc_units','volume_uL_per_mL','effective_conc_mM','lot_number','added_order'] if c in reagents_df.columns]
        st.dataframe(reagents_df[keep], use_container_width=True)

        del_sel = st.selectbox("Delete reagent:", options=[""]+[f"{r['reagent_id']} — {r['reagent_name']}" for _,r in reagents_df.iterrows()])
        if del_sel and st.button("🗑️ Delete Selected Reagent"):
            reagent_id = int(del_sel.split(" — ")[0])
            delete_reagent(reagent_id)
            st.success("Deleted.")
            st.rerun()
    else:
        st.info("No reagents yet.")

    st.subheader("Add New Reagent")
    with st.form(f"add_reagent_{record_id[:8]}"):
        c1,c2,c3 = st.columns(3)
        with c1:
            name = st.text_input("Reagent Name*")
            rclass = st.selectbox("Class", ["","buffer","base","acid","salt","media","additive","enzyme","crosslinker","other"])
            purpose = st.text_input("Purpose")
        with c2:
            stock = st.number_input("Stock value", 0.0, 1e9, 1.0, 0.1)
            units = st.selectbox("Units", ["M","mM","µM","%","x","mg/mL","U/mL"])
            vol = st.number_input("µL per mL", 0.0, 1000.0, 0.0, 0.5)
        with c3:
            lot = st.text_input("Lot #")
            order = st.number_input("Added order", 1, 99, (1 if reagents_df.empty else int(reagents_df['added_order'].max())+1))
            
            # Calculate effective concentrations with PBS/DMEM hints
            eff = effective_mM(stock, units, vol)
            if eff is not None:
                st.caption(f"→ effective ~ **{eff:.2f} mM**")
            else:
                st.caption(f"→ effective: n/a for {units}")
            
            # Extra hints for PBS and DMEM
            name_lower = (name or "").strip().lower()
            if units == "x" and "pbs" in name_lower:
                final_x = pbs_final_x(stock, vol)
                if final_x is not None:
                    st.caption(f"PBS final ≈ **{final_x:.2f}×**")
            if "dmem" in name_lower or ("media" in (rclass or "").lower()):
                media_pct = dmem_final_percent(vol)
                if media_pct is not None and media_pct > 0:
                    st.caption(f"Media final ≈ **{media_pct:.2f}% v/v**")

        submit = st.form_submit_button("➕ Add Reagent")
        if submit:
            if not name:
                st.error("Name required.")
            else:
                add_reagent(dict(
                    record_id=record_id, reagent_name=name, reagent_class=(rclass or None), purpose=(purpose or None),
                    stock_conc_value=stock, stock_conc_units=units, volume_uL_per_mL=vol, effective_conc_mM=eff,
                    lot_number=(lot or None), added_order=int(order)
                ))
                st.success("Added.")
                st.rerun()

def show_events_logger(codebook):
    st.header("Events Logger")
    df_wells = read_wells()
    if df_wells.empty:
        st.info("No wells found.")
        return

    options = [(f"{row['record_id'][:16]}… — {row.get('batch_id','N/A')}", row['record_id']) for _,row in df_wells.iterrows()]
    labels = [o[0] for o in options]
    label = st.selectbox("Select a well:", options=labels)
    record_id = dict(options)[label]

    st.subheader(f"Events for `{record_id}`")
    ev = get_events(record_id)
    if not ev.empty:
        keep = [c for c in ['event_type','time_point_min','measurement_type','measurement_value','measurement_units','status_code','gel_strength_score_0to3','tilt_test_angle_deg','observation'] if c in ev.columns]
        st.dataframe(ev[keep], use_container_width=True)
        if 'measurement_value' in ev.columns and ev['measurement_value'].notna().any():
            st.line_chart(ev.set_index('time_point_min')['measurement_value'])
        del_sel = st.selectbox("Delete event:", options=[""]+[f"{r['event_id']} — {r['event_type']} @ {r['time_point_min']} min" for _,r in ev.iterrows()])
        if del_sel and st.button("🗑️ Delete Selected Event"):
            delete_event(int(del_sel.split(" — ")[0]))
            st.success("Deleted.")
            st.rerun()
    else:
        st.info("No events yet.")

    st.subheader("Log New Event")
    with st.form(f"add_event_{record_id[:8]}"):
        STATUS = codebook['status_code']
        c1,c2 = st.columns(2)
        with c1:
            event_type = st.selectbox("Event Type*", ["","status","soften","liquefy","syneresis_onset","tilt_score","strength_score","OD_Reading","Other"])
            tmin = st.number_input("Time Point (min)*", 0.0, 1e7, 0.0, 1.0)
            thours = st.number_input("Time from mix (hours)", 0.0, 1e6, 0.0, 0.1)
        with c2:
            day = st.number_input("Day from mix", 0, 10000, 0)
            gel_strength = st.selectbox("Gel Strength (0-3)", ["",0,1,2,3])
        
        # Quick status picker (radio for common codes)
        st.caption("Status Code:")
        col_status1, col_status2 = st.columns([3, 1])
        with col_status1:
            quick_status = st.radio(
                "Quick pick", 
                ["(none)","liquid","weak_gel","soft_gel","stiff_gel","softened","liquidated"],
                index=0, 
                horizontal=True,
                label_visibility="collapsed"
            )
        with col_status2:
            custom_status = st.selectbox("Or select custom", [""] + STATUS, label_visibility="collapsed")
        
        # Use quick pick if selected, otherwise use dropdown
        if quick_status != "(none)":
            status_code = quick_status
        else:
            status_code = custom_status if custom_status else None

        c3,c4 = st.columns(2)
        with c3:
            mtype = st.text_input("Measurement Type (e.g., OD405, pH)")
            mval = st.number_input("Measurement Value", value=0.0, step=0.01)
        with c4:
            munits = st.text_input("Measurement Units")
            tilt = st.number_input("Tilt Angle (deg)", 0.0, 90.0, 0.0, 1.0)

        obs = st.text_area("Observation / Notes")
        operator = st.text_input("Observer ID")

        sub = st.form_submit_button("➕ Log Event")
        if sub:
            if not event_type:
                st.error("Event type required.")
            else:
                payload = dict(
                    record_id=record_id,
                    event_type=event_type,
                    time_point_min=tmin,
                    time_from_mix_hours=(None if thours==0 else thours),
                    day_from_mix=(None if day==0 else day),
                    status_code=(None if status_code=="" else status_code),
                    gel_strength_score_0to3=(None if gel_strength=="" else int(gel_strength)),
                    tilt_test_angle_deg=(None if tilt==0 else tilt),
                    measurement_type=(None if mtype.strip()=="" else mtype),
                    measurement_value=(None if mval==0 else mval),
                    measurement_units=(None if munits.strip()=="" else munits),
                    observation=(None if obs.strip()=="" else obs),
                    operator_id=(None if operator.strip()=="" else operator)
                )
                try:
                    add_event(payload)
                    st.success("✅ Event logged.")
                    st.rerun()
                except Exception as e:
                    st.error(f"❌ Error: {e}")

def show_plate_map_wizard(codebook):
    st.header("🧩 Plate Map Wizard — bulk create wells")
    st.caption("Tip: choose a template well to copy base metadata and (optionally) reagents.")

    df_wells = read_wells()

    # Pick a template well
    tmpl_options = [(f"{row['record_id'][:8]}… — {row.get('family','?')} / {row.get('batch_id','N/A')}", row['record_id']) 
                    for _,row in df_wells.iterrows()] if not df_wells.empty else []
    label = st.selectbox("Template well (optional)", options=["(none)"] + ([o[0] for o in tmpl_options] if tmpl_options else []))
    tmpl_id = None if label == "(none)" or not tmpl_options else dict(tmpl_options)[label]

    st.subheader("🧫 Choose Plate")
    st.caption("Reuse an existing physical plate or create a new one")
    
    # Load recent plates
    recent_plates = get_recent_plates(limit=50)
    
    wizard_plate_mode = st.radio(
        "Plate Option",
        ["Reuse Existing", "Create New"],
        horizontal=True,
        key="wizard_plate_mode"
    )
    
    if wizard_plate_mode == "Reuse Existing" and recent_plates:
        plate_options_wiz = [""] + [f"{p['plate_id']} ({p['n_wells']} wells, {p['n_batches']} batches, last: {p['last_use']})" for p in recent_plates]
        plate_ids_wiz = [""] + [p['plate_id'] for p in recent_plates]
        
        sel_idx = st.selectbox("Select Plate*", range(len(plate_options_wiz)), format_func=lambda i: plate_options_wiz[i], key="wiz_plate_sel")
        plate_id = plate_ids_wiz[sel_idx] if sel_idx > 0 else ""
        
        if plate_id:
            st.success(f"✅ Reusing: {plate_id}")
    else:
        # Create new
        wiz_p_col1, wiz_p_col2 = st.columns([2, 1])
        with wiz_p_col1:
            plate_type_wiz = st.selectbox("Plate Type", ["6","12","24","48","96","384"], index=4, key="wiz_ptype")
            suggested_plate_wiz = generate_plate_id(plate_type_wiz)
            plate_id = st.text_input("Plate ID*", value=suggested_plate_wiz, key="wiz_plate_id")
        with wiz_p_col2:
            if st.button("🔄 Next Plate", key="wiz_next_plate"):
                parts = plate_id.split("-")
                if len(parts) == 3 and parts[-1].isdigit():
                    new_seq = int(parts[-1]) + 1
                    plate_id = f"{parts[0]}-{parts[1]}-{new_seq:03d}"
                    st.rerun()
        st.info(f"Creating new plate: {plate_id}")

    # Ensure default if it looks like '...-96' etc.
    if plate_id:
        ensure_default_plate_if_unset(plate_id)
    geom = get_plate_geometry(plate_id) if plate_id else None
    if geom:
        row_labels, max_cols = geom
    else:
        row_labels, max_cols = "ABCDEFGH", 12  # fallback

    with st.expander("⚙️ Plate geometry (register / edit)", expanded=False):
        pg1, pg2 = st.columns([2,1])
        with pg1:
            new_rows = st.text_input("Row labels", value=row_labels)
        with pg2:
            new_cols = st.number_input("Max columns", min_value=1, max_value=48, value=int(max_cols))
        desc = st.text_input("Description (optional)", value="")
        if st.button("💾 Save plate geometry", key="save_plate_geom_wizard"):
            try:
                upsert_plate_geometry(plate_id, new_rows.strip(), int(new_cols), description=(desc or None))
                st.success("✅ Plate geometry saved.")
                row_labels, max_cols = new_rows.strip(), int(new_cols)
            except Exception as e:
                st.error(f"❌ Failed to save geometry: {e}")

    # Base fields if no template chosen (or overrides)
    st.subheader("Base metadata / overrides")
    c1,c2,c3 = st.columns(3)
    with c1:
        family = st.selectbox(
            "ECM Family", 
            options=[""] + codebook['family'],
            index=2 if "decECM" in codebook['family'] else 0  # Default to "decECM"
        )
        batch_id = st.text_input("Batch ID")
        operator_id = st.text_input("Operator ID", value="")
    with c2:
        target_pH = st.number_input("Target pH", 0.0, 14.0, 7.2, 0.05)
        tempC = st.number_input("Incubation temp (°C)", 0.0, 60.0, 37.0, 0.5)
    with c3:
        pre_pH = st.number_input("Pre pH", 0.0, 14.0, 4.0, 0.1)
        protein = st.number_input("Total protein (mg/mL)", 0.0, 100.0, 7.0, 0.1)
        cond_mS = st.number_input("Pre-conductivity (mS/cm)", 0.0, 100.0, 3.0, 0.1)

    # ECM Provenance (species and tissue origin)
    st.subheader("🧬 ECM Provenance")
    prov_wiz1, prov_wiz2 = st.columns(2)
    with prov_wiz1:
        dec_species_w = st.selectbox(
            "Origin species*" if family == "decECM" else "Origin species", 
            [""] + codebook['species'],
            index=1 if "human" in codebook['species'] else 0,  # Default to "human"
            help="Required for decECM, optional for other ECM types"
        )
    with prov_wiz2:
        dec_tissue_w = st.selectbox(
            "Source tissue/organ*" if family == "decECM" else "Source tissue/organ", 
            [""] + codebook['tissues'],
            index=1 if "mammary" in codebook['tissues'] else 0,  # Default to "mammary"
            help="Required for decECM, optional for other ECM types"
        )

    st.subheader("Select well positions")

    mode = st.radio(
        "Selection mode",
        ["Manual picks (A2, B6, ...)", "Row/Column range"],
        index=0,
        horizontal=True
    )

    rep_start = st.number_input("Replicate start", 1, 999, 1)

    positions = []  # will be [(row, col)]

    if mode == "Manual picks (A2, B6, ...)":
        manual_text = st.text_area(
            "Enter wells (comma/space/newline separated):",
            placeholder="e.g., A2, B6, H12 or A1-A3, B4:B6",
            height=100,
            help="Supports single wells (A2), ranges (A1-A3, B4:B6), and mixed formats. Invalid entries are ignored."
        )
        raw_picks = _parse_manual_well_tokens(manual_text, row_labels, int(max_cols))
        if manual_text and not raw_picks:
            st.warning("⚠️ No valid wells found. Use patterns like A2, B6, A1-A3, B4:B6.")
        positions = raw_picks

    else:
        # Keep existing range UI for folks who like blocks
        sel_rows = st.multiselect("Rows", list(row_labels), default=list(row_labels)[:min(2, len(row_labels))])
        c_from, c_to = st.columns(2)
        with c_from: col_start = st.number_input("Column start", 1, int(max_cols), 1)
        with c_to:   col_end   = st.number_input("Column end", 1, int(max_cols), min(6, int(max_cols)))

        if col_start > col_end:
            st.warning(f"⚠️ Column start ({col_start}) > column end ({col_end}) — swapping.")
            col_start, col_end = col_end, col_start

        # Validate rows, but don't hard stop; just skip bad ones
        good_rows = [r for r in sel_rows if r in row_labels]
        bad_rows  = [r for r in sel_rows if r not in row_labels]
        if bad_rows:
            st.warning(f"Ignoring invalid rows for plate '{plate_id}': {', '.join(bad_rows)}")

        for r in good_rows:
            for c in range(int(col_start), int(col_end) + 1):
                positions.append((r, c))

    # Deduplicate positions just in case
    positions = list(dict.fromkeys(positions))

    st.write(f"Planned wells: **{len(positions)}**")
    if positions:
        prev = pd.DataFrame([{"row": r, "col": c, "replicate_id": rep_start + i} for i, (r, c) in enumerate(positions)])
        st.dataframe(prev, use_container_width=True, height=200)

    st.subheader("Reagents template")
    clone_reagents = st.checkbox("Copy reagents from template well", value=True if tmpl_id else False)

    # Submit
    if st.button("🚀 Create wells", type="primary"):
        if not positions:
            st.error("No valid well positions selected. Please choose wells using either manual picks or row/column range.")
            return

        # Validate decECM provenance requirements
        if family == "decECM":
            if not dec_species_w or dec_species_w == "":
                st.error("❌ Origin species is required for decECM")
                return
            if not dec_tissue_w or dec_tissue_w == "":
                st.error("❌ Source tissue/organ is required for decECM")
                return

        # Build a template well payload
        if tmpl_id:
            tmpl = get_well(tmpl_id)
            if tmpl is None:
                st.error("Template well not found.")
                return
            reag_tmpl = get_reagents_template(tmpl_id) if clone_reagents else None
        else:
            # synthesize a minimal template from overrides
            tmpl = dict(
                record_id=new_record_id(),  # temporary, will be replaced
                date=datetime.now().date().isoformat(),
                operator_id=(operator_id or None),
                family=(family or None),
                batch_id=(batch_id or None),
                donor_id=None,
                plate_id=(plate_id or None),  # ensure plate is set
                row=None, col=None, replicate_id=None,
                pre_storage_days_4C=0, pre_storage_freeze_cycles=0,
                ecm_total_protein_mgml=protein,
                pre_pH=pre_pH,
                pre_conductivity_mS=cond_mS,
                temp_incubation_C=tempC,
                uv_A220=None, uv_A230=None, uv_A260=None, uv_A280=None, uv_ratio_A220_A280=None,
                sds_smear_index=None, sds_alpha_ratio=None,
                hydroxyproline_mgml=None, dmmB_GAG_ugml=None, viscosity_proxy_sec=None,
                probe_type=None, target_pH=target_pH,
                od_wavelength_nm=None, od_sampling_interval_min=None, time_to_halfmax_min=None,
                slope_OD_per_min=None, final_OD=None, lag_time_min=None,
                gel_binary=None, gel_strength_score_0to3=None, tilt_test_angle_deg=None, time_to_handle_min=None,
                failure_mode=None, suspected_cause=None, confidence_0to1=None,
                syneresis_binary=None, syneresis_time_min=None, precipitate_binary=None, color_shift=None,
                notes_pre=None, notes_post=None, app_recipe_recommended=None, app_pgel_pred=None,
                app_thalf_pred_min=None, app_uncertainty=None, counterfactual_recipe=None, counterfactual_expected_pgel=None,
                ecm_origin_species=(dec_species_w or None),
                ecm_source_tissue=(dec_tissue_w or None),
                split=None
            )
            reag_tmpl = None

        # Build final positions with replicate increments
        pos_with_rep = [(r, c, rep_start + i) for i,(r,c) in enumerate(positions)]

        try:
            with st.spinner(f"Creating {len(pos_with_rep)} wells..."):
                new_ids = []
                for (r, c, rep) in pos_with_rep:
                    rid = new_record_id()
                    payload = copy_well_payload(
                        tmpl, new_record_id=rid,
                        date_override=datetime.now().date().isoformat(),
                        operator_override=(operator_id or tmpl.get("operator_id")),
                        plate_id=(plate_id or tmpl.get("plate_id")),  # ensure plate is set
                        row_letter=r, col_num=c, replicate_id=rep,
                        batch_id=(batch_id or tmpl.get("batch_id"))
                    )
                    create_well(payload, reagents_list=reag_tmpl)
                    new_ids.append(rid)
            st.success(f"✅ Created {len(new_ids)} wells!")
            with st.expander("View created record IDs"):
                st.code("\n".join(new_ids[:min(20, len(new_ids))]))
            st.balloons()
        except Exception as e:
            st.error(f"❌ Failed to create wells: {e}")
            import traceback
            with st.expander("Error details"):
                st.code(traceback.format_exc())

def show_plates_registry():
    st.header("🧱 Plates Registry & Usage Tracker")
    st.caption("Manage plate geometries and track physical plate reuse")
    
    # Tab view for registry vs usage
    tab1, tab2 = st.tabs(["📋 Plate Geometries", "📊 Plate Usage Analytics"])
    
    with tab1:
        conn = get_connection()
        df = pd.read_sql_query(
            "SELECT plate_id, row_labels, max_cols, description, updated_at FROM plates_registry ORDER BY updated_at DESC",
            conn
        )
        conn.close()

        st.subheader("Registered plates")
        if df.empty:
            st.info("No plates registered yet. Add one below to enforce geometry validation.")
        else:
            st.dataframe(df, use_container_width=True)
            st.caption(f"**Total registered plates:** {len(df)}")
    
    with tab2:
        st.subheader("Physical Plate Usage Analytics")
        st.caption("Track how physical plates are reused across experiments")
        
        # Get plate usage stats
        recent_plates = get_recent_plates(limit=100)
        
        if not recent_plates:
            st.info("No plates have been used yet.")
        else:
            # Convert to DataFrame for display
            df_usage = pd.DataFrame(recent_plates)
            
            # Summary metrics
            col1, col2, col3, col4 = st.columns(4)
            with col1:
                st.metric("Total Plates", len(df_usage))
            with col2:
                st.metric("Total Wells", df_usage['n_wells'].sum())
            with col3:
                avg_reuse = df_usage['n_batches'].mean()
                st.metric("Avg Batches/Plate", f"{avg_reuse:.1f}")
            with col4:
                max_reuse = df_usage['n_batches'].max()
                st.metric("Max Batches/Plate", int(max_reuse))
            
            st.markdown("---")
            
            # Show plates with high reuse (good lab practice)
            st.markdown("**🌟 Most Reused Plates:**")
            df_sorted = df_usage.sort_values('n_batches', ascending=False).head(10)
            st.dataframe(
                df_sorted[['plate_id', 'n_wells', 'n_batches', 'n_gelations', 'first_use', 'last_use']],
                use_container_width=True,
                hide_index=True
            )
            
            # Alert for plates that might need cleaning/replacement
            st.markdown("---")
            st.markdown("**⚠️ Plates with High Usage (Consider Physical Inspection):**")
            high_use = df_usage[df_usage['n_wells'] > 50]
            if not high_use.empty:
                st.dataframe(
                    high_use[['plate_id', 'n_wells', 'first_use', 'last_use']],
                    use_container_width=True,
                    hide_index=True
                )
                st.caption("Physical plates with 50+ wells may need cleaning or inspection for contamination")
            else:
                st.success("✅ No plates with excessive usage")
            
            # Search for specific plate
            st.markdown("---")
            st.subheader("🔍 Plate Details")
            search_plate = st.selectbox(
                "Select Plate to View Details",
                [""] + df_usage['plate_id'].tolist()
            )
            
            if search_plate:
                # Get all wells from this plate
                conn = get_connection()
                wells_on_plate = pd.read_sql_query("""
                    SELECT record_id, date, batch_id, gelation_id, row, col, family, gel_binary, gel_strength_score_0to3
                    FROM wells_master_v4
                    WHERE plate_id = ?
                    ORDER BY date DESC, row, col
                """, conn, params=(search_plate,))
                conn.close()
                
                if not wells_on_plate.empty:
                    st.markdown(f"**Plate: {search_plate}**")
                    
                    # Summary
                    col_det1, col_det2, col_det3 = st.columns(3)
                    with col_det1:
                        st.metric("Total Wells", len(wells_on_plate))
                        st.metric("Date Range", f"{wells_on_plate['date'].min()} to {wells_on_plate['date'].max()}")
                    with col_det2:
                        st.metric("Unique Batches", wells_on_plate['batch_id'].nunique())
                        st.metric("Unique Gelations", wells_on_plate['gelation_id'].nunique())
                    with col_det3:
                        gel_rate = wells_on_plate['gel_binary'].mean() if 'gel_binary' in wells_on_plate.columns else 0
                        st.metric("Overall Gel Rate", f"{gel_rate:.1%}")
                        avg_strength = wells_on_plate['gel_strength_score_0to3'].mean() if 'gel_strength_score_0to3' in wells_on_plate.columns else 0
                        st.metric("Avg Strength", f"{avg_strength:.2f}/3")
                    
                    # Full table
                    st.markdown("**All Wells on This Plate:**")
                    st.dataframe(wells_on_plate, use_container_width=True, height=400)
                    
                    # Export plate data
                    if st.button("📥 Export This Plate to CSV"):
                        csv = wells_on_plate.to_csv(index=False)
                        st.download_button(
                            "Download CSV",
                            csv,
                            file_name=f"{search_plate}_wells.csv",
                            mime="text/csv"
                        )

    st.markdown("---")
    st.subheader("Add / Update Plate")
    st.caption("Register a new plate or update an existing one. Auto-detects 96/48/24 if in plate_id.")
    
    c1, c2, c3 = st.columns([2,1,2])
    with c1:
        pid = st.text_input("Plate ID*", placeholder="PLT-001-96", help="Include 96/48/24 for auto-detection")
    with c2:
        rows = st.text_input("Row labels*", value="ABCDEFGH", help="E.g., ABCDEFGH or ABCDEF")
        cols = st.number_input("Max columns*", 1, 48, 12)
    with c3:
        desc = st.text_input("Description", value="", placeholder="96-well screening plate")

    if st.button("💾 Save Plate Geometry", type="primary"):
        if not pid:
            st.error("Plate ID is required!")
        else:
            try:
                upsert_plate_geometry(pid, rows, int(cols), description=(desc or None))
                st.success(f"✅ Saved geometry for '{pid}'.")
                st.balloons()
                st.rerun()
            except Exception as e:
                st.error(f"❌ Failed: {e}")

    st.markdown("---")
    st.subheader("⚠️ Delete Plate (Danger Zone)")
    st.caption("Deleting a plate geometry won't affect existing wells, but new wells won't enforce bounds.")
    
    del_pid = st.text_input("Plate ID to delete", placeholder="PLT-001-96")
    if st.button("🗑️ Delete Plate Geometry", type="secondary"):
        if not del_pid:
            st.error("Enter a plate ID to delete.")
        else:
            try:
                with tx() as con:
                    result = con.execute("DELETE FROM plates_registry WHERE plate_id=?", (del_pid,))
                    if result.rowcount == 0:
                        st.warning(f"Plate '{del_pid}' not found in registry.")
                    else:
                        # Clear cache
                        try:
                            _get_plate_geom_cached.cache_clear()
                        except Exception:
                            pass
                        st.success(f"✅ Deleted plate geometry for '{del_pid}'.")
                        st.rerun()
            except Exception as e:
                st.error(f"❌ Failed: {e}")
    
    st.markdown("---")
    st.subheader("💡 Tips")
    st.markdown("""
    **Auto-detection:**
    - Plate IDs containing "96" → Auto-register as 96-well (A-H × 12)
    - Plate IDs containing "48" → Auto-register as 48-well (A-F × 8)
    - Plate IDs containing "24" → Auto-register as 24-well (A-D × 6)
    
    **Custom formats:**
    - 384-well: Row labels = ABCDEFGHIJKLMNOP (16), Max cols = 24
    - 8-well slide: Row labels = AB (2), Max cols = 4
    - Custom array: Define any format!
    
    **Validation:**
    - Row labels must be letters (auto-uppercased, duplicates rejected)
    - Max columns must be ≥ 1
    - Geometry enforced in New Entry, Clone, and Plate Map Wizard
    """)

def show_images_manager(codebook):
    """Image upload and gallery manager."""
    st.header("📷 Gel Images")
    st.caption("Upload and manage images for visual QC and model training")
    
    df_wells = read_wells()
    if df_wells.empty:
        st.info("No wells yet. Create wells first before uploading images.")
        return
    
    # Select well
    options = [(f"{r['record_id'][:10]}… — {r.get('batch_id','N/A')} — {r.get('family','N/A')}", r['record_id']) 
               for _, r in df_wells.iterrows()]
    label = st.selectbox("Select a well", options=[o[0] for o in options])
    record_id = dict(options)[label]
    
    st.markdown("---")
    
    # Upload section
    st.subheader("📤 Upload Images")
    
    # Optional: Link to specific event
    df_events = get_events(record_id)
    event_id_link = None
    if not df_events.empty:
        with st.expander("🔗 Link to specific event (optional)", expanded=False):
            st.caption("Associate this image with a specific time point/observation")
            event_options = ["(none - general well image)"] + [
                f"Day {row['day_from_mix']} — {row['event_type']} — {row.get('status_code','')} (ID: {row['event_id']})"
                for _, row in df_events.iterrows()
            ]
            event_choice = st.selectbox("Event", event_options)
            if event_choice != "(none - general well image)":
                # Extract event_id from the string
                import re
                match = re.search(r'\(ID: (\d+)\)', event_choice)
                if match:
                    event_id_link = int(match.group(1))
    
    uploaded = st.file_uploader(
        "Drop images here",
        type=["jpg", "jpeg", "png", "tif", "tiff", "webp"],
        accept_multiple_files=True,
        help="Max ~25 MB per image. You can upload multiple images at once or come back later to upload more!"
    )
    
    colA, colB, colC = st.columns(3)
    with colA:
        kind = st.selectbox("Kind", ["photo", "tilt", "macro", "micrograph", "other"])
    with colB:
        lighting = st.text_input("Lighting", placeholder="top, side, transillumination")
    with colC:
        magnification = st.text_input("Magnification", placeholder="phone, 4x, 10x")
    
    caption = st.text_input("Caption (optional)", placeholder="e.g., 'Gel at 24h, starting to soften'")
    tilt_deg = st.number_input("Tilt angle (deg)", 0.0, 90.0, 0.0, 1.0, help="For tilt-test photos")
    qc_flag = st.checkbox("Include in training", value=True)
    operator = st.text_input("Uploader ID", value=st.session_state.get("last_operator_id", ""))
    
    if uploaded and st.button("📷 Upload Images", type="primary"):
        for file in uploaded:
            try:
                raw = file.read()
                
                # Size limit (25 MB)
                if len(raw) > 25 * 1024 * 1024:
                    st.error(f"❌ {file.name}: Too large (max 25 MB)")
                    continue
                
                sha = _sha256_bytes(raw)
                mime = file.type or "application/octet-stream"
                ext = _safe_ext(mime)
                img_id = new_record_id()
                
                # Paths
                rel_dir = Path("media") / "images" / record_id
                rel_path = rel_dir / f"{img_id}{ext}"
                abs_path = ROOT / rel_path
                abs_path.parent.mkdir(parents=True, exist_ok=True)
                
                with open(abs_path, "wb") as f:
                    f.write(raw)
                
                # Thumbnail + dims + EXIF
                thm_rel = Path("media") / "thumbs" / record_id / f"{img_id}.jpg"
                thm_abs = ROOT / thm_rel
                width, height = _probe_dims(raw)
                taken_at = _exif_datetime(Image.open(io.BytesIO(raw))) or datetime.now().isoformat()
                _save_thumbnail(raw, thm_abs)
                
                payload = {
                    "image_id": img_id,
                    "record_id": record_id,
                    "event_id": event_id_link,  # Link to event if selected
                    "taken_at": taken_at,
                    "operator_id": (operator or None),
                    "caption": (caption or None),
                    "kind": kind,
                    "mime_type": mime,
                    "width_px": int(width),
                    "height_px": int(height),
                    "sha256_hex": sha,
                    "file_relpath": str(rel_path),
                    "thumb_relpath": str(thm_rel),
                    "lighting": (lighting or None),
                    "magnification": (magnification or None),
                    "tilt_deg": (None if tilt_deg == 0 else float(tilt_deg)),
                    "qc_flag": 1 if qc_flag else 0
                }
                add_image_record(payload)
                st.success(f"✅ Uploaded {file.name}")
                
            except Exception as e:
                st.error(f"❌ Failed {file.name}: {e}")
        
        st.balloons()
        st.rerun()
    
    st.markdown("---")
    
    # Gallery
    st.subheader("🖼️ Image Gallery")
    imgs = get_images_for_record(record_id)
    
    if imgs.empty:
        st.info("No images for this well yet.")
    else:
        st.caption(f"**Total images:** {len(imgs)}")
        
        # Grid view of thumbnails
        cols = st.columns(4)
        for i, (_, row) in enumerate(imgs.iterrows()):
            c = cols[i % 4]
            with c:
                thm = ROOT / row["thumb_relpath"] if row.get("thumb_relpath") else None
                if thm and thm.exists():
                    st.image(str(thm), caption=row.get("caption") or row["image_id"][:8], use_column_width=True)
                else:
                    st.caption("🖼️ (thumbnail missing)")
                
                st.caption(f"**{row['kind']}** • {row['width_px']}×{row['height_px']}")
                
                # Show event link if present
                if row.get("event_id"):
                    st.caption(f"📅 Linked to event #{row['event_id']}")
                
                # Show capture time
                if row.get("taken_at"):
                    taken_short = row['taken_at'][:10] if len(row['taken_at']) >= 10 else row['taken_at']
                    st.caption(f"📸 {taken_short}")
                
                if row.get("lighting"):
                    st.caption(f"💡 {row['lighting']}")
                if row.get("magnification"):
                    st.caption(f"🔍 {row['magnification']}")
                if row.get("tilt_deg") and row['tilt_deg'] > 0:
                    st.caption(f"📐 Tilt: {row['tilt_deg']}°")
                
                if st.button("🗑️ Delete", key=f"del_{row['image_id']}"):
                    delete_image(row["image_id"])
                    st.success("Image deleted")
                    st.rerun()

def show_export_page():
    st.header("Export Data")
    
    # Backup section at top
    st.subheader("🧷 Database Backup")
    col_b1, col_b2, col_b3 = st.columns([1, 2, 1])
    
    with col_b1:
        if st.button("📦 Backup Database", use_container_width=True):
            try:
                backups = ROOT / "backups"
                backups.mkdir(exist_ok=True)
                ts = datetime.now().strftime("%Y%m%d_%H%M%S")
                dest = backups / f"gelpredict_{ts}.db"
                shutil.copy2(DB_PATH, dest)
                st.success(f"✅ Backup created: `{dest.name}`")
                st.caption(f"Location: `{dest.relative_to(ROOT)}`")
            except Exception as e:
                st.error(f"❌ Backup failed: {e}")
    
    with col_b2:
        st.caption("Creates timestamped copy of `gelpredict.db` in `/backups`.")
        # Show recent backups
        backups_dir = ROOT / "backups"
        if backups_dir.exists():
            backups_list = sorted(backups_dir.glob("gelpredict_*.db"), reverse=True)
            if backups_list:
                st.caption(f"💾 Recent backups: {len(backups_list)} found")
    
    with col_b3:
        if st.button("🧹 VACUUM (compact)", use_container_width=True):
            try:
                with tx() as con:
                    con.execute("VACUUM")
                st.success("✅ Database compacted")
                st.caption("Reclaimed unused space")
            except Exception as e:
                st.error(f"❌ Failed: {e}")
    
    st.markdown("---")

    df_wells = read_wells(use_effective_view=True)
    if df_wells.empty:
        st.info("No data to export yet.")
        return

    st.subheader("📊 Wells (preview)")
    st.dataframe(df_wells.head(10), use_container_width=True)

    c1,c2,c3 = st.columns(3)

    with c1:
        st.download_button(
            "⬇️ Wells (CSV)",
            df_wells.to_csv(index=False),
            file_name=f"wells_master_{datetime.now().strftime('%Y%m%d')}.csv",
            mime="text/csv"
        )

    with c2:
        conn = get_connection()
        df_rg = pd.read_sql_query("SELECT * FROM reagents_per_well", conn)
        conn.close()
        if not df_rg.empty:
            st.download_button(
                "⬇️ Reagents (CSV)",
                df_rg.to_csv(index=False),
                file_name=f"reagents_per_well_{datetime.now().strftime('%Y%m%d')}.csv",
                mime="text/csv"
            )

    with c3:
        conn = get_connection()
        df_ev = pd.read_sql_query("SELECT * FROM events_long", conn)
        conn.close()
        if not df_ev.empty:
            st.download_button(
                "⬇️ Events (CSV)",
                df_ev.to_csv(index=False),
                file_name=f"events_long_{datetime.now().strftime('%Y%m%d')}.csv",
                mime="text/csv"
            )

    st.subheader("🤖 Export for Training")
    st.caption("Complete dataset with all experimental parameters, protocols, and outcomes")
    
    # Comprehensive training dataset with all new parameters
    training_cols = [
        # Identifiers & metadata
        'record_id','date','operator_id','family','batch_id','gelation_id','donor_id',
        'ecm_origin_species','ecm_source_tissue','plate_id','row','col','replicate_id',
        
        # Pre-processing tissue storage (NEW!)
        'pre_storage_days_4C','pre_storage_fresh_notes','pre_storage_freeze_cycles','pre_storage_temp_freezer','pre_storage_duration_months','pre_storage_frozen_in','pre_storage_thaw_method','pre_storage_thaw_duration_min','pre_storage_ft_notes',
        
        # Processing & gelation protocols (JSON)
        'processing_protocol','gelation_protocol',
        
        # Composition measurements
        'ecm_total_protein_mgml','protein_assay_method','gel_volume_uL',
        'pre_pH','pre_conductivity_mS','temp_incubation_C',
        
        # Spectroscopy
        'uv_A220','uv_A280','uv_ratio_A220_A280',
        'sds_smear_index','sds_alpha_ratio',
        
        # Advanced biochemical assays (optional)
        'hydroxyproline_mgml','dmmB_GAG_ugml','viscosity_proxy_sec',
        
        # Pre-gel viscosity (Scientific Reports 2019) (optional)
        'pre_gel_viscosity_mPas','pre_gel_viscosity_temp_C','shear_rate_s_minus1',
        
        # Turbidity/gelation kinetics (Scientific Reports 2019, MDPI 2021) (optional)
        'turbidity_lag_time_min','turbidity_t_half_min','turbidity_slope_per_min',
        
        # Viscoelastic/rheological properties (Saldin et al. 2016, Brazdaru et al. 2015) (optional)
        'storage_modulus_G_prime_Pa','loss_modulus_G_double_prime_Pa','tan_delta',
        
        # Residual contaminants (cornea ECM study 2019) (optional)
        'sds_residual_ppm','detergent_residual_binary','cytotoxicity_score_0to3',
        
        # Micro-DSC parameters (optional)
        'dsc_onset_T_C','dsc_peak_T_C','dsc_delta_H_J_g',
        
        # Circular Dichroism parameters (optional)
        'cd_molar_ellipticity_222nm_mdeg','cd_helix_percent',
        
        # FTIR parameters (optional)
        'ftir_amide3_1450_ratio',
        
        # Additional residual contaminants (optional)
        'dna_residual_ng_mg','endotoxin_residual_EU_mg','protease_residual_U_mg',
        
        # Swelling ratio parameters (optional)
        'swelling_ratio_Q','gel_fresh_weight_mg','gel_swollen_weight_mg','gel_dry_weight_mg',
        
        # Enzymatic degradation parameters (optional)
        'enzymatic_degradation_t_half_min','collagenase_concentration_U_mL',
        
        # Diffusion/FRAP parameters (optional)
        'diffusion_coefficient_um2_s','frap_t_half_s','probe_radius_um',
        
        # Test conditions
        'probe_type','target_pH',
        'od_wavelength_nm','od_sampling_interval_min','time_to_halfmax_min',
        
        # Effective ionic concentrations (from view - will be renamed for AI compatibility)
        'eff_NaCl_mM','eff_CaCl2_mM','pbs_final_x','media_percent',
        
        # Gelation kinetics (NEW!)
        'time_to_gel_min','pre_gel_storage_temp_C','pre_gel_storage_duration_min','pre_gel_storage_notes',
        
        # Outcomes
        'gel_binary','gel_strength_score_0to3','tilt_test_angle_deg',
        'failure_mode','suspected_cause','confidence_0to1',
        'syneresis_binary','precipitate_binary','color_shift',
        
        # Degradation tracking (NEW!)
        'disintegrated','days_to_disintegration','reliquefied','days_to_reliquefaction',
        'plate_adhesion','adhesion_notes',
        
        # Commercial product tracking
        'is_commercial_product','commercial_vendor','commercial_product_name','commercial_website',
        
        # Notes
        'notes_pre','notes_post',
        
        # Split
        'split'
    ]
    
    export_cols = [c for c in training_cols if c in df_wells.columns]
    df_training = df_wells[export_cols].copy()
    
    # Rename columns to match AI model expectations (DEFAULT_FEATURES in src/train_baseline.py)
    ai_column_mapping = {
        'eff_NaCl_mM': 'NaCl_mM_added',
        'eff_CaCl2_mM': 'CaCl2_mM_added',
        'pbs_final_x': 'PBS_10x_uL_per_mL',
        'media_percent': 'DMEM_percent'
    }
    
    # Only rename columns that exist in the dataframe
    rename_map = {old: new for old, new in ai_column_mapping.items() if old in df_training.columns}
    if rename_map:
        df_training = df_training.rename(columns=rename_map)
    
    st.write(f"**Training dataset:** {len(df_training)} wells × {len(df_training.columns)} features")
    st.caption("✅ Column names aligned with AI model expectations (`src/train_baseline.py`)")
    
    # Show summary of what's included
    with st.expander("📋 Features included in training export"):
        feature_groups = {
            "Identifiers": ['record_id','date','family','batch_id','gelation_id'],
            "Pre-storage": ['pre_storage_days_4C','pre_storage_fresh_notes','pre_storage_freeze_cycles','pre_storage_temp_freezer','pre_storage_duration_months','pre_storage_frozen_in','pre_storage_thaw_method','pre_storage_thaw_duration_min','pre_storage_ft_notes'],
            "Protocols": ['processing_protocol','gelation_protocol'],
            "Composition": ['ecm_total_protein_mgml','protein_assay_method','pre_pH','pre_conductivity_mS'],
            "Ionic & Media (AI features)": ['NaCl_mM_added','CaCl2_mM_added','PBS_10x_uL_per_mL','DMEM_percent'],
            "Gelation Kinetics": ['time_to_gel_min','pre_gel_storage_temp_C','pre_gel_storage_duration_min'],
            "Degradation": ['disintegrated','days_to_disintegration','reliquefied','days_to_reliquefaction','plate_adhesion'],
            "Outcomes": ['gel_binary','gel_strength_score_0to3','failure_mode']
        }
        
        for group_name, cols in feature_groups.items():
            available = [c for c in cols if c in export_cols]
            if available:
                st.caption(f"**{group_name}:** {len(available)} fields")
    
    st.download_button(
        "⬇️ Training Dataset (CSV)",
        df_training.to_csv(index=False),
        file_name=f"ecm_runs_export_{datetime.now().strftime('%Y%m%d')}.csv",
        mime="text/csv",
        use_container_width=True
    )
    st.success("✅ Includes all new parameters: pre-storage, protocols (JSON), gelation kinetics, degradation tracking")
    st.caption("💡 **Next step:** Use `src/feature_engineering.py` to parse JSON protocols and extract features (decell method, dialysis acid concentration, processing temps, etc.)")
    
    st.markdown("---")
    
    st.subheader("📑 Data Dictionary")
    st.caption("Auto-generated from field specifications — perfect for methods sections and collaborators")
    
    if st.button("📑 Generate Data Dictionary", use_container_width=True):
        try:
            dict_path = ROOT / "data_dictionary.csv"
            df_dict = export_data_dictionary(FIELD_SPEC, dict_path)
            
            st.success(f"✅ Data dictionary generated ({len(df_dict)} fields)")
            
            # Preview
            with st.expander("Preview data dictionary"):
                st.dataframe(df_dict.head(20), use_container_width=True)
            
            # Download
            csv_dict = df_dict.to_csv(index=False)
            st.download_button(
                "⬇️ Download Data Dictionary (CSV)",
                csv_dict,
                file_name="GelPredict_DataDictionary.csv",
                mime="text/csv",
                use_container_width=True
            )
        except Exception as e:
            st.error(f"❌ Error generating dictionary: {e}")
    
    st.markdown("---")

    st.subheader("📤 Export Excel Workbook (for PIs)")
    st.caption("📊 Professional workbook with charts, pivots, and data dictionary")
    
    exporter = ROOT / "export_to_excel.py"
    if st.button("📊 Generate Excel Export", type="primary", use_container_width=True):
        if not exporter.exists():
            st.error("❌ export_to_excel.py not found in project root.")
        else:
            with st.spinner("Generating Excel workbook with charts..."):
                result = subprocess.run(["python", str(exporter)], capture_output=True, text=True)
                
                # Parse output to find the created file
                out_path = None
                if result.stdout:
                    for line in result.stdout.splitlines()[::-1]:
                        if line.strip().endswith(".xlsx"):
                            # Extract just the filename from the path
                            out_path = ROOT / Path(line.strip()).name
                            break
                
                # Fallback: construct expected filename
                if out_path is None:
                    ts = datetime.now().strftime("%Y%m%d_%H%M")
                    out_path = ROOT / f"GelPredict_Export_{ts}.xlsx"
                
                if result.returncode == 0 and out_path.exists():
                    # Success toast
                    st.toast("✅ Workbook ready!", icon="📊")
                    
                    with open(out_path, "rb") as f:
                        st.download_button(
                            "⬇️ Download Excel Workbook", 
                            f, 
                            file_name=out_path.name, 
                            mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                            use_container_width=True
                        )
                    st.success(f"✅ Excel export complete: {out_path.name}")
                    
                    # Show export log
                    if result.stdout:
                        with st.expander("View export log"):
                            st.code(result.stdout)
                else:
                    st.error("❌ Export failed — ensure Python can import openpyxl and pandas.")
                    st.info("💡 Run: `pip install openpyxl`")
                    if result.stderr:
                        with st.expander("Error details"):
                            st.code(result.stderr)

    st.markdown("---")
    
    # Image manifest export
    st.subheader("🖼️ Images Manifest (for training)")
    st.caption("Export image metadata for model training with visual features")
    
    conn = get_connection()
    df_img = pd.read_sql_query("""
        SELECT gi.image_id, gi.record_id, gi.event_id, gi.qc_flag, gi.kind, gi.taken_at,
               gi.file_relpath, gi.thumb_relpath, gi.width_px, gi.height_px, gi.sha256_hex,
               gi.lighting, gi.magnification, gi.tilt_deg, gi.caption,
               w.family, w.batch_id, w.gel_binary, w.gel_strength_score_0to3, w.target_pH,
               w.temp_incubation_C, w.date
        FROM gel_images gi
        LEFT JOIN wells_master_v4 w ON w.record_id = gi.record_id
        ORDER BY gi.created_at DESC
    """, conn)
    conn.close()
    
    if df_img.empty:
        st.info("No images uploaded yet.")
    else:
        st.caption(f"**Total images:** {len(df_img)} ({len(df_img[df_img['qc_flag']==1])} marked for training)")
        
        # Preview
        with st.expander("Preview image metadata"):
            st.dataframe(df_img.head(12), use_container_width=True)
        
        # Download
        st.download_button(
            "⬇️ Images Manifest (CSV)",
            df_img.to_csv(index=False),
            file_name=f"gel_images_manifest_{datetime.now().strftime('%Y%m%d')}.csv",
            mime="text/csv",
            use_container_width=True
        )

# ============================================================================
# RUN
# ============================================================================

if __name__ == "__main__":
    main()