File size: 197,595 Bytes
9df6ae5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cors from "cors";
import express from "express";
import multer from "multer";
import fs from "node:fs";
import fsp from "node:fs/promises";
import crypto from "node:crypto";
import https from "node:https";
import http from "node:http";
import path from "node:path";
import os from "node:os";
import { fileURLToPath } from "node:url";
import { spawn } from "node:child_process";
import { Readable } from "node:stream";
import {
  S3Client,
  CreateMultipartUploadCommand,
  UploadPartCommand,
  CompleteMultipartUploadCommand,
  AbortMultipartUploadCommand,
  CopyObjectCommand,
  DeleteObjectCommand,
  GetObjectCommand,
  PutObjectCommand,
} from "@aws-sdk/client-s3";

const __filename = fileURLToPath(import.meta.url);

// Robust fetch with timeout using AbortController (works on all Node.js versions)
async function fetchWithTimeout(url, options = {}, timeoutMs = 5000) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(url, { ...options, signal: controller.signal });
    clearTimeout(timeoutId);
    return response;
  } catch (err) {
    clearTimeout(timeoutId);
    if (err.name === "AbortError") {
      throw new Error(`Timed out after ${timeoutMs / 1000}s - server not responding`);
    }
    // Provide clearer error messages for common network issues
    const errMsg = err.message || String(err);
    if (errMsg.includes("fetch failed") || errMsg.includes("ECONNREFUSED")) {
      throw new Error(`Cannot connect to server. The server may be down, or HuggingFace Spaces may block connections to this port. Try a standard port (80, 443, 8080).`);
    }
    if (errMsg.includes("ENOTFOUND") || errMsg.includes("getaddrinfo")) {
      throw new Error(`Server hostname not found: ${url}`);
    }
    if (errMsg.includes("ETIMEDOUT") || errMsg.includes("ENETUNREACH")) {
      throw new Error(`Network unreachable or timed out connecting to: ${url}`);
    }
    throw err;
  }
}
const __dirname = path.dirname(__filename);
const projectRoot = path.resolve(__dirname, "..");
const distDir = path.join(projectRoot, "dist");

const PORT = Number(process.env.PORT || 7860);
const HOST = process.env.HOST || "0.0.0.0";
const DOWNLOADS_DIR = process.env.DOWNLOADS_DIR || path.join(projectRoot, "downloads");
const ENCODED_DIR = process.env.ENCODED_DIR || path.join(projectRoot, "encoded");

await fsp.mkdir(DOWNLOADS_DIR, { recursive: true });
await fsp.mkdir(ENCODED_DIR, { recursive: true });

// ── Cross-device safe move ─────────────────────────────────────────────────────
// fs.rename fails with EXDEV when src and dest are on different filesystems
// (e.g. /tmp β†’ /home/runner/workspace).  Fall back to copy + unlink.
async function safeMoveFile(src, dest) {
  try {
    await fsp.rename(src, dest);
  } catch (err) {
    if (err.code === "EXDEV") {
      await fsp.copyFile(src, dest);
      await fsp.unlink(src);
    } else {
      throw err;
    }
  }
}

// ── Startup validation ────────────────────────────────────────────────────────
async function checkBinary(name) {
  return new Promise((resolve) => {
    const proc = spawn(name, ["-version"], { stdio: "pipe" });
    proc.on("close", (code) => resolve(code === 0));
    proc.on("error", () => resolve(false));
    // timeout after 5 seconds
    setTimeout(() => { try { proc.kill(); } catch {}; resolve(false); }, 5000);
  });
}

const ffmpegOk = await checkBinary("ffmpeg");
const ffprobeOk = await checkBinary("ffprobe");

if (!ffmpegOk) console.warn("[warn] ffmpeg not found on PATH β€” encoding, trimming, and video info will fail.");
if (!ffprobeOk) console.warn("[warn] ffprobe not found on PATH β€” video metadata extraction will fail.");
if (ffmpegOk && ffprobeOk) console.log("[ok] ffmpeg and ffprobe found on PATH.");

const app = express();

// ── Basic Auth ─────────────────────────────────────────────────────────────────
const AUTH_USER = process.env.APP_USERNAME || "admin";
const AUTH_PASS = process.env.APP_PASSWORD || "1234";

function basicAuth(req, res, next) {
  // Skip auth for internal health-check pings if needed
  const header = req.headers["authorization"] || "";
  const match = header.match(/^Basic\s+(.+)$/i);
  if (match) {
    const decoded = Buffer.from(match[1], "base64").toString("utf8");
    const colon = decoded.indexOf(":");
    if (colon !== -1) {
      const user = decoded.slice(0, colon);
      const pass = decoded.slice(colon + 1);
      // Constant-time comparison to prevent timing attacks
      const userOk = user.length === AUTH_USER.length &&
        crypto.timingSafeEqual(Buffer.from(user), Buffer.from(AUTH_USER));
      const passOk = pass.length === AUTH_PASS.length &&
        crypto.timingSafeEqual(Buffer.from(pass), Buffer.from(AUTH_PASS));
      if (userOk && passOk) return next();
    }
  }
  res.set("WWW-Authenticate", 'Basic realm="OgA-Encoder"');
  res.status(401).send("Unauthorized");
}

app.use(basicAuth);

app.use(cors());
app.use(express.json({ limit: "1mb" }));
const upload = multer({ storage: multer.memoryStorage() });

// ── Job stores ─────────────────────────────────────────────────────────────────
const jobs = new Map();
const downloadJobs = new Map();

// ── Job history persistence ───────────────────────────────────────────────────
const HISTORY_FILE = path.join(projectRoot, 'data', 'jobs_history.json');
await fsp.mkdir(path.dirname(HISTORY_FILE), { recursive: true });
try {
  const raw = await fsp.readFile(HISTORY_FILE, 'utf8');
  const hist = JSON.parse(raw);
  if (Array.isArray(hist)) {
    for (const j of hist) jobs.set(j.id, { ...j, _process: null });
    console.log(`[ok] Loaded ${hist.length} historical job(s)`);
  }
} catch { /* no history file yet */ }

async function persistJobHistory() {
  try {
    const toSave = [...jobs.values()]
      .filter(j => j.status !== 'running')
      .sort((a, b) => b.createdAt - a.createdAt)
      .slice(0, 300)
      .map(({ _process: _p, ...j }) => j);
    await fsp.writeFile(HISTORY_FILE, JSON.stringify(toSave, null, 2), 'utf8');
  } catch { /* ignore */ }
}

// ── App settings persistence ──────────────────────────────────────────────────
const SETTINGS_FILE = path.join(projectRoot, 'data', 'app_settings.json');
let appSettings = {};
try {
  const raw = await fsp.readFile(SETTINGS_FILE, 'utf8');
  appSettings = JSON.parse(raw);
  console.log('[ok] Loaded app settings');
} catch { /* no settings file yet */ }

async function persistSettings(patch) {
  try {
    appSettings = { ...appSettings, ...patch };
    await fsp.writeFile(SETTINGS_FILE, JSON.stringify(appSettings, null, 2), 'utf8');
  } catch { /* ignore */ }
}

app.get('/api/settings', (req, res) => res.json(appSettings));

app.post('/api/settings', async (req, res) => {
  await persistSettings(req.body || {});
  res.json({ ok: true });
});

function randomId(prefix = "job") {
  return `${prefix}_${Math.random().toString(16).slice(2)}_${Date.now().toString(16)}`;
}

function parseFfmpegTimeToSeconds(value) {
  const parts = value.split(":");
  if (parts.length !== 3) return 0;
  const [hh, mm, ss] = parts;
  return Number(hh) * 3600 + Number(mm) * 60 + Number(ss);
}

function parseLooseClockToSeconds(value) {
  const parts = String(value || "").split(":").map((p) => Number(p));
  if (parts.some((n) => Number.isNaN(n) || n < 0)) return null;
  if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  if (parts.length === 2) return parts[0] * 60 + parts[1];
  if (parts.length === 1 && String(value || "").trim()) return parts[0];
  return null;
}

function runProcess(command, args) {
  return new Promise((resolve, reject) => {
    const p = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
    let stdout = "";
    let stderr = "";
    p.stdout.on("data", (d) => { stdout += d.toString(); });
    p.stderr.on("data", (d) => { stderr += d.toString(); });
    p.on("error", reject);
    p.on("close", (code) => {
      if (code === 0) resolve({ stdout, stderr });
      else reject(new Error(stderr || `${command} exited with code ${code}`));
    });
  });
}

function isChildProcessRunning(child) {
  return Boolean(child && !child.killed && child.exitCode === null);
}

function stopFfmpegProcess(job, reason = "Job stopped by user.") {
  if (!job || job.status !== "running") return;
  job.status = "stopped";
  job.progress?.log?.push(reason);

  const child = job._process;
  if (!isChildProcessRunning(child)) {
    job._process = null;
    return;
  }

  let escalationStarted = false;
  const escalateStop = () => {
    if (!isChildProcessRunning(child)) return;
    if (!escalationStarted) {
      escalationStarted = true;
      try { child.kill("SIGTERM"); } catch { /* ignore */ }
      setTimeout(() => {
        if (!isChildProcessRunning(child)) return;
        try { child.kill("SIGKILL"); } catch { /* ignore */ }
      }, 3000).unref?.();
    }
  };

  try {
    if (child.stdin && !child.stdin.destroyed) {
      child.stdin.write("q\n", (err) => {
        if (err) escalateStop();
      });
      setTimeout(escalateStop, 1500).unref?.();
      return;
    }
  } catch {
    // fall through to signal-based stop
  }

  escalateStop();
}

async function getDurationSeconds(filePath) {
  try {
    const { stdout } = await runProcess("ffprobe", [
      "-v", "error",
      "-show_entries", "format=duration",
      "-of", "default=noprint_wrappers=1:nokey=1",
      filePath,
    ]);
    const sec = Number(stdout.trim());
    return Number.isFinite(sec) ? sec : 0;
  } catch {
    return 0;
  }
}

function fixUtf8(str) {
  if (!str) return str;
  const win1252Map = new Set([
    0x20ac, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030,
    0x0160, 0x2039, 0x0152, 0x017d, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022,
    0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x017e, 0x0178,
  ]);
  let isLikelyMojibake = true;
  for (let i = 0; i < str.length; i++) {
    const code = str.charCodeAt(i);
    if (code > 0x00ff && !win1252Map.has(code)) { isLikelyMojibake = false; break; }
  }
  if (!isLikelyMojibake) return str;
  try {
    const bytes = new Uint8Array(str.length);
    for (let i = 0; i < str.length; i++) {
      let code = str.charCodeAt(i);
      if (code === 0x20ac) code = 0x80; else if (code === 0x201a) code = 0x82;
      else if (code === 0x0192) code = 0x83; else if (code === 0x201e) code = 0x84;
      else if (code === 0x2026) code = 0x85; else if (code === 0x2020) code = 0x86;
      else if (code === 0x2021) code = 0x87; else if (code === 0x02c6) code = 0x88;
      else if (code === 0x2030) code = 0x89; else if (code === 0x0160) code = 0x8a;
      else if (code === 0x2039) code = 0x8b; else if (code === 0x0152) code = 0x8c;
      else if (code === 0x017d) code = 0x8e; else if (code === 0x2018) code = 0x91;
      else if (code === 0x2019) code = 0x92; else if (code === 0x201c) code = 0x93;
      else if (code === 0x201d) code = 0x94; else if (code === 0x2022) code = 0x95;
      else if (code === 0x2013) code = 0x96; else if (code === 0x2014) code = 0x97;
      else if (code === 0x02dc) code = 0x98; else if (code === 0x2122) code = 0x99;
      else if (code === 0x0161) code = 0x9a; else if (code === 0x203a) code = 0x9b;
      else if (code === 0x0153) code = 0x9c; else if (code === 0x017e) code = 0x9e;
      else if (code === 0x0178) code = 0x9f;
      bytes[i] = code;
    }
    const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
    return decoded;
  } catch { /* fall through */ }
  return str;
}

function safeFilenameFromUrl(urlValue) {
  try {
    const u = new URL(urlValue);
    const name = decodeURIComponent(path.basename(u.pathname || "")).trim();
    return fixUtf8(name) || `download_${Date.now()}.bin`;
  } catch {
    return `download_${Date.now()}.bin`;
  }
}

function getFilenameFromHeaders(response, urlValue) {
  const disposition = response.headers.get("content-disposition");
  if (disposition) {
    const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i);
    if (utf8Match) return decodeURIComponent(utf8Match[1]);
    const asciiMatch = disposition.match(/filename="([^"]+)"/i);
    if (asciiMatch) return fixUtf8(asciiMatch[1]);
  }
  return safeFilenameFromUrl(urlValue);
}

/**

 * Sanitize a single path segment (no slashes allowed).

 */
function sanitizeSegment(seg, fallback = "file") {
  const cleaned = String(seg || "")
    .normalize("NFC")
    .replace(/[\\/]/g, "_")
    .replace(/[.\s]+$/, "")       // no trailing dots/spaces
    .replace(/^[.\s]+/, "")       // no leading dots/spaces
    .replace(/[\u0000-\u001f\u007f]/g, "")
    .trim();
  return cleaned || fallback;
}

/**

 * Sanitize a relative folder path like "MyShow/Season 1"

 * Each segment is sanitized individually.

 */
function sanitizeFolderPath(rawPath) {
  if (!rawPath || rawPath === "/" || rawPath === ".") return "/";
  return rawPath
    .split(/[\\/]/)
    .filter(Boolean)
    .map((seg) => sanitizeSegment(seg, "folder"))
    .join("/");
}

function getUniqueFilePath(dir, filename) {
  const baseName = path.parse(filename).name || "file";
  const ext = path.parse(filename).ext || "";
  let candidateName = `${baseName}${ext}`;
  let candidatePath = path.join(dir, candidateName);
  let i = 1;
  while (fs.existsSync(candidatePath)) {
    candidateName = `${baseName} (${i})${ext}`;
    candidatePath = path.join(dir, candidateName);
    i += 1;
  }
  return { name: candidateName, fullPath: candidatePath };
}

async function getVideoResolution(filePath) {
  try {
    const { stdout } = await runProcess("ffprobe", [
      "-v", "error", "-select_streams", "v:0",
      "-show_entries", "stream=width,height",
      "-of", "csv=s=x:p=0", filePath,
    ]);
    return stdout.trim() || "unknown";
  } catch {
    return "unknown";
  }
}

/**

 * Resolve a file id like "downloaded:MyFolder/filename.mkv"

 * Returns { source, name (relative path), filePath (absolute), folder }

 */
function resolveFileFromId(fileId) {
  const [source, ...nameParts] = String(fileId || "").split(":");
  const name = nameParts.join(":");
  if (!name || (source !== "downloaded" && source !== "encoded")) return null;

  // Prevent path traversal
  const base = source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR;
  const resolved = path.resolve(base, name);
  if (!resolved.startsWith(base + path.sep) && resolved !== base) return null;

  const folder = path.dirname(name) === "." ? "/" : `/${path.dirname(name)}`;
  return { source, name, filePath: resolved, folder };
}

/**

 * Recursively list all files under dirPath, returning entries with relative paths.

 */
async function listFilesRecursive(dirPath, source, relDir = "") {
  const out = [];
  let entries;
  try {
    entries = await fsp.readdir(dirPath, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const entry of entries) {
    const fullPath = path.join(dirPath, entry.name);
    const relPath = relDir ? `${relDir}/${entry.name}` : entry.name;
    if (entry.isDirectory()) {
      const children = await listFilesRecursive(fullPath, source, relPath);
      out.push(...children);
    } else if (entry.isFile()) {
      // Skip hidden/temp files and settings sidecars
      if (entry.name.startsWith("_concat_") || entry.name.startsWith(".")) continue;
      if (entry.name.endsWith(".settings.json")) continue;
      const st = await fsp.stat(fullPath);
      const folder = relDir ? `/${relDir}` : "/";
      out.push({
        id: `${source}:${relPath}`,
        name: entry.name,
        relativePath: relPath,
        sizeBytes: st.size,
        source,
        createdAt: st.mtimeMs,
        folder,
      });
    }
  }
  return out;
}

async function listFoldersRecursive(dirPath, relDir = "") {
  const out = [];
  let entries;
  try {
    entries = await fsp.readdir(dirPath, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const entry of entries) {
    if (!entry.isDirectory()) continue;
    if (entry.name.startsWith(".")) continue;
    const relPath = relDir ? `${relDir}/${entry.name}` : entry.name;
    out.push(`/${relPath}`);
    const children = await listFoldersRecursive(path.join(dirPath, entry.name), relPath);
    out.push(...children);
  }
  return out;
}

function buildEncodeArgs(settings, inputPath, outputPath) {
  const args = ["-y"];

  const startSeconds = settings.startTime ? parseLooseClockToSeconds(String(settings.startTime)) : null;
  const endSeconds = settings.endTime ? parseLooseClockToSeconds(String(settings.endTime)) : null;

  if (startSeconds != null) args.push("-ss", String(settings.startTime));
  if (endSeconds != null && (startSeconds == null || endSeconds > startSeconds)) {
    args.push("-to", String(settings.endTime));
  }

  args.push("-i", inputPath);

  const subtitleRel = settings.subtitleFile ? String(settings.subtitleFile) : "";
  let subtitlePath = null;
  let subtitleExists = false;
  if (subtitleRel) {
    const resolvedSub = path.resolve(DOWNLOADS_DIR, subtitleRel);
    if (resolvedSub.startsWith(DOWNLOADS_DIR + path.sep) || resolvedSub === DOWNLOADS_DIR) {
      subtitlePath = resolvedSub;
      subtitleExists = fs.existsSync(resolvedSub);
    }
  }
  if (subtitleExists) {
    args.push("-i", subtitlePath);
  }

  const isAudioOnly = settings.outputFormat === 'audio';
  const sameAsOriginalVideo = settings.sameAsOriginalVideo;
  const sameAsOriginalAudio = settings.sameAsOriginalAudio;
  const cropEnabled = Boolean(settings.cropEnabled);
  const cropLeft = Number(settings.cropLeft ?? 0);
  const cropRight = Number(settings.cropRight ?? 0);
  const cropTop = Number(settings.cropTop ?? 0);
  const cropBottom = Number(settings.cropBottom ?? 0);
  const needsVideoReencode = !isAudioOnly && (!sameAsOriginalVideo || cropEnabled);

  const filters = [];
  if (!isAudioOnly && needsVideoReencode) {
    if (cropEnabled && (cropLeft > 0 || cropRight > 0 || cropTop > 0 || cropBottom > 0)) {
      const cropW = 100 - cropLeft - cropRight;
      const cropH = 100 - cropTop - cropBottom;
      const cropX = cropLeft;
      const cropY = cropTop;
      filters.push(`crop=iw*${Math.max(0, cropW) / 100}:ih*${Math.max(0, cropH) / 100}:iw*${Math.max(0, cropX) / 100}:ih*${Math.max(0, cropY) / 100}`);
    }

    if (settings.resolution === "1080p") filters.push("scale=-2:1080");
    else if (settings.resolution === "720p") filters.push("scale=-2:720");
    else if (settings.resolution === "480p") filters.push("scale=-2:480");
    else if (settings.resolution === "custom" && settings.scaleWidth && settings.scaleHeight)
      filters.push(`scale=${settings.scaleWidth}:${settings.scaleHeight}`);

    if (settings.deinterlace) filters.push("yadif=1");
    if (settings.denoise) filters.push("hqdn3d=3:3:6:6");
    if (settings.rotate === "90cw") filters.push("transpose=1");
    if (settings.rotate === "90ccw") filters.push("transpose=2");
    if (settings.rotate === "180") filters.push("transpose=2,transpose=2");
    if (settings.speed && Number(settings.speed) !== 1) filters.push(`setpts=${(1 / Number(settings.speed)).toFixed(3)}*PTS`);
    // Only add eq filter when values differ from defaults
    const br = Number(settings.brightness ?? 0);
    const ct = Number(settings.contrast ?? 1);
    const sat = Number(settings.saturation ?? 1);
    if (br !== 0 || ct !== 1 || sat !== 1) {
      filters.push(`eq=brightness=${br}:contrast=${ct}:saturation=${sat}`);
    }
    if (settings.subtitleBurn && subtitleExists) {
      const subPath = subtitlePath.replace(/\\/g, "\\\\").replace(/:/g, "\\:");
      filters.push(`subtitles='${subPath}'`);
    }
  }

  if (filters.length) args.push("-vf", filters.join(","));

  if (!isAudioOnly && settings.frameRate !== "original") args.push("-r", String(settings.frameRate));

  if (!isAudioOnly) {
    args.push("-pix_fmt", "yuv420p");

    const fps = settings.frameRate !== "original" ? Number(settings.frameRate) : 30;
    args.push("-g", String(Math.max(60, Math.round(fps * 2))));

    // -sc_threshold only works for h264/h265, not SVT-AV1
    if (settings.codec !== "av1" && settings.sceneChange !== undefined && settings.sceneChange !== null) {
      const sc = Math.max(0, Math.min(100, Number(settings.sceneChange)));
      args.push("-sc_threshold", String(sc));
    }
  }

  if (settings.stripSubtitles && !subtitleExists) args.push("-sn");
  if (settings.stripMetadata) args.push("-map_metadata", "-1");

  if (isAudioOnly) {
    args.push("-vn"); // No video
  } else if (sameAsOriginalVideo && !cropEnabled) {
    args.push("-c:v", "copy");
  } else {
    if (settings.codec === "av1") {
      args.push("-c:v", "libsvtav1", "-preset", String(settings.preset ?? 5));
      if (settings.mode === "crf-1pass") args.push("-crf", String(settings.crf ?? 40));
      else args.push("-b:v", `${settings.videoBitrateKbps || 800}k`);

      const svtParams = [
        "tune=1",
        `aq-mode=${settings.aqMode !== undefined ? settings.aqMode : 0}`,
        "enable-tf=0",
        "enable-overlays=0",
        "film-grain=0",
        "fast-decode=1",
        "scd=1",
      ];
      const tilesValue = String(settings.tiles ?? "0");
      if (tilesValue === "2x2" || tilesValue === "2") svtParams.push("tile-columns=1", "tile-rows=1");
      else if (tilesValue === "4") svtParams.push("tile-columns=2", "tile-rows=2");
      args.push("-svtav1-params", svtParams.join(":"));
    }

    if (settings.codec === "h265") {
      const h265Preset = settings.h26xPreset || "medium";
      args.push("-c:v", "libx265", "-preset", h265Preset);
      if (settings.mode === "crf-1pass") args.push("-crf", String(settings.crf ?? 28));
      else args.push("-b:v", `${settings.videoBitrateKbps || 1800}k`);
      args.push("-x265-params", "psy-rd=1.0:psy-rdoq=1.0:b-adapt=2");
    }

    if (settings.codec === "h264") {
      const h264Preset = settings.h26xPreset || "medium";
      args.push("-c:v", "libx264", "-preset", h264Preset);
      if (settings.mode === "crf-1pass") args.push("-crf", String(settings.crf ?? 23));
      else args.push("-b:v", `${settings.videoBitrateKbps || 2200}k`);
      args.push("-tune", "film");
    }
  }

  // Audio speed filter (atempo) when speed is changed β€” must match video setpts
  const speedVal = Number(settings.speed || 1);
  if (speedVal !== 1 && speedVal > 0 && !isAudioOnly) {
    // atempo only accepts values between 0.5 and 100.0, chain for extreme values
    const audioFilters = [];
    let remaining = speedVal;
    while (remaining > 2.0) { audioFilters.push("atempo=2.0"); remaining /= 2.0; }
    while (remaining < 0.5) { audioFilters.push("atempo=0.5"); remaining /= 0.5; }
    audioFilters.push(`atempo=${remaining.toFixed(4)}`);
    args.push("-filter:a", audioFilters.join(","));
  }

  if (!sameAsOriginalAudio) {
    args.push("-c:a", "libopus", "-b:a", `${settings.audioBitrateKbps || 72}k`,
      "-vbr", "on", "-compression_level", "10", "-application", "audio");
    if (settings.forceStereo || settings.audioChannels === "stereo") args.push("-ac", "2");
    if (settings.audioChannels === "mono") args.push("-ac", "1");
  } else {
    args.push("-c:a", "copy"); // Copy original audio
  }

  if (subtitleExists && !settings.subtitleBurn && !isAudioOnly) {
    // Map video, audio from first input, then subtitle from second input
    args.push("-map", "0:v:0", "-map", "0:a:0", "-map", "1:0");
    args.push("-c:s", "copy");
    if (settings.subtitleLang) {
      args.push("-metadata:s:s:0", `language=${settings.subtitleLang}`);
    }
  } else if (isAudioOnly) {
    args.push("-map", "0:a:0"); // Only audio
  }

  const ext = path.extname(outputPath).toLowerCase();
  if (ext === ".mp4" || ext === ".m4v") {
    args.push("-strict", "experimental", "-movflags", "+faststart");
  }

  if (ext === ".webm") {
    // WebM container: enforce compatible audio codec
    args.push("-c:a", "libopus");
  }

  args.push(outputPath);
  return args;
}

// ── API Routes ─────────────────────────────────────────────────────────────────

app.get("/api/health", (_req, res) => res.json({ ok: true }));

app.get("/api/files", async (_req, res) => {
  try {
    const downloaded = await listFilesRecursive(DOWNLOADS_DIR, "downloaded");
    const encoded = await listFilesRecursive(ENCODED_DIR, "encoded");
    const folders = await listFoldersRecursive(DOWNLOADS_DIR);
    res.json({ downloaded, encoded, folders });
  } catch (err) {
    res.status(500).json({ error: err.message || "Failed to list files" });
  }
});

/**

 * Upload endpoint.

 * Each file may have a corresponding folderPath_N field (relative path like "MyFolder/SubFolder").

 * Files are saved into DOWNLOADS_DIR/<folderPath>/<filename>.

 */
app.post("/api/files/upload", upload.array("files"), async (req, res) => {
  const files = Array.isArray(req.files) ? req.files : [];
  if (files.length === 0) return res.status(400).json({ error: "No files uploaded" });
  try {
    const uploaded = [];
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const rawName = fixUtf8(file.originalname) || "upload.bin";
      const safeName = path.basename(rawName);

      // Folder path sent by client (e.g. "MyShow/Season1" or "")
      const rawFolder = String(req.body?.[`folderPath_${i}`] || "").trim();
      const folderPath = sanitizeFolderPath(rawFolder); // "/" or "MyShow/Season1"

      let targetDir = DOWNLOADS_DIR;
      if (folderPath && folderPath !== "/") {
        targetDir = path.join(DOWNLOADS_DIR, folderPath);
        await fsp.mkdir(targetDir, { recursive: true });
      }

      const { name, fullPath } = getUniqueFilePath(targetDir, safeName);

      // relative path for the id
      const relPath = folderPath && folderPath !== "/"
        ? `${folderPath.replace(/^\//, "")}/${name}`
        : name;

      await fsp.writeFile(fullPath, file.buffer);
      uploaded.push({ name, relPath, folder: folderPath || "/" });
    }
    return res.json({ ok: true, uploaded });
  } catch (err) {
    return res.status(500).json({ error: err.message || "Failed to upload files" });
  }
});

app.get("/api/files/:id/download", async (req, res) => {
  try {
    let fileId;
    try { fileId = decodeURIComponent(String(req.params.id || "")); }
    catch { return res.status(400).json({ error: "Invalid file id encoding" }); }

    const info = resolveFileFromId(fileId);
    if (!info) return res.status(400).json({ error: "Invalid file id" });
    try {
      await fsp.access(info.filePath);
      return res.download(info.filePath, info.name);
    } catch {
      return res.status(404).json({ error: "File not found" });
    }
  } catch (err) {
    console.error("[download] unexpected error:", err.message, err.stack);
    if (!res.headersSent) res.status(500).json({ error: err.message || "Download failed" });
  }
});

// Video/audio streaming endpoint with Range request support (required for browser playback)
app.get("/api/files/:id/stream", async (req, res) => {
  try {
    let fileId;
    try { fileId = decodeURIComponent(String(req.params.id || "")); }
    catch { return res.status(400).json({ error: "Invalid file id encoding" }); }

    const info = resolveFileFromId(fileId);
    if (!info) return res.status(400).json({ error: "Invalid file id" });

    let stat;
    try {
      stat = await fsp.stat(info.filePath);
    } catch {
      return res.status(404).json({ error: "File not found" });
    }

    const ext = path.extname(info.name).toLowerCase();
    const mimeMap = {
      ".mp4": "video/mp4", ".m4v": "video/mp4", ".webm": "video/webm",
      ".mkv": "video/x-matroska", ".mov": "video/quicktime", ".avi": "video/x-msvideo",
      ".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".aac": "audio/aac",
      ".ogg": "audio/ogg", ".wav": "audio/wav", ".flac": "audio/flac",
    };
    const contentType = mimeMap[ext] || "application/octet-stream";
    const fileSize = stat.size;
    const rangeHeader = req.headers.range;

    // For bucket-mounted storage, use larger chunks (50 MB) to reduce requests
    // This helps with seeking performance on network-mounted buckets
    const MAX_CHUNK = 50 * 1024 * 1024; // 50 MB

    let start = 0;
    let end = Math.min(fileSize - 1, MAX_CHUNK - 1);

    if (rangeHeader) {
      const parts = rangeHeader.replace(/bytes=/, "").split("-");
      const reqStart = parseInt(parts[0], 10);
      // If client specifies an end, honour it; otherwise cap at MAX_CHUNK from start
      const reqEnd = parts[1] ? parseInt(parts[1], 10) : reqStart + MAX_CHUNK - 1;
      start = reqStart;
      end = Math.min(reqEnd, fileSize - 1);
      if (isNaN(start) || isNaN(end) || start >= fileSize || start > end) {
        return res.status(416).set("Content-Range", `bytes */${fileSize}`).end();
      }
    }

    const chunkSize = end - start + 1;
    res.status(206)
      .set("Content-Range", `bytes ${start}-${end}/${fileSize}`)
      .set("Accept-Ranges", "bytes")
      .set("Content-Length", String(chunkSize))
      .set("Content-Type", contentType)
      .set("Cache-Control", "public, max-age=604800, immutable")
      .set("Connection", "keep-alive")
      .set("Keep-Alive", "timeout=60, max=100");

    const readStream = fs.createReadStream(info.filePath, {
      start,
      end,
      highWaterMark: 256 * 1024 // 256 KB buffer for better bucket performance
    });
    
    // Longer timeout for bucket-mounted files (network I/O slower than local)
    // 120 seconds to allow bucket operations to complete
    const streamTimeout = setTimeout(() => {
      readStream.destroy();
      console.warn("[stream] timeout on", info.filePath, `range: ${start}-${end}`);
      if (!res.headersSent) res.status(504).json({ error: "Stream timeout - bucket response too slow" });
      else res.destroy();
    }, 120000); // 120 second timeout for bucket
    
    readStream.on("error", (err) => {
      clearTimeout(streamTimeout);
      console.error("[stream] read error:", err.message, "file:", info.filePath);
      if (!res.headersSent) res.status(500).json({ error: "Stream read failed" });
      else res.destroy();
    });
    
    readStream.on("end", () => clearTimeout(streamTimeout));
    readStream.pipe(res);
  } catch (err) {
    console.error("[stream] unexpected error:", err.message, err.stack);
    if (!res.headersSent) res.status(500).json({ error: err.message || "Stream failed" });
  }
});

app.post("/api/files/:id/rename", async (req, res) => {
  const info = resolveFileFromId(decodeURIComponent(String(req.params.id || "")));
  const requestedName = String(req.body?.newName || "").trim();
  if (!info) return res.status(400).json({ error: "Invalid file id" });
  if (!requestedName) return res.status(400).json({ error: "newName is required" });

  const fileDir = path.dirname(info.filePath);
  const oldParsed = path.parse(info.name);
  const reqParsed = path.parse(requestedName);
  const withExt = reqParsed.ext ? requestedName : `${requestedName}${oldParsed.ext || ""}`;
  const { name: nextName, fullPath: nextPath } = getUniqueFilePath(fileDir, withExt);

  try {
    await fsp.access(info.filePath);
    if (nextPath !== info.filePath) await fsp.rename(info.filePath, nextPath);
    // Rebuild id with same folder prefix
    const folderPrefix = info.folder !== "/" ? info.folder.replace(/^\//, "") + "/" : "";
    const newId = `${info.source}:${folderPrefix}${nextName}`;
    return res.json({ ok: true, id: newId, name: nextName });
  } catch {
    return res.status(404).json({ error: "File not found" });
  }
});

app.delete("/api/files/:id", async (req, res) => {
  const info = resolveFileFromId(decodeURIComponent(String(req.params.id || "")));
  if (!info) return res.status(400).json({ error: "Invalid file id" });
  try {
    await fsp.unlink(info.filePath);
    return res.json({ ok: true });
  } catch {
    return res.status(404).json({ error: "File not found" });
  }
});

app.delete("/api/files", async (_req, res) => {
  for (const dir of [DOWNLOADS_DIR, ENCODED_DIR]) {
    const entries = await fsp.readdir(dir, { withFileTypes: true });
    await Promise.all(
      entries.map((e) => {
        const fullPath = path.join(dir, e.name);
        if (e.isDirectory()) return fsp.rm(fullPath, { recursive: true, force: true });
        return fsp.unlink(fullPath);
      })
    );
  }
  return res.json({ ok: true });
});

// ── URL Download with progress tracking ────────────────────────────────────────
/** Convert a size string from aria2c output (e.g. "258MiB", "2.4GiB") to bytes */
function parseAriaSize(str) {
  if (!str) return 0;
  const m = str.trim().match(/^([\d.]+)\s*(GiB|MiB|KiB|GB|MB|KB|B)?$/i);
  if (!m) return 0;
  const n = parseFloat(m[1]);
  switch ((m[2] || "B").toUpperCase()) {
    case "GIB": return n * 1024 ** 3;
    case "MIB": return n * 1024 ** 2;
    case "KIB": return n * 1024;
    case "GB":  return n * 1e9;
    case "MB":  return n * 1e6;
    case "KB":  return n * 1e3;
    default:    return n;
  }
}

app.post("/api/download-url", async (req, res) => {
  const { url, username, password, useAria2 } = req.body || {};
  if (!url || typeof url !== "string") return res.status(400).json({ error: "url is required" });

  let cleanUrl = url;
  let finalUsername = username;
  let finalPassword = password;

  try {
    const parsed = new URL(url);
    if (parsed.username || parsed.password) {
      finalUsername = finalUsername || decodeURIComponent(parsed.username);
      finalPassword = finalPassword || decodeURIComponent(parsed.password);
      parsed.username = "";
      parsed.password = "";
      cleanUrl = parsed.toString();
    }
  } catch {
    // ignore invalid URL parsing and use original input
  }

  const dlJobId = randomId("dl");
  const dlJob = {
    id: dlJobId,
    createdAt: Date.now(),
    status: "running",
    url: cleanUrl,
    filename: null,
    bytesDownloaded: 0,
    totalBytes: 0,
    speedBytesPerSec: 0,
    useAria2: !!useAria2,
    error: null,
    abortController: new AbortController(),
    _process: null,
  };
  downloadJobs.set(dlJobId, dlJob);
  res.json({ ok: true, jobId: dlJobId });

  // ── Fast path: aria2c direct (16 parallel connections) ────────────────────
  if (useAria2) {
    (async () => {
      try {
        // 1. HEAD the URL to learn filename + size (best-effort)
        const headHeaders = {};
        if (finalUsername && finalPassword) {
          headHeaders.Authorization = `Basic ${Buffer.from(`${finalUsername}:${finalPassword}`).toString("base64")}`;
        }
        let guessedName = null;
        let guessedSize = 0;
        try {
          const head = await fetch(cleanUrl, { method: "HEAD", headers: headHeaders, signal: AbortSignal.timeout(8000) });
          guessedSize = Number(head.headers.get("content-length") || 0);
          guessedName = getFilenameFromHeaders(head, cleanUrl);
        } catch { /* ignore; aria2c will still download */ }

        const { name: filename, fullPath: destPath } = getUniqueFilePath(DOWNLOADS_DIR, guessedName || "download");
        dlJob.filename = filename;
        if (guessedSize > 0) dlJob.totalBytes = guessedSize;

        // 2. Spawn aria2c
        const ariaArgs = [
          `-x`, `16`,
          `-s`, `16`,
          `-k`, `1M`,
          `--file-allocation=none`,
          `--auto-file-renaming=false`,
          `--console-log-level=error`,  // suppress NOTICE noise; we poll the file
          `-d`, DOWNLOADS_DIR,
          `-o`, filename,
          cleanUrl,
        ];
        if (finalUsername && finalPassword) {
          ariaArgs.push(`--http-user=${finalUsername}`, `--http-passwd=${finalPassword}`);
        }

        const aria = spawn("aria2c", ariaArgs, { stdio: ["pipe", "pipe", "pipe"] });
        dlJob._process = aria;

        // 3. Track progress by polling the destination file size every second.
        //    aria2c writes directly to destPath while downloading, so stat() works.
        let lastPollBytes = 0;
        const sizePoller = setInterval(() => {
          if (dlJob.status !== "running") { clearInterval(sizePoller); return; }
          try {
            const st = fs.statSync(destPath);
            const now = st.size;
            dlJob.speedBytesPerSec = Math.max(0, now - lastPollBytes);
            lastPollBytes = now;
            dlJob.bytesDownloaded = now;
          } catch { /* file not created yet */ }
        }, 1000);

        // 4. Collect stderr for error messages (strip ANSI codes)
        const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
        let errBuf = "";
        const stderrLines = [];
        aria.stderr.on("data", (chunk) => {
          errBuf += chunk.toString();
          const parts = errBuf.split(/[\r\n]+/); errBuf = parts.pop();
          for (const raw of parts) {
            const line = stripAnsi(raw).trim();
            if (line) stderrLines.push(line);
          }
        });
        // stdout is minimal with --console-log-level=error; drain it anyway
        aria.stdout.on("data", () => {});

        aria.on("error", (err) => {
          clearInterval(sizePoller);
          dlJob._process = null;
          dlJob.status = "failed";
          dlJob.error = `Failed to launch aria2c: ${err.message}`;
        });

        aria.on("close", (code) => {
          clearInterval(sizePoller);
          dlJob._process = null;
          if (dlJob.status === "stopped") return;
          if (code === 0) {
            dlJob.status = "done";
            // Final size from disk
            try { dlJob.bytesDownloaded = fs.statSync(destPath).size; } catch {}
            if (dlJob.totalBytes === 0) dlJob.totalBytes = dlJob.bytesDownloaded;
            dlJob.speedBytesPerSec = 0;
          } else {
            dlJob.status = "failed";
            // Surface first meaningful error line from stderr
            const errLine = stderrLines.find((l) => /error|exception|fail/i.test(l));
            dlJob.error = errLine || `aria2c exited with code ${code}`;
          }
        });
      } catch (err) {
        dlJob.status = "failed";
        dlJob.error = err.message || "Fast download failed";
      }
    })();
    return;
  }

  // ── Standard path: single-connection Node fetch ────────────────────────────
  const headers = {};
  if (finalUsername && finalPassword) {
    headers.Authorization = `Basic ${Buffer.from(`${finalUsername}:${finalPassword}`).toString("base64")}`;
  }

  (async () => {
    let lastBytes = 0, lastTime = Date.now();
    try {
      const response = await fetch(cleanUrl, { headers, signal: dlJob.abortController.signal });
      if (!response.ok || !response.body) {
        dlJob.status = "failed";
        dlJob.error = `Server returned ${response.status} for ${cleanUrl}`;
        return;
      }
      const contentLength = response.headers.get("content-length");
      dlJob.totalBytes = contentLength ? Number(contentLength) : 0;
      const requestedName = getFilenameFromHeaders(response, url);
      const { name: filename, fullPath: destPath } = getUniqueFilePath(DOWNLOADS_DIR, requestedName);
      dlJob.filename = filename;
      const fileStream = fs.createWriteStream(destPath);
      const nodeReadable = Readable.fromWeb(response.body);
      nodeReadable.on("data", (chunk) => {
        dlJob.bytesDownloaded += chunk.length;
        const now = Date.now();
        const elapsed = (now - lastTime) / 1000;
        if (elapsed >= 0.5) {
          dlJob.speedBytesPerSec = (dlJob.bytesDownloaded - lastBytes) / elapsed;
          lastBytes = dlJob.bytesDownloaded;
          lastTime = now;
        }
      });
      await new Promise((resolve, reject) => {
        nodeReadable.on("error", reject);
        fileStream.on("error", reject);
        fileStream.on("finish", resolve);
        nodeReadable.pipe(fileStream);
      });
      dlJob.status = "done";
      dlJob.speedBytesPerSec = 0;
    } catch (err) {
      if (err.name === "AbortError") dlJob.status = "stopped";
      else { dlJob.status = "failed"; dlJob.error = err.message || "Download failed"; }
    }
  })();
});

app.get("/api/download-jobs/:id", (req, res) => {
  const dlJob = downloadJobs.get(req.params.id);
  if (!dlJob) return res.status(404).json({ error: "Download job not found" });
  const { abortController: _ac, _process: _p, ...safe } = dlJob;
  return res.json({ job: safe });
});

app.post("/api/download-jobs/:id/stop", (req, res) => {
  const dlJob = downloadJobs.get(req.params.id);
  if (!dlJob) return res.status(404).json({ error: "Download job not found" });
  if (dlJob.status === "running") {
    dlJob.status = "stopped";
    if (dlJob._process) { try { dlJob._process.kill("SIGTERM"); } catch {} dlJob._process = null; }
    else if (dlJob.abortController) { dlJob.abortController.abort(); }
  }
  return res.json({ ok: true });
});

// ── Encode ─────────────────────────────────────────────────────────────────────
app.post("/api/encode", async (req, res) => {
  const settings = req.body || {};
  if (!settings.inputFilename || !settings.outputFilename) {
    return res.status(400).json({ error: "inputFilename and outputFilename are required" });
  }

  // Resolve input: prefer fileId (works for both downloaded + encoded), fall back to DOWNLOADS_DIR
  let inputPath;
  if (settings.fileId) {
    const info = resolveFileFromId(String(settings.fileId));
    if (!info) return res.status(400).json({ error: "Invalid fileId" });
    inputPath = info.filePath;
  } else {
    const rawInput = String(settings.inputFilename || "");
    inputPath = path.resolve(DOWNLOADS_DIR, rawInput);
    if (!inputPath.startsWith(DOWNLOADS_DIR + path.sep) && inputPath !== DOWNLOADS_DIR) {
      return res.status(400).json({ error: "Invalid input path" });
    }
  }
  const tempOutputPath = path.join(ENCODED_DIR, path.basename(settings.outputFilename));

  try { await fsp.access(inputPath); } catch {
    return res.status(404).json({ error: "Input file not found" });
  }

  const jobId = randomId("enc");
  const durationSeconds = await getDurationSeconds(inputPath);
  const job = {
    id: jobId,
    createdAt: Date.now(),
    startedAt: Date.now(),
    status: "running",
    settings,
    batchIndex: settings.batchIndex !== undefined ? Number(settings.batchIndex) : null,
    batchTotal: settings.batchTotal !== undefined ? Number(settings.batchTotal) : null,
    outputFolder: "/",
    outputSource: "encoded",
    _process: null,
    progress: { percent: 0, fps: 0, etaSeconds: durationSeconds, speed: 0, bitrateKbps: 0, sizeOutBytes: 0, log: ["Starting ffmpeg encode..."] },
  };
  jobs.set(jobId, job);

  const args = buildEncodeArgs(settings, inputPath, tempOutputPath);
  job.progress.log.push(`ffmpeg ${args.map((a) => String(a)).join(" ")}`);
  const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });
  job._process = ffmpeg;

  ffmpeg.stderr.on("data", async (chunk) => {
    const line = chunk.toString();
    const latest = jobs.get(jobId);
    if (!latest) return;
    latest.progress.log.push(line.trim());
    if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500);
    const timeMatch = line.match(/time=([0-9:.]+)/);
    if (timeMatch) {
      const seconds = parseFfmpegTimeToSeconds(timeMatch[1]);
      if (durationSeconds > 0) {
        latest.progress.percent = Math.min(99.5, (seconds / durationSeconds) * 100);
        // Calculate actual encoding speed and accurate ETA
        const elapsedMs = Date.now() - latest.startedAt;
        const elapsedSec = elapsedMs / 1000;
        const speed = elapsedSec > 0 ? seconds / elapsedSec : 0;
        latest.progress.speed = speed;
        const remaining = durationSeconds - seconds;
        latest.progress.etaSeconds = speed > 0 ? Math.max(0, remaining / speed) : remaining;
      }
    }
    const fpsMatch = line.match(/fps=\s*([0-9.]+)/);
    if (fpsMatch) latest.progress.fps = Number(fpsMatch[1]) || 0;
    const speedMatch = line.match(/speed=\s*([0-9.]+)x/);
    if (speedMatch) latest.progress.speed = Number(speedMatch[1]) || 0;
    // Parse current bitrate from ffmpeg output (e.g., bitrate= 883.2kbits/s)
    const bitrateMatch = line.match(/bitrate=\s*([0-9.]+)kbits\/s/);
    if (bitrateMatch) latest.progress.bitrateKbps = Number(bitrateMatch[1]) || 0;
    const sizeMatch = line.match(/size=\s*([0-9]+)kB/);
    if (sizeMatch) {
      latest.progress.sizeOutBytes = Number(sizeMatch[1]) * 1024;
    } else {
      try { const st = await fsp.stat(tempOutputPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ }
    }
  });

  ffmpeg.on("error", (err) => {
    const latest = jobs.get(jobId);
    if (!latest) return;
    latest.status = "failed";
    latest.progress.log.push(`Failed to launch ffmpeg: ${err.message}`);
  });

  ffmpeg.on("close", async (code) => {
    const latest = jobs.get(jobId);
    if (!latest) return;
    latest._process = null;
    if (latest.status === "stopped") {
      const stoppedOutputPath = tempOutputPath;
      const resolution = await getVideoResolution(stoppedOutputPath);
      const parsedOutput = path.parse(stoppedOutputPath);
      const cleanedBase = parsedOutput.name
        .replace(/_encoded(?:_\d+x\d+)?$/i, "");
      const desiredName = `${cleanedBase}_stopped_${resolution}${parsedOutput.ext}`;
      const { name: finalName, fullPath: finalPath } = getUniqueFilePath(ENCODED_DIR, desiredName);
      let actualPath = stoppedOutputPath;
      try {
        await fsp.access(stoppedOutputPath);
        await safeMoveFile(stoppedOutputPath, finalPath);
        actualPath = finalPath;
      } catch {
        // keep original path if rename/access fails
      }
      latest.outputFolder = "/";
      latest.outputSource = "encoded";
      try {
        const st = await fsp.stat(actualPath);
        latest.progress.sizeOutBytes = st.size;
      } catch {
        /* ignore */
      }
      latest.outputFilename = path.basename(actualPath);
      latest.progress.log.push(`Encode stopped. Partial output kept: ${path.basename(actualPath)}`);
      persistJobHistory();
      return;
    }
    if (code === 0) {
      const resolution = await getVideoResolution(tempOutputPath);
      const parsedOutput = path.parse(tempOutputPath);
      const cleanedBase = parsedOutput.name
        .replace(/_encoded(?:_\d+x\d+)?$/i, "");
      const desiredName = `${cleanedBase}_encoded_${resolution}${parsedOutput.ext}`;
      const { name: finalName, fullPath: finalPath } = getUniqueFilePath(ENCODED_DIR, desiredName);
      try { await safeMoveFile(tempOutputPath, finalPath); } catch {
        latest.progress.log.push(`Warning: could not rename to ${finalName}`);
      }
      const actualPath = fs.existsSync(finalPath) ? finalPath : tempOutputPath;
      latest.status = "done";
      latest.outputFolder = "/";
      latest.outputSource = "encoded";
      latest.outputFilename = path.basename(actualPath);
      latest.progress.percent = 100;
      latest.progress.etaSeconds = 0;
      try { const st = await fsp.stat(actualPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ }
      latest.progress.log.push(`Encode completed. Output: ${path.basename(actualPath)}`);

      // Persist encoding settings sidecar for later display
      try {
        const settingsPath = `${actualPath}.settings.json`;
        await fsp.writeFile(settingsPath, JSON.stringify({
          createdAt: Date.now(),
          inputFilename: settings.inputFilename,
          outputFilename: path.basename(actualPath),
          resolution,
          settings,
        }, null, 2), "utf8");
      } catch {
        // ignore sidecar failures
      }
      persistJobHistory();
    } else {
      latest.status = "failed";
      latest.progress.log.push(`ffmpeg exited with code ${code}`);
      persistJobHistory();
    }
  });

  const { _process: _p, ...safeJob } = job;
  return res.json({ job: safeJob });
});

// ── Stop an encode/trim/merge job ──────────────────────────────────────────────
app.post("/api/jobs/:id/stop", (req, res) => {
  const job = jobs.get(req.params.id);
  if (!job) return res.status(404).json({ error: "Job not found" });
  if (job.status !== "running") return res.json({ ok: true, note: "Job not running" });
  stopFfmpegProcess(job);
  return res.json({ ok: true });
});

app.get("/api/jobs", (_req, res) => {
  const allJobs = [...jobs.values()]
    .sort((a, b) => b.createdAt - a.createdAt)
    .map(({ _process: _p, ...j }) => j);
  res.json({ jobs: allJobs });
});

app.get("/api/jobs/:id", (req, res) => {
  const job = jobs.get(req.params.id);
  if (!job) return res.status(404).json({ error: "Job not found" });
  const { _process: _p, ...safeJob } = job;
  return res.json({ job: safeJob });
});

app.delete("/api/jobs/finished", async (_req, res) => {
  for (const [id, job] of jobs.entries()) {
    if (job.status !== "running") jobs.delete(id);
  }
  await persistJobHistory();
  return res.json({ ok: true });
});

// ── File Info ──────────────────────────────────────────────────────────────────
app.get("/api/files/:id/info", async (req, res) => {
  const info = resolveFileFromId(decodeURIComponent(String(req.params.id || "")));
  if (!info) return res.status(400).json({ error: "Invalid file id" });
  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }
  try {
    const { stdout } = await runProcess("ffprobe", [
      "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", info.filePath,
    ]);
    const probe = JSON.parse(stdout);
    const fmt = probe.format || {};
    const streams = probe.streams || [];
    const videoStream = streams.find((s) => s.codec_type === "video");
    const audioStreams = streams.filter((s) => s.codec_type === "audio");
    const subtitleStreams = streams.filter((s) => s.codec_type === "subtitle");
    const audioStream = audioStreams[0];

    const durationSec = parseFloat(fmt.duration || videoStream?.duration || 0);
    const h = Math.floor(durationSec / 3600);
    const m = Math.floor((durationSec % 3600) / 60);
    const s = Math.floor(durationSec % 60);
    const durationStr = h > 0
      ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`
      : `${m}:${String(s).padStart(2, "0")}`;

    const st = await fsp.stat(info.filePath);
    const totalBitrate = parseInt(fmt.bit_rate || 0);
    const audioBitrate = parseInt(audioStream?.bit_rate || 0);
    const videoBitrate = parseInt(videoStream?.bit_rate || 0) || (totalBitrate - audioBitrate) || 0;
    const videoStreamSize = durationSec > 0 && videoBitrate > 0 ? Math.round((videoBitrate / 8) * durationSec) : null;
    const audioStreamSize = durationSec > 0 && audioBitrate > 0 ? Math.round((audioBitrate / 8) * durationSec) : null;

    function fmtBytes(b) {
      if (!b) return "unknown";
      if (b < 1024) return `${b} B`;
      if (b < 1024 ** 2) return `${(b / 1024).toFixed(1)} KB`;
      if (b < 1024 ** 3) return `${(b / 1024 ** 2).toFixed(2)} MB`;
      return `${(b / 1024 ** 3).toFixed(2)} GB`;
    }
    function fmtBitrate(bps) {
      if (!bps) return "unknown";
      if (bps >= 1_000_000) return `${(bps / 1_000_000).toFixed(2)} Mbps`;
      return `${(bps / 1000).toFixed(0)} kbps`;
    }

    let frameRate = "unknown";
    if (videoStream?.r_frame_rate) {
      const [num, den] = videoStream.r_frame_rate.split("/").map(Number);
      if (den && den !== 0) frameRate = (num / den).toFixed(3).replace(/\.?0+$/, "") + " fps";
    }

    let encodeSettings = null;
    if (info.source === "encoded") {
      try {
        const settingsPath = `${info.filePath}.settings.json`;
        const raw = await fsp.readFile(settingsPath, "utf8");
        encodeSettings = JSON.parse(raw);
      } catch {
        encodeSettings = null;
      }
    }

    // Load saved crop settings from .crop.json sidecar (created by trim-segments)
    let savedCropSettings = null;
    try {
      const cropSettingsPath = `${info.filePath}.crop.json`;
      const cropRaw = await fsp.readFile(cropSettingsPath, "utf8");
      savedCropSettings = JSON.parse(cropRaw);
    } catch {
      savedCropSettings = null;
    }

    return res.json({
      ok: true,
      info: {
        fileSize: fmtBytes(st.size),
        fileSizeBytes: st.size,
        duration: durationStr,
        durationSeconds: durationSec,
        video: videoStream ? {
          codec: videoStream.codec_name || "unknown",
          profile: videoStream.profile || null,
          resolution: `${videoStream.width}x${videoStream.height}`,
          width: videoStream.width,
          height: videoStream.height,
          frameRate,
          bitrate: fmtBitrate(videoBitrate),
          bitrateRaw: videoBitrate,
          pixFmt: videoStream.pix_fmt || "unknown",
          streamSize: videoStreamSize ? fmtBytes(videoStreamSize) : "unknown",
        } : null,
        audio: audioStream ? {
          codec: audioStream.codec_name || "unknown",
          sampleRate: audioStream.sample_rate ? `${audioStream.sample_rate} Hz` : "unknown",
          channels: audioStream.channels || "unknown",
          channelLayout: audioStream.channel_layout || "unknown",
          bitrate: fmtBitrate(parseInt(audioStream.bit_rate || 0)),
          bitrateRaw: parseInt(audioStream.bit_rate || 0),
          streamSize: audioStreamSize ? fmtBytes(audioStreamSize) : "unknown",
        } : null,
        audioStreams: audioStreams.map((stream) => {
          const streamBitrate = parseInt(stream.bit_rate || 0);
          const streamSize = durationSec > 0 && streamBitrate > 0
            ? Math.round((streamBitrate / 8) * durationSec)
            : null;

          return {
            index: typeof stream.index === "number" ? stream.index : -1,
            codec: stream.codec_name || "unknown",
            sampleRate: stream.sample_rate ? `${stream.sample_rate} Hz` : "unknown",
            channels: stream.channels || "unknown",
            channelLayout: stream.channel_layout || "unknown",
            bitrate: fmtBitrate(streamBitrate),
            bitrateRaw: streamBitrate,
            streamSize: streamSize ? fmtBytes(streamSize) : "unknown",
            language: stream.tags?.language || "unknown",
            title: stream.tags?.title || "",
          };
        }),
        subtitleStreams: subtitleStreams.map((stream) => ({
          index: typeof stream.index === "number" ? stream.index : -1,
          codec: stream.codec_name || "unknown",
          language: stream.tags?.language || "unknown",
          title: stream.tags?.title || "",
          forced: Boolean(stream.disposition?.forced),
          default: Boolean(stream.disposition?.default),
        })),
        encodeSettings,
        savedCropSettings,
      },
    });
  } catch (err) {
    return res.status(500).json({ error: err.message || "ffprobe failed" });
  }
});

// ── Trim ───────────────────────────────────────────────────────────────────────
app.post("/api/trim", async (req, res) => {
  const { fileId, startTime, endTime, outputFilename, segments } = req.body || {};
  if (!fileId || !outputFilename) {
    return res.status(400).json({ error: "fileId and outputFilename are required" });
  }

  const info = resolveFileFromId(String(fileId));
  if (!info) return res.status(400).json({ error: "Invalid file id" });
  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }

  const normalizedSegments = Array.isArray(segments)
    ? segments.map((item) => ({ startTime: Number(item?.startTime), endTime: Number(item?.endTime) }))
    : [{ startTime: Number(startTime), endTime: Number(endTime) }];

  if (normalizedSegments.length === 0) {
    return res.status(400).json({ error: "At least one trim segment is required" });
  }

  for (const segment of normalizedSegments) {
    if (!Number.isFinite(segment.startTime) || !Number.isFinite(segment.endTime)) {
      return res.status(400).json({ error: "Invalid trim segment times" });
    }
    if (segment.endTime <= segment.startTime) {
      return res.status(400).json({ error: "Each trim segment must have an end time after its start time" });
    }
  }

  // Save trimmed output to the SAME folder as the source file
  const sourceDir = path.dirname(info.filePath);
  const { name: outName, fullPath: outPath } = getUniqueFilePath(sourceDir, String(outputFilename));

  // Compute output folder (relative to DOWNLOADS_DIR or ENCODED_DIR)
  const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR;
  const relOutDir = path.relative(base, sourceDir);
  const outputFolder = relOutDir ? `/${relOutDir}` : "/";

  const totalDuration = normalizedSegments.reduce((sum, segment) => sum + (segment.endTime - segment.startTime), 0);
  const jobId = randomId("trim");
  const job = {
    id: jobId,
    createdAt: Date.now(),
    status: "running",
    _process: null,
    outputFolder,
    outputSource: info.source,
    settings: { inputFilename: info.name, outputFilename: outName, segments: normalizedSegments, type: "trim" },
    progress: { percent: 0, fps: 0, etaSeconds: totalDuration, sizeOutBytes: 0, log: ["Starting trim..."] },
  };
  jobs.set(jobId, job);

  const runFfmpegProcess = (args, previousSeconds = 0) => new Promise((resolve, reject) => {
    const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });
    const update = (chunk) => {
      const line = chunk.toString();
      const latest = jobs.get(jobId);
      if (!latest) return;
      latest.progress.log.push(line.trim());
      if (latest.progress.log.length > 200) latest.progress.log = latest.progress.log.slice(-200);
      const timeMatch = line.match(/time=([0-9:.]+)/);
      if (timeMatch) {
        const secs = parseFfmpegTimeToSeconds(timeMatch[1]);
        if (totalDuration > 0) {
          latest.progress.percent = Math.min(99.5, ((previousSeconds + secs) / totalDuration) * 100);
          latest.progress.etaSeconds = Math.max(0, totalDuration - (previousSeconds + secs));
        }
      }
      const sizeMatch = line.match(/size=\s*([0-9]+)kB/);
      if (sizeMatch) latest.progress.sizeOutBytes = Number(sizeMatch[1]) * 1024;
    };

    ffmpeg.stderr.on("data", update);
    ffmpeg.on("error", (err) => {
      const latest = jobs.get(jobId);
      if (!latest) return;
      latest.status = "failed";
      latest.progress.log.push(`Failed: ${err.message}`);
      reject(err);
    });
    ffmpeg.on("close", (code) => {
      const latest = jobs.get(jobId);
      if (!latest) return resolve(null);
      latest._process = null;
      if (latest.status === "stopped") {
        return resolve(null);
      }
      if (code === 0) {
        resolve(null);
      } else {
        latest.status = "failed";
        latest.progress.log.push(`ffmpeg exited with code ${code}`);
        reject(new Error(`ffmpeg exited with code ${code}`));
      }
    });

    job._process = ffmpeg;
  });

  const runSegment = async (segment, idx, outputPath, previousSeconds = 0) => {
    const args = ["-y", "-ss", String(segment.startTime), "-to", String(segment.endTime), "-i", info.filePath, "-c", "copy", outputPath];
    await runFfmpegProcess(args, previousSeconds);
    return outputPath;
  };

  let tempDir = null;
  let concatListPath = null;
  let segmentFiles = [];

  try {
    if (normalizedSegments.length === 1) {
      const segment = normalizedSegments[0];
      await runSegment(segment, 0, outPath, 0);
      if (job.status === "stopped") {
        try { const st = await fsp.stat(outPath); job.progress.sizeOutBytes = st.size; } catch { /* ignore */ }
        job.progress.log.push(`Trim stopped. Partial output kept: ${outName}`);
        return;
      }
      job.status = "done";
      job.progress.percent = 100;
      job.progress.etaSeconds = 0;
      try { const st = await fsp.stat(outPath); job.progress.sizeOutBytes = st.size; } catch { /* ignore */ }
      job.progress.log.push(`Trim completed. Output: ${outName}`);
    } else {
      tempDir = path.join(os.tmpdir(), `trim-segments-${jobId}`);
      await fsp.mkdir(tempDir, { recursive: true });

      let elapsed = 0;
      for (let idx = 0; idx < normalizedSegments.length; idx += 1) {
        const segment = normalizedSegments[idx];
        const segmentPath = path.join(tempDir, `segment_${idx + 1}${path.extname(info.filePath) || ".mkv"}`);
        job.progress.log.push(`Trimming segment ${idx + 1} of ${normalizedSegments.length}…`);
        await runSegment(segment, idx, segmentPath, elapsed);
        if (job.status === "stopped") break;
        segmentFiles.push(segmentPath);
        elapsed += segment.endTime - segment.startTime;
      }

      if (job.status !== "stopped") {
        job.progress.log.push(`Merging ${segmentFiles.length} segments…`);
        concatListPath = path.join(tempDir, `concat-${jobId}.txt`);
        const concatContent = segmentFiles.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n");

        await fsp.writeFile(concatListPath, concatContent, "utf8");



        await runFfmpegProcess(["-y", "-f", "concat", "-safe", "0", "-i", concatListPath, "-c", "copy", outPath], 0);



        if (job.status !== "stopped") {

          job.status = "done";

          job.progress.percent = 100;

          job.progress.etaSeconds = 0;

          try { const st = await fsp.stat(outPath); job.progress.sizeOutBytes = st.size; } catch { /* ignore */ }

          job.progress.log.push(`Trim completed. Output: ${outName}`);

        }

      }

    }

  } catch (err) {

    const latest = jobs.get(jobId);

    if (latest && latest.status !== "stopped") {

      latest.status = "failed";

      latest.progress.log.push(`Trim failed: ${err.message || err}`);

    }

  } finally {

    if (concatListPath) {

      await fsp.rm(concatListPath, { force: true }).catch(() => {});

    }

    if (segmentFiles.length > 0) {

      await Promise.all(segmentFiles.map((filePath) => fsp.rm(filePath, { force: true }).catch(() => {})));

    }

    if (tempDir) {

      await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});

    }

  }



  const { _process: _p, ...safeJob } = job;

  return res.json({ job: safeJob });

});



// ── Pixeldrain Upload ──────────────────────────────────────────────────────────

const pixeldrainJobs = new Map();



app.post("/api/files/:id/pixeldrain", async (req, res) => {

  const info = resolveFileFromId(decodeURIComponent(String(req.params.id || "")));

  if (!info) return res.status(400).json({ error: "Invalid file id" });

  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }



  const PIXELDRAIN_API_KEY = process.env.PIXELDRAIN_API_KEY || "";

  const pdJobId = randomId("pd");

  const st = await fsp.stat(info.filePath);



  const pdJob = {

    id: pdJobId,

    createdAt: Date.now(),

    status: "running",

    filename: info.name,

    bytesUploaded: 0,

    totalBytes: st.size,

    pixeldrainUrl: null,

    error: null,

  };

  pixeldrainJobs.set(pdJobId, pdJob);

  res.json({ ok: true, jobId: pdJobId });



  (async () => {

    try {

      const fileStream = fs.createReadStream(info.filePath);

      let bytesRead = 0;

      fileStream.on("data", (chunk) => { bytesRead += chunk.length; pdJob.bytesUploaded = bytesRead; });

      const headers = {

        "Content-Type": "application/octet-stream",

        "Content-Length": String(st.size),

      };

      if (PIXELDRAIN_API_KEY) {

        headers["Authorization"] = `Basic ${Buffer.from(`:${PIXELDRAIN_API_KEY}`).toString("base64")}`;

      }

      const url = `https://pixeldrain.com/api/file/${encodeURIComponent(info.name)}`;

      const response = await new Promise((resolve, reject) => {

        const parsedUrl = new URL(url);

        const options = {

          hostname: parsedUrl.hostname,

          path: parsedUrl.pathname + parsedUrl.search,

          method: "PUT",

          headers,

        };

        const req2 = https.request(options, resolve);

        req2.on("error", reject);

        fileStream.pipe(req2);

      });

      let body = "";

      await new Promise((resolve) => {

        response.on("data", (d) => { body += d.toString(); });

        response.on("end", resolve);

      });

      const result = JSON.parse(body);

      if (result.id) {

        pdJob.status = "done";

        pdJob.bytesUploaded = st.size;

        pdJob.pixeldrainUrl = `https://pixeldrain.com/u/${result.id}`;

      } else {

        pdJob.status = "failed";

        pdJob.error = result.message || result.value || "Upload failed";

      }

    } catch (err) {

      pdJob.status = "failed";

      pdJob.error = err.message || "Upload failed";

    }

  })();

});



app.get("/api/pixeldrain-jobs/:id", (req, res) => {

  const job = pixeldrainJobs.get(req.params.id);

  if (!job) return res.status(404).json({ error: "Job not found" });

  return res.json({ job });

});



// ── Merge ──────────────────────────────────────────────────────────────────────

app.post("/api/merge", async (req, res) => {

  const { fileIds, outputFilename } = req.body || {};

  if (!Array.isArray(fileIds) || fileIds.length < 2) {

    return res.status(400).json({ error: "fileIds array with at least 2 files is required" });

  }

  if (!outputFilename) return res.status(400).json({ error: "outputFilename is required" });



  const resolvedFiles = [];

  for (const id of fileIds) {

    const info = resolveFileFromId(String(id));

    if (!info) return res.status(400).json({ error: `Invalid file id: ${id}` });

    try { await fsp.access(info.filePath); } catch {

      return res.status(404).json({ error: `File not found: ${info.name}` });

    }

    resolvedFiles.push(info);

  }



  // Save merged output to same folder as first source file

  const firstInfo = resolvedFiles[0];

  const outputDir = path.dirname(firstInfo.filePath);

  const base = firstInfo.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR;

  const relOutDir = path.relative(base, outputDir);

  const outputFolder = relOutDir ? `/${relOutDir}` : "/";



  const { name: outName, fullPath: outPath } = getUniqueFilePath(outputDir, String(outputFilename));



  const concatListPath = path.join(DOWNLOADS_DIR, `_concat_${Date.now()}.txt`);

  const concatContent = resolvedFiles.map((f) => `file '${f.filePath.replace(/'/g, "'\\''")}'`).join("\n");

  await fsp.writeFile(concatListPath, concatContent, "utf8");



  let totalDuration = 0;

  for (const f of resolvedFiles) totalDuration += await getDurationSeconds(f.filePath);



  const jobId = randomId("merge");

  const job = {

    id: jobId,

    createdAt: Date.now(),

    status: "running",

    _process: null,

    outputFolder,

    outputSource: firstInfo.source,

    settings: {

      type: "merge",

      inputFilenames: resolvedFiles.map((f) => f.name),

      outputFilename: outName,

    },

    batchIndex: null,

    batchTotal: null,

    progress: {

      percent: 0, fps: 0, etaSeconds: totalDuration,

      sizeOutBytes: 0, log: [`Merging ${resolvedFiles.length} files…`],

    },

  };

  jobs.set(jobId, job);



  const args = ["-y", "-f", "concat", "-safe", "0", "-i", concatListPath, "-c", "copy", outPath];

  const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });

  job._process = ffmpeg;



  ffmpeg.stderr.on("data", (chunk) => {

    const line = chunk.toString();

    const latest = jobs.get(jobId);

    if (!latest) return;

    latest.progress.log.push(line.trim());

    if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500);

    const timeMatch = line.match(/time=([0-9:.]+)/);

    if (timeMatch) {

      const secs = parseFfmpegTimeToSeconds(timeMatch[1]);

      if (totalDuration > 0) {

        latest.progress.percent = Math.min(99.5, (secs / totalDuration) * 100);

        latest.progress.etaSeconds = Math.max(0, totalDuration - secs);

      }

    }

    const sizeMatch = line.match(/size=\s*([0-9]+)kB/);

    if (sizeMatch) latest.progress.sizeOutBytes = Number(sizeMatch[1]) * 1024;

  });



  ffmpeg.on("error", (err) => {

    const latest = jobs.get(jobId);

    if (!latest) return;

    latest.status = "failed";

    latest.progress.log.push(`Failed: ${err.message}`);

    fsp.unlink(concatListPath).catch(() => {});

  });



  ffmpeg.on("close", async (code) => {

    const latest = jobs.get(jobId);

    if (!latest) return;

    latest._process = null;

    fsp.unlink(concatListPath).catch(() => {});

    if (latest.status === "stopped") {

      try { const st = await fsp.stat(outPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ }

      latest.progress.log.push(`Merge stopped. Partial output kept: ${outName}`);

      return;

    }

    if (code === 0) {

      latest.status = "done";

      latest.progress.percent = 100;

      latest.progress.etaSeconds = 0;

      try { const st = await fsp.stat(outPath); latest.progress.sizeOutBytes = st.size; } catch { /* ignore */ }

      latest.progress.log.push(`Merge completed. Output: ${outName}`);

    } else {

      latest.status = "failed";

      latest.progress.log.push(`ffmpeg exited with code ${code}`);

    }

  });



  const { _process: _p, ...safeJob } = job;

  return res.json({ job: safeJob });

});



// ── Folder operations ──────────────────────────────────────────────────────────



app.post("/api/folders/create", async (req, res) => {

  const rawName = String(req.body?.folderName || req.body?.name || "").trim();

  const rawParent = String(req.body?.parent || "").trim();

  if (!rawName) return res.status(400).json({ error: "name is required" });

  const safeName = sanitizeSegment(rawName, "folder");

  const safeParent = sanitizeFolderPath(rawParent);

  const parentDir = safeParent && safeParent !== "/"

    ? path.join(DOWNLOADS_DIR, safeParent)

    : DOWNLOADS_DIR;

  const newDir = path.join(parentDir, safeName);

  if (!newDir.startsWith(DOWNLOADS_DIR)) return res.status(400).json({ error: "Invalid path" });

  try {

    await fsp.mkdir(newDir, { recursive: true });

    const relPath = path.relative(DOWNLOADS_DIR, newDir);

    return res.json({ ok: true, folder: `/${relPath}` });

  } catch (err) {

    return res.status(500).json({ error: err.message });

  }

});



app.post("/api/folders/rename", async (req, res) => {

  const rawFolder = String(req.body?.oldPath || req.body?.folder || "").trim();

  const rawNewName = String(req.body?.newName || "").trim();

  if (!rawFolder || rawFolder === "/") return res.status(400).json({ error: "folder is required" });

  if (!rawNewName) return res.status(400).json({ error: "newName is required" });

  const safeFolder = sanitizeFolderPath(rawFolder);

  const oldDir = path.join(DOWNLOADS_DIR, safeFolder);

  if (!oldDir.startsWith(DOWNLOADS_DIR + path.sep)) return res.status(400).json({ error: "Invalid path" });

  const parentDir = path.dirname(oldDir);

  const safeName = sanitizeSegment(rawNewName, "folder");

  const newDir = path.join(parentDir, safeName);

  if (!newDir.startsWith(DOWNLOADS_DIR)) return res.status(400).json({ error: "Invalid path" });

  try {

    await fsp.access(oldDir);

    await fsp.rename(oldDir, newDir);

    const relPath = path.relative(DOWNLOADS_DIR, newDir);

    return res.json({ ok: true, folder: `/${relPath}` });

  } catch (err) {

    return res.status(500).json({ error: err.message });

  }

});



app.delete("/api/folders", async (req, res) => {

  const rawFolder = String(req.body?.folderPath || req.body?.folder || "").trim();

  if (!rawFolder || rawFolder === "/") return res.status(400).json({ error: "folder path is required" });

  const safeFolder = sanitizeFolderPath(rawFolder);

  const dirPath = path.join(DOWNLOADS_DIR, safeFolder);

  if (!dirPath.startsWith(DOWNLOADS_DIR + path.sep)) return res.status(400).json({ error: "Invalid path" });

  try {

    await fsp.rm(dirPath, { recursive: true, force: true });

    return res.json({ ok: true });

  } catch (err) {

    return res.status(500).json({ error: err.message });

  }

});



app.get("/api/folders/zip", async (req, res) => {

  const rawFolder = String(req.query?.folder || "").trim();

  const isRoot = !rawFolder || rawFolder === "/";

  let dirPath, zipFilename;

  if (isRoot) {

    dirPath = DOWNLOADS_DIR;

    zipFilename = "root";

  } else {

    const safeFolder = sanitizeFolderPath(rawFolder);

    dirPath = path.join(DOWNLOADS_DIR, safeFolder);

    if (!dirPath.startsWith(DOWNLOADS_DIR + path.sep)) return res.status(400).json({ error: "Invalid path" });

    zipFilename = path.basename(dirPath);

  }

  try {

    await fsp.access(dirPath);

  } catch {

    return res.status(404).json({ error: "Folder not found" });

  }



  res.setHeader("Content-Type", "application/zip");

  res.setHeader("Content-Disposition", `attachment; filename="${encodeURIComponent(zipFilename)}.zip"`);



  try {

    const archiver = (await import("archiver")).default;

    const archive = archiver("zip", { zlib: { level: 0 } }); // level 0 = store only (fast)

    archive.on("error", (err) => { console.error("zip error", err); res.end(); });

    archive.pipe(res);

    archive.directory(dirPath, zipFilename);

    await archive.finalize();

  } catch (err) {

    console.error("archiver error", err);

    if (!res.headersSent) res.status(500).json({ error: err.message });

  }

});



app.post("/api/folders/upload-zip", upload.any(), async (req, res) => {

  const rawFolder = String(req.body?.folderPath || req.body?.folder || "").trim();

  const files = Array.isArray(req.files) ? req.files : [];

  const uploadedFile = files[0];

  if (!uploadedFile) return res.status(400).json({ error: "No file uploaded" });

  const safeFolder = sanitizeFolderPath(rawFolder);

  const targetDir = safeFolder && safeFolder !== "/"

    ? path.join(DOWNLOADS_DIR, safeFolder)

    : DOWNLOADS_DIR;

  if (!targetDir.startsWith(DOWNLOADS_DIR)) return res.status(400).json({ error: "Invalid path" });



  try {

    await fsp.mkdir(targetDir, { recursive: true });

    const tmpZip = path.join(DOWNLOADS_DIR, `_upload_zip_${Date.now()}.zip`);

    await fsp.writeFile(tmpZip, uploadedFile.buffer);

    const unzipper = (await import("unzipper")).default;

    await new Promise((resolve, reject) => {

      fs.createReadStream(tmpZip)

        .pipe(unzipper.Extract({ path: targetDir }))

        .on("close", resolve)

        .on("error", reject);

    });

    await fsp.unlink(tmpZip).catch(() => {});

    return res.json({ ok: true });

  } catch (err) {

    return res.status(500).json({ error: err.message });

  }

});



app.post("/api/files/:id/move", async (req, res) => {

  const info = resolveFileFromId(decodeURIComponent(String(req.params.id || "")));

  if (!info) return res.status(400).json({ error: "Invalid file id" });

  const rawDest = String(req.body?.targetFolder || req.body?.destFolder || "").trim();

  const safeFolder = sanitizeFolderPath(rawDest);

  const rootDir = info.source === "encoded" ? ENCODED_DIR : DOWNLOADS_DIR;

  const destDir = safeFolder && safeFolder !== "/"

    ? path.join(rootDir, safeFolder)

    : rootDir;

  if (!destDir.startsWith(rootDir)) return res.status(400).json({ error: "Invalid destination" });

  try {

    await fsp.access(info.filePath);

    await fsp.mkdir(destDir, { recursive: true });

    const { name: newName, fullPath: newPath } = getUniqueFilePath(destDir, info.name);

    await fsp.rename(info.filePath, newPath);

    const relPath = path.relative(rootDir, newPath);

    return res.json({ ok: true, id: `${info.source}:${relPath}`, name: newName, folder: safeFolder || "/" });

  } catch (err) {

    return res.status(500).json({ error: err.message });

  }

});



app.post("/api/batch/move", async (req, res) => {

  const ids = Array.isArray(req.body?.ids) ? req.body.ids : [];

  const rawDest = String(req.body?.targetFolder || req.body?.destFolder || "").trim();

  const safeFolder = sanitizeFolderPath(rawDest);

  if (!ids.length) return res.status(400).json({ error: "ids array is required" });



  const results = [];

  for (const id of ids) {

    const info = resolveFileFromId(String(id));

    if (!info) {

      results.push({ id, ok: false, error: "Invalid id" });

      continue;

    }

    const rootDir = info.source === "encoded" ? ENCODED_DIR : DOWNLOADS_DIR;

    const destDir = safeFolder && safeFolder !== "/"

      ? path.join(rootDir, safeFolder)

      : rootDir;

    if (!destDir.startsWith(rootDir)) {

      results.push({ id, ok: false, error: "Invalid destination" });

      continue;

    }

    try {

      await fsp.access(info.filePath);

      await fsp.mkdir(destDir, { recursive: true });

      const { name: newName, fullPath: newPath } = getUniqueFilePath(destDir, info.name);

      await fsp.rename(info.filePath, newPath);

      const relPath = path.relative(rootDir, newPath);

      results.push({ id, ok: true, newId: `${info.source}:${relPath}`, name: newName, folder: safeFolder || "/" });

    } catch (err) {

      results.push({ id, ok: false, error: err.message });

    }

  }



  return res.json({ ok: true, results });

});



// ── Batch operations ───────────────────────────────────────────────────────────

app.post("/api/batch/delete", async (req, res) => {

  const ids = Array.isArray(req.body?.ids) ? req.body.ids : [];

  if (!ids.length) return res.status(400).json({ error: "ids array is required" });

  const results = [];

  for (const id of ids) {

    const info = resolveFileFromId(String(id));

    if (!info) { results.push({ id, ok: false, error: "Invalid id" }); continue; }

    try { await fsp.unlink(info.filePath); results.push({ id, ok: true }); }

    catch { results.push({ id, ok: false, error: "Not found" }); }

  }

  return res.json({ ok: true, results });

});



app.post("/api/batch/pixeldrain", async (req, res) => {

  const ids = Array.isArray(req.body?.ids) ? req.body.ids : [];

  if (!ids.length) return res.status(400).json({ error: "ids array is required" });

  const PIXELDRAIN_API_KEY = process.env.PIXELDRAIN_API_KEY || "";

  const jobIds = [];



  for (const id of ids) {

    const info = resolveFileFromId(String(id));

    if (!info) continue;

    try { await fsp.access(info.filePath); } catch { continue; }

    const st = await fsp.stat(info.filePath);

    const pdJobId = randomId("pd");

    const pdJob = {

      id: pdJobId, createdAt: Date.now(), status: "running",

      filename: info.name, bytesUploaded: 0, totalBytes: st.size,

      pixeldrainUrl: null, error: null,

    };

    pixeldrainJobs.set(pdJobId, pdJob);

    jobIds.push(pdJobId);



    (async (localInfo, localSt, localJob) => {

      try {

        const fileStream = fs.createReadStream(localInfo.filePath);

        let bytesRead = 0;

        fileStream.on("data", (chunk) => { bytesRead += chunk.length; localJob.bytesUploaded = bytesRead; });

        const headers = {

          "Content-Type": "application/octet-stream",

          "Content-Length": String(localSt.size),

        };

        if (PIXELDRAIN_API_KEY) {

          headers["Authorization"] = `Basic ${Buffer.from(`:${PIXELDRAIN_API_KEY}`).toString("base64")}`;

        }

        const url = `https://pixeldrain.com/api/file/${encodeURIComponent(localInfo.name)}`;

        const response = await new Promise((resolve, reject) => {

          const parsedUrl = new URL(url);

          const opts = { hostname: parsedUrl.hostname, path: parsedUrl.pathname + parsedUrl.search, method: "PUT", headers };

          const r = https.request(opts, resolve);

          r.on("error", reject);

          fileStream.pipe(r);

        });

        let body = "";

        await new Promise((resolve) => { response.on("data", (d) => { body += d.toString(); }); response.on("end", resolve); });

        const result = JSON.parse(body);

        if (result.id) {

          localJob.status = "done"; localJob.bytesUploaded = localSt.size;

          localJob.pixeldrainUrl = `https://pixeldrain.com/u/${result.id}`;

        } else {

          localJob.status = "failed"; localJob.error = result.message || "Upload failed";

        }

      } catch (err) { localJob.status = "failed"; localJob.error = err.message || "Upload failed"; }

    })(info, st, pdJob);

  }



  return res.json({ ok: true, jobIds });

});



// ── Batch Zip ──────────────────────────────────────────────────────────────────

app.post("/api/batch/zip", async (req, res) => {

  const ids = Array.isArray(req.body?.fileIds) ? req.body.fileIds : [];

  if (ids.length < 1) return res.status(400).json({ error: "fileIds array is required" });



  const resolvedFiles = [];

  for (const id of ids) {

    const info = resolveFileFromId(String(id));

    if (!info) continue;

    try { await fsp.access(info.filePath); resolvedFiles.push(info); } catch { /* skip missing */ }

  }

  if (resolvedFiles.length === 0) return res.status(400).json({ error: "No valid files to zip" });



  // Generate unique zip filename

  const timestamp = new Date().toISOString().slice(0, 19).replace(/[T:]/g, "-");

  const { name: zipName, fullPath: zipPath } = getUniqueFilePath(DOWNLOADS_DIR, `archive_${timestamp}.zip`);



  try {

    const archiver = (await import("archiver")).default;

    const archive = archiver("zip", { zlib: { level: 5 } });

    const output = fs.createWriteStream(zipPath);



    await new Promise((resolve, reject) => {

      output.on("close", resolve);

      archive.on("error", reject);

      archive.pipe(output);

      for (const f of resolvedFiles) {

        archive.file(f.filePath, { name: path.basename(f.filePath) });

      }

      archive.finalize();

    });



    return res.json({ ok: true, filename: zipName, fileCount: resolvedFiles.length });

  } catch (err) {

    // Clean up partial zip on failure

    await fsp.unlink(zipPath).catch(() => {});

    return res.status(500).json({ error: err.message || "Failed to create zip" });

  }

});



// ── Unzip archive ──────────────────────────────────────────────────────────────

app.post("/api/files/:id/unzip", async (req, res) => {

  const info = resolveFileFromId(decodeURIComponent(String(req.params.id || "")));

  if (!info) return res.status(400).json({ error: "Invalid file id" });

  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }



  const ext = info.name.toLowerCase();

  const isZip = ext.endsWith(".zip");

  const isTar = ext.endsWith(".tar") || ext.endsWith(".tar.gz") || ext.endsWith(".tgz")

    || ext.endsWith(".tar.xz") || ext.endsWith(".tar.bz2");



  if (!isZip && !isTar) {

    return res.status(400).json({ error: "Unsupported archive format. Supported: .zip, .tar, .tar.gz, .tgz, .tar.xz, .tar.bz2" });

  }



  // Create output folder named after the archive (without extension) in the same directory

  const sourceDir = path.dirname(info.filePath);

  let baseName = path.parse(info.name).name;

  // Handle double extensions like .tar.gz

  if (baseName.toLowerCase().endsWith(".tar")) baseName = baseName.slice(0, -4);



  // Find a unique folder name

  let outDirName = baseName;

  let outDir = path.join(sourceDir, outDirName);

  let idx = 1;

  while (fs.existsSync(outDir)) {

    outDirName = `${baseName} (${idx})`;

    outDir = path.join(sourceDir, outDirName);

    idx++;

  }

  await fsp.mkdir(outDir, { recursive: true });



  try {

    if (isZip) {

      const unzipper = (await import("unzipper")).default;

      await new Promise((resolve, reject) => {

        fs.createReadStream(info.filePath)

          .pipe(unzipper.Extract({ path: outDir }))

          .on("close", resolve)

          .on("error", reject);

      });

    } else if (isTar) {

      // Use system tar command for .tar, .tar.gz, .tar.xz, .tar.bz2

      await runProcess("tar", ["-xf", info.filePath, "-C", outDir]);

    }



    // Count extracted files

    let fileCount = 0;

    const countFiles = async (dir) => {

      const entries = await fsp.readdir(dir, { withFileTypes: true });

      for (const e of entries) {

        if (e.isFile()) fileCount++;

        else if (e.isDirectory()) await countFiles(path.join(dir, e.name));

      }

    };

    await countFiles(outDir);



    // Compute relative output folder path

    const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR;

    const relOutDir = path.relative(base, outDir);

    const outputFolder = relOutDir ? `/${relOutDir}` : "/";



    return res.json({ ok: true, outputFolder, fileCount });

  } catch (err) {

    // Clean up on failure

    await fsp.rm(outDir, { recursive: true, force: true }).catch(() => {});

    return res.status(500).json({ error: err.message || "Extraction failed" });

  }

});





function isHfBucketUrl(url) {

  const m = String(url).match(/^(?:https?:\/\/)?huggingface\.co\/(?:api\/)?buckets\/([^\/]+)\/([^\/]+)(?:\/tree(?:\/(.*))?)?$/);

  if (m) return { org: m[1], bucket: m[2], path: (m[3]||"").replace(/\/+$/, "") };

  return null;

}



async function listHfBucket(org, bucket, prefix, hfToken) {

  const api = `https://huggingface.co/api/buckets/${encodeURIComponent(org)}/${encodeURIComponent(bucket)}/tree/${encodeURIComponent(prefix||"")}`;

  const headers = { "Accept": "application/json", "User-Agent": "Mozilla/5.0" };

  if (hfToken) headers.Authorization = `Bearer ${hfToken}`;

  const r = await fetchWithTimeout(api, { headers }, 10000);

  if (!r.ok) throw new Error("HF Bucket API returned " + r.status);

  const items = await r.json();

  const prefixStr = prefix ? prefix.replace(/\/+$/,"")+"/" : "";

  const seen = new Set();

  const out = [];

  for (const item of items) {

    const rel = item.path.startsWith(prefixStr) ? item.path.slice(prefixStr.length) : item.path;

    if (!rel) continue;

    if (item.type === "directory") {

      const n = rel.replace(/\/+$/,"").split("/")[0];

      if (n && !seen.has("d:"+n)) { seen.add("d:"+n); out.push({name:n,isDir:true,size:0,sizeStr:"-",type:"directory"}); }

    } else {

      const parts = rel.split("/");

      if (parts.length>1) {

        const n = parts[0];

        if (!seen.has("d:"+n)) { seen.add("d:"+n); out.push({name:n,isDir:true,size:0,sizeStr:"-",type:"directory"}); }

      } else {

        const n = parts[0];

        if (!seen.has("f:"+n)) {

          seen.add("f:"+n);

          out.push({name:n,isDir:false,size:item.size||0,sizeStr:item.size?fmtBytesSimple(item.size):"0 B",type:"file",hfPath:item.path,hfOrg:org,hfBucket:bucket});

        }

      }

    }

  }

  return out;

}



async function listAllHfBucketFiles(org, bucket, prefix, hfToken) {

  const api = `https://huggingface.co/api/buckets/${encodeURIComponent(org)}/${encodeURIComponent(bucket)}/tree/${encodeURIComponent(prefix||"")}?recursive=true`;

  const headers = { "Accept": "application/json", "User-Agent": "Mozilla/5.0" };

  if (hfToken) headers.Authorization = `Bearer ${hfToken}`;

  const r = await fetchWithTimeout(api, { headers }, 15000);

  if (!r.ok) throw new Error("HF Bucket recursive API returned " + r.status);

  const items = await r.json();

  return items

    .filter((item) => item.type === "file")

    .map((item) => ({

      name: item.path.split("/").pop() || item.path,

      hfPath: item.path,

      hfOrg: org,

      hfBucket: bucket,

      size: item.size || 0,

    }));

}







// ── TeleBox helpers ────────────────────────────────────────────────────────────

async function teleboxRequest(endpoint, params, options = {}) {

  const url = new URL(`https://www.telebox.online${endpoint}`);

  for (const [k, v] of Object.entries(params || {})) {

    if (v !== undefined && v !== null) url.searchParams.set(k, String(v));

  }

  const r = await fetchWithTimeout(url.toString(), {

    headers: {

      "Accept": "application/json",

      "User-Agent": "Mozilla/5.0",

    },

  }, 15000);



  const data = await r.json().catch(() => null);

  if (!r.ok) throw new Error(`TeleBox HTTP ${r.status}`);

  if (!data) throw new Error("TeleBox returned non-JSON");



  const allowMsgs = Array.isArray(options.allowMsgs) ? options.allowMsgs : [];

  const msg = String(data.msg || "");



  if (typeof data.status !== "undefined" && Number(data.status) !== 1) {

    if (allowMsgs.some((s) => msg.toLowerCase().includes(String(s).toLowerCase()))) {

      return data;

    }

    throw new Error(data.msg || `TeleBox status ${data.status}`);

  }

  return data;

}



// ── TeleBox API routes ─────────────────────────────────────────────────────────

app.get("/api/telebox/list", async (req, res) => {

  const token = String(req.query.token || "").trim();

  const pid = String(req.query.pid || "0").trim();

  if (!token) return res.status(400).json({ error: "token is required" });



  try {

    const data = await teleboxRequest("/api/open/file_search", {

      name: "",

      pid,

      pageNo: 1,

      pageSize: 200,

      token,

    });



    const items = Array.isArray(data?.data?.list) ? data.data.list : [];

    const entries = items.map((item) => {

      const isDir = String(item.type || "").toLowerCase().includes("dir");

      return {

        id: String(item.id || item.item_id || ""),

        itemId: item.item_id ? String(item.item_id) : undefined,

        name: String(item.name || "unknown"),

        isDir,

        size: Number(item.size || 0),

        sizeStr: isDir ? "-" : fmtBytesSimple(Number(item.size || 0)),

        type: String(item.type || (isDir ? "dir" : "file")),

        subType: item.sub_type ? String(item.sub_type) : undefined,

        pid: Number(item.pid || 0),

      };

    });



    return res.json({ ok: true, entries, pid: Number(pid) });

  } catch (err) {

    return res.status(500).json({ error: err.message || "TeleBox list failed" });

  }

});



app.post("/api/telebox/folder-create", async (req, res) => {

  const { token, pid, name } = req.body || {};

  if (!token) return res.status(400).json({ error: "token is required" });

  if (!name) return res.status(400).json({ error: "name is required" });



  try {

    const data = await teleboxRequest("/api/open/folder_create", {

      name,

      pid: Number(pid || 0),

      token,

      isShare: 0,

      canInvite: 0,

      canShare: 0,

      withBodyImg: 0,

      desc: "",

    });

    return res.json({ ok: true, dirId: data?.data?.dirId ?? null });

  } catch (err) {

    return res.status(500).json({ error: err.message || "TeleBox folder create failed" });

  }

});



app.post("/api/telebox/download", async (req, res) => {

  const { token, webToken, itemId, filename, targetFolder } = req.body || {};

  const sessionToken = String(webToken || token || "").trim();



  if (!sessionToken) return res.status(400).json({ error: "webToken (or token) is required" });

  if (!itemId) return res.status(400).json({ error: "itemId is required" });



  try {

    const detailUrl = new URL("https://www.telebox.online/api/file/detail");

    detailUrl.searchParams.set("itemId", String(itemId));

    detailUrl.searchParams.set("needUser", "1");

    detailUrl.searchParams.set("needTpInfo", "1");

    detailUrl.searchParams.set("token", sessionToken);

    detailUrl.searchParams.set("platform", "web");

    detailUrl.searchParams.set("pf", "web");

    detailUrl.searchParams.set("lan", "en");



    const detailResp = await fetchWithTimeout(detailUrl.toString(), {

      headers: {

        "Accept": "application/json",

        "User-Agent": "Mozilla/5.0",

      },

    }, 15000);



    const detail = await detailResp.json().catch(() => null);

    if (!detailResp.ok) {

      return res.status(500).json({ error: `TeleBox detail HTTP ${detailResp.status}`, debug: detail });

    }



    const item = detail?.data?.itemInfo || null;

    const dlUrl =

      item?.resolutionList?.[0]?.url ||

      item?.url ||

      null;



    if (!dlUrl) {

      return res.status(500).json({

        error: "TeleBox detail did not return a downloadable URL",

        debug: detail

      });

    }



    const safeFolder = sanitizeFolderPath(String(targetFolder || ""));

    const targetDir = safeFolder && safeFolder !== "/"

      ? path.join(DOWNLOADS_DIR, safeFolder)

      : DOWNLOADS_DIR;

    await fsp.mkdir(targetDir, { recursive: true });



    const dlJobId = randomId("tbxdl");

    const dlJob = {

      id: dlJobId,

      createdAt: Date.now(),

      status: "running",

      url: String(dlUrl),

      filename: filename || item?.name || null,

      bytesDownloaded: 0,

      totalBytes: 0,

      error: null,

      targetFolder: safeFolder || "/",

      abortController: new AbortController(),

    };

    remoteDownloadJobs.set(dlJobId, dlJob);

    res.json({ ok: true, jobId: dlJobId });



    (async () => {

      try {

        const response = await fetch(dlUrl, {

          signal: dlJob.abortController.signal,

          headers: {

            "user-agent": USER_AGENT,

            "accept": "*/*",

          },

          redirect: "follow",

        });



        if (!response.ok || !response.body) {

          throw new Error(`TeleBox download HTTP ${response.status}`);

        }



        const requestedName = filename || item?.name || getFilenameFromHeaders(response, dlUrl);

        const outName = ensureUniqueFilename(targetDir, sanitizeFilename(requestedName || "telebox.bin"));

        const outPath = path.join(targetDir, outName);



        dlJob.filename = outName;

        dlJob.totalBytes = Number(response.headers.get("content-length") || item?.size || 0);



        await streamResponseToFile(response, outPath, dlJob);



        dlJob.status = "done";

        dlJob.completedAt = Date.now();

        dlJob.localPath = outPath;

      } catch (err) {

        dlJob.status = "error";

        dlJob.error = err?.message || "TeleBox download failed";

        dlJob.completedAt = Date.now();

      }

    })();

  } catch (err) {

    return res.status(500).json({

      error: err?.message || "TeleBox download setup failed"

    });

  }

});



app.post("/api/telebox/upload", upload.array("files"), async (req, res) => {

  const token = String(req.body?.token || "").trim();

  const pid = Number(req.body?.pid || 0);

  if (!token) return res.status(400).json({ error: "token is required" });



  const files = Array.isArray(req.files) ? req.files : [];

  if (!files.length) return res.status(400).json({ error: "No files uploaded" });



  const results = [];



  try {

    for (const file of files) {

      const pre10m = file.buffer.subarray(0, Math.min(file.buffer.length, 10 * 1024 * 1024));

      const crypto = await import("node:crypto");

      const md5 = crypto.createHash("md5").update(pre10m).digest("hex");



      const auth = await teleboxRequest("/api/open/get_upload_url", {

        fileMd5ofPre10m: md5,

        fileSize: file.size,

        token,

      }, {

        allowMsgs: ["not need upload"],

      });

      console.log("TELEBOX UPLOAD auth response:", JSON.stringify(auth, null, 2));



      const signUrl = auth?.data?.signUrl;

      const skipUpload =

        !signUrl &&

        /not need upload/i.test(String(auth?.msg || ""));



      if (!signUrl && !skipUpload) {

        throw new Error(`TeleBox did not return signUrl: ${JSON.stringify(auth)}`);

      }



      if (!skipUpload) {

        const putResp = await fetch(signUrl, {

          method: "PUT",

          body: file.buffer,

          headers: {

            "Content-Length": String(file.size),

          },

        });



        if (!putResp.ok) {

          throw new Error(`TeleBox upload PUT failed with ${putResp.status}`);

        }

      } else {

        console.log("TELEBOX UPLOAD skipping PUT because API said not need upload");

      }



      console.log("TELEBOX UPLOAD file:", JSON.stringify({

        name: file.originalname,

        size: file.size,

        pid,

        md5

      }, null, 2));



      const finish = await teleboxRequest("/api/open/folder_upload_file", {

        fileMd5ofPre10m: md5,

        fileSize: file.size,

        pid,

        diyName: file.originalname,

        token,

      });

      console.log("TELEBOX UPLOAD finish response:", JSON.stringify(finish, null, 2));



      results.push({

        ok: true,

        name: file.originalname,

        itemId:

          finish?.data?.itemId ||

          finish?.data?.item_id ||

          finish?.itemId ||

          finish?.item_id ||

          null,

      });

    }



    return res.json({ ok: true, results });

  } catch (err) {

    return res.status(500).json({ error: err.message || "TeleBox upload failed", results });

  }

});



// ── Remote Server Browser ──────────────────────────────────────────────────────

const remoteDownloadJobs = new Map();



// Test endpoint to check if a URL is reachable from HuggingFace

app.get("/api/remote/test", async (req, res) => {

  const testUrl = String(req.query.url || "").trim();

  if (!testUrl) return res.status(400).json({ error: "url query param required" });

  

  console.log(`[Remote Test] Testing connectivity to: ${testUrl}`);

  const startTime = Date.now();

  

  try {

    const response = await fetchWithTimeout(testUrl, { method: "HEAD" }, 5000);

    const elapsed = Date.now() - startTime;

    console.log(`[Remote Test] Success: ${response.status} in ${elapsed}ms`);

    return res.json({

      ok: true,

      reachable: true,

      status: response.status,

      statusText: response.statusText,

      responseTimeMs: elapsed,

      headers: Object.fromEntries(response.headers.entries()),

    });

  } catch (err) {

    const elapsed = Date.now() - startTime;

    console.log(`[Remote Test] Failed after ${elapsed}ms: ${err.message}`);

    return res.json({

      ok: false,

      reachable: false,

      error: err.message,

      responseTimeMs: elapsed,

      suggestion: "HuggingFace Spaces may block connections to non-standard ports. Try using ports 80, 443, or 8080. Also ensure the remote server is running and publicly accessible.",

    });

  }

});



app.get("/api/remote/list", async (req, res) => {

  const baseUrl = String(req.query.url || "").trim().replace(/\/+$/, "");

  const remotePath = String(req.query.path || "").trim().replace(/^\//, "").replace(/\/+$/, "");

  const listPath = remotePath ? "/" + remotePath : "";

  const hfToken = String(req.query.hfToken || "").trim();

  if (!baseUrl) return res.status(400).json({ error: "url query param is required" });

  

  // Send response quickly - don't let HF gateway timeout

  const startTime = Date.now();



  // Helper to parse JSON array response from custom Python server

  function parseJsonListing(text) {

    const json = JSON.parse(text);

    const arr = Array.isArray(json) ? json : [];

    return arr.map((item) => {

      const size = typeof item.size === "number" ? item.size : parseInt(item.size) || 0;

      const isDir = item.type === "directory" || item.type === "dir" || item.type === "folder";

      return {

        name: String(item.name || "unknown"),

        isDir,

        size,

        sizeStr: isDir ? "-" : (size > 0 ? fmtBytesSimple(size) : "0 B"),

        type: item.type || "file",

      };

    });

  }



  // Helper to parse HTML directory listing (Apache/Nginx/Python SimpleHTTPServer)

  function parseHtmlListing(html) {

    const entries = [];

    // Match <a href="...">name</a> patterns

    const linkRegex = /<a\s+[^>]*href="([^"]+)"[^>]*>([^<]*)<\/a>/gi;

    let match;

    while ((match = linkRegex.exec(html)) !== null) {

      const href = match[1];

      const text = match[2].trim();

      // Skip parent directory, query strings, absolute URLs, and anchors

      if (!href || href === "../" || href === ".." || href.startsWith("?") ||

          href.startsWith("#") || href.startsWith("http://") || href.startsWith("https://") ||

          href.startsWith("/") || text === "Parent Directory" || text === "..") continue;

      const isDir = href.endsWith("/");

      const name = decodeURIComponent(isDir ? href.slice(0, -1) : href);

      if (!name) continue;

      // Try to extract size from the line (common in autoindex)

      let size = 0;

      const lineAfter = html.substring(match.index + match[0].length, match.index + match[0].length + 100);

      const sizeMatch = lineAfter.match(/(\d+(?:\.\d+)?)\s*([KMGT]i?B?)/i);

      if (sizeMatch) {

        const num = parseFloat(sizeMatch[1]);

        const unit = sizeMatch[2].toUpperCase().replace("I", "");

        if (unit.startsWith("K")) size = Math.round(num * 1024);

        else if (unit.startsWith("M")) size = Math.round(num * 1024 * 1024);

        else if (unit.startsWith("G")) size = Math.round(num * 1024 * 1024 * 1024);

        else if (unit.startsWith("T")) size = Math.round(num * 1024 * 1024 * 1024 * 1024);

      }

      entries.push({

        name,

        isDir,

        size,

        sizeStr: size ? fmtBytesSimple(size) : (isDir ? "-" : undefined),

        type: isDir ? "directory" : "file",

      });

    }

    return entries;

  }



  try {

    // Strategy 0: HuggingFace Storage Bucket

    let entries = null;

    let fetchError = null;



    console.log(`[Remote] Attempting to list files from: ${baseUrl}`);



    const hfBucket = isHfBucketUrl(baseUrl);

    if (hfBucket) {

      try {

        entries = await listHfBucket(hfBucket.org, hfBucket.bucket, hfBucket.path, hfToken);

        if (entries.length > 0) {

          entries.sort((a, b) => { if (a.isDir && !b.isDir) return -1; if (!a.isDir && b.isDir) return 1; return a.name.localeCompare(b.name); });

          return res.json({ ok: true, entries, baseUrl });

        }

      } catch (err) {

        fetchError = "HF Bucket: " + err.message;

      }

    }



    try {

      console.log(`[Remote] Strategy 1: GET ${baseUrl}/files${listPath ? "?path=" + encodeURIComponent(listPath) : ""}`);

      const fetchUrl1 = listPath ? `${baseUrl}/files?path=${encodeURIComponent(listPath)}` : `${baseUrl}/files`;

      const response = await fetchWithTimeout(fetchUrl1, {

        headers: { "Accept": "application/json" },

      }, 5000); // 5 second timeout

      console.log(`[Remote] Strategy 1 response status: ${response.status}`);

      if (response.ok) {

        const text = await response.text();

        console.log(`[Remote] Strategy 1 response length: ${text.length} chars`);

        try {

          entries = parseJsonListing(text);

          console.log(`[Remote] Strategy 1 parsed ${entries.length} entries`);

        } catch (parseErr) {

          // /files returned non-JSON, not a custom API server

          fetchError = `GET /files returned non-JSON: ${text.substring(0, 100)}`;

          console.log(`[Remote] Strategy 1 parse failed: ${fetchError}`);

        }

      } else {

        fetchError = `GET /files returned ${response.status}`;

        console.log(`[Remote] Strategy 1 failed: ${fetchError}`);

      }

    } catch (err) {

      fetchError = err.message || "Failed to connect";

      console.log(`[Remote] Strategy 1 error: ${fetchError}`);

    }



    // Strategy 2: If /files failed, try root URL for HTML directory listing

    if (!entries || entries.length === 0) {

      try {

        console.log(`[Remote] Strategy 2: GET ${baseUrl}/${listPath ? listPath.slice(1) + "/" : ""}`);

        const fetchUrl2 = listPath ? `${baseUrl}/${remotePath}/` : `${baseUrl}/`;

        const rootResponse = await fetchWithTimeout(fetchUrl2, {}, 5000);

        console.log(`[Remote] Strategy 2 response status: ${rootResponse.status}`);

        if (rootResponse.ok) {

          const html = await rootResponse.text();

          console.log(`[Remote] Strategy 2 response length: ${html.length} chars`);

          // Try JSON first (maybe root returns JSON)

          try {

            entries = parseJsonListing(html);

            console.log(`[Remote] Strategy 2 parsed as JSON: ${entries.length} entries`);

          } catch {

            // Try HTML parsing

            const htmlEntries = parseHtmlListing(html);

            console.log(`[Remote] Strategy 2 parsed as HTML: ${htmlEntries.length} entries`);

            if (htmlEntries.length > 0) {

              entries = htmlEntries;

              fetchError = null; // HTML listing worked

            }

          }

        }

      } catch (err) {

        console.log(`[Remote] Strategy 2 error: ${err.message}`);

        // Root fetch also failed

      }

    }



    if (!entries || entries.length === 0) {

      return res.status(502).json({

        error: fetchError

          ? `Could not list files from remote server. ${fetchError}`

          : "Could not list files. Server returned no parseable file listing. Make sure the server has GET /files endpoint or serves an HTML directory listing.",

      });

    }



    // Sort: directories first, then files alphabetically

    entries.sort((a, b) => {

      if (a.isDir && !b.isDir) return -1;

      if (!a.isDir && b.isDir) return 1;

      return a.name.localeCompare(b.name);

    });



    return res.json({ ok: true, entries, baseUrl });

  } catch (err) {

    return res.status(500).json({ error: err.message || "Failed to fetch remote listing" });

  }

});



// AWS SigV4 requires the canonical query string to be built from individually

// percent-encoded, alphabetically-sorted key/value pairs β€” NOT the raw query

// string dropped in wholesale. Getting this wrong (e.g. lumping "?list-type=2&

// delimiter=/" into the canonical URI with an empty canonical query string)

// produces a signature that some providers (Backblaze B2) reject outright with

// SignatureDoesNotMatch, while others tolerate it. Always build both the actual

// request query string and the canonical one from the same encoding so they

// can never drift apart.

function awsUriEncode(str) {

  return encodeURIComponent(str).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());

}

function buildCanonicalQueryString(queryParams) {

  if (!queryParams) return "";

  const entries = Object.entries(queryParams).filter(([, v]) => v !== undefined && v !== null);

  entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));

  return entries.map(([k, v]) => `${awsUriEncode(k)}=${awsUriEncode(String(v))}`).join("&");

}



// Generic AWS SigV4 signed request against any S3-compatible host (HF buckets,

// Qencode media storage, Backblaze B2, etc). Signs only host/x-amz-content-sha256/

// x-amz-date β€” the minimal header set AWS SigV4 requires β€” since some gateways

// (e.g. Backblaze-backed ones) reject requests that sign more than they're sent.

// `queryParams` is an optional object of query key/value pairs (not a raw string).

function s3SignedRequest(method, host, pathStr, queryParams, region, accessKeyId, secretAccessKey, body, contentType) {

  return new Promise((resolve, reject) => {

    const service = "s3";

    const now = new Date();

    const amzDate = now.toISOString().replace(/[:-]/g, "").replace(/\.\d{3}Z$/, "Z");

    const dateStr = amzDate.slice(0, 8);

    const bodyBuf = body || Buffer.alloc(0);

    const bodyHash = crypto.createHash("sha256").update(bodyBuf).digest("hex");

    const canonicalQueryString = buildCanonicalQueryString(queryParams);

    const requestPath = canonicalQueryString ? `${pathStr}?${canonicalQueryString}` : pathStr;



    const signedHeaders = "host;x-amz-content-sha256;x-amz-date";

    const canonicalHeaders = `host:${host}\nx-amz-content-sha256:${bodyHash}\nx-amz-date:${amzDate}\n`;

    const canonicalRequest = [method, pathStr, canonicalQueryString, canonicalHeaders, signedHeaders, bodyHash].join("\n");



    const credentialScope = `${dateStr}/${region}/${service}/aws4_request`;

    const stringToSign = [

      "AWS4-HMAC-SHA256",

      amzDate,

      credentialScope,

      crypto.createHash("sha256").update(canonicalRequest).digest("hex"),

    ].join("\n");



    function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); }

    const dateKey = hmac(`AWS4${secretAccessKey}`, dateStr);

    const regionKey = hmac(dateKey, region);

    const serviceKey = hmac(regionKey, service);

    const signingKey = hmac(serviceKey, "aws4_request");

    const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex");



    const authorization = `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;



    const headers = {

      Host: host,

      "x-amz-content-sha256": bodyHash,

      "x-amz-date": amzDate,

      Authorization: authorization,

    };

    if (body) {

      headers["Content-Length"] = Buffer.byteLength(bodyBuf);

      headers["Content-Type"] = contentType || "application/octet-stream";

    }



    const req2 = https.request({ hostname: host, port: 443, path: requestPath, method, headers }, (res) => {

      if (method === "GET" && res.statusCode >= 200 && res.statusCode < 300 && contentType === "__STREAM__") {

        resolve({ status: res.statusCode, stream: res, headers: res.headers });

        return;

      }

      let data = "";

      res.on("data", (chunk) => (data += chunk));

      res.on("end", () => {

        if (res.statusCode >= 200 && res.statusCode < 300) resolve({ status: res.statusCode, body: data, headers: res.headers });

        else reject(new Error(`S3 request failed: ${res.statusCode} ${data.slice(0, 500)}`));

      });

    });

    req2.on("error", reject);

    req2.end(bodyBuf);

  });

}



// Helper function for HF bucket copy operations (GET β†’ PUT β†’ DELETE)

async function hfBucketCopyViaGetPut(hf, oldKey, newKey, accessKeyId, secretAccessKey, hfToken) {

  // oldKey is like "bucketname/optional/path/filename.mp4"

  // The HF resolve URL is: /buckets/{org}/{repo}/resolve/{path_within_repo}

  // where path_within_repo is everything after "{bucket}/"

  const oldObjectPath = oldKey.startsWith(hf.bucket + "/")

    ? oldKey.slice(hf.bucket.length + 1)

    : oldKey;



  // Encode each path segment individually (don't encode the slashes)

  const encodedPath = oldObjectPath.split("/").map(s => encodeURIComponent(s)).join("/");

  const resolveUrl = `https://huggingface.co/buckets/${encodeURIComponent(hf.org)}/${encodeURIComponent(hf.bucket)}/resolve/${encodedPath}?download=true`;



  console.log("[HF copy] GET from:", resolveUrl);

  console.log("[HF copy] hfToken:", hfToken ? hfToken.slice(0, 8) + "..." : "MISSING");



  if (!hfToken) {

    throw new Error("hfToken is required for HF bucket GET β€” add your HF token in the Remote tab");

  }



  const getResp = await fetch(resolveUrl, {

    headers: {

      "Authorization": `Bearer ${hfToken}`,

      "User-Agent": "Mozilla/5.0",

      "Accept": "*/*",

    },

    redirect: "follow",

  });



  if (!getResp.ok) {

    const body = await getResp.text().catch(() => "(unreadable)");

    throw new Error(`HF GET failed: ${getResp.status} ${getResp.statusText} β€” ${body}`);

  }



  const arrayBuffer = await getResp.arrayBuffer();

  const buffer = Buffer.from(arrayBuffer);

  const contentType = getResp.headers.get("content-type") || "application/octet-stream";



  console.log("[HF copy] Downloaded bytes:", buffer.length, "| contentType:", contentType);



  const client = new S3Client({

    endpoint: "https://s3.hf.co",

    region: "us-east-1",

    credentials: { accessKeyId, secretAccessKey },

    forcePathStyle: true,

  });



  await client.send(new PutObjectCommand({

    Bucket: hf.org,

    Key: newKey,

    Body: buffer,

    ContentType: contentType,

  }));

  console.log("[HF copy] PUT to:", newKey, "β€” OK");



  await client.send(new DeleteObjectCommand({

    Bucket: hf.org,

    Key: oldKey,

  }));

  console.log("[HF copy] DELETE:", oldKey, "β€” OK");

}



// PUT a file into an HF Storage Bucket via the S3 gateway.

async function hfBucketUpload(hf, filename, buffer, accessKeyId, secretAccessKey) {

  const keyParts = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), filename].filter(Boolean);

  const pathStr = "/" + [hf.org, ...keyParts].map(encodeURIComponent).join("/");

  await s3SignedRequest("PUT", "s3.hf.co", pathStr, null, "us-east-1", accessKeyId, secretAccessKey, buffer, "application/octet-stream");

}



// Helpers for the generic S3-compatible storage integration (Qencode, Backblaze,

// Wasabi, R2, etc). Callers pass the exact bucket endpoint URL they were given

// (virtual-hosted style, e.g. https://<bucket>.media-storage.<region>.qencode.com) β€”

// we sign requests straight against that host with no bucket segment in the path.

function s3KeyPath(prefix, name) {

  const parts = [...(prefix ? prefix.split("/") : []), name].filter(Boolean);

  return "/" + parts.map(encodeURIComponent).join("/");

}



// ── Qencode CDN signed URLs (RS256 JWT, separate from the S3 access key/secret) ──

const QENCODE_SIGNING_KEY_PATH = path.join(__dirname, ".secrets", "qencode_signing_key.pem");

const QENCODE_SIGNING_KEY_ID = "90be430d-8dc6-4f12-832c-08443bb0c3af";



function base64url(input) {

  return Buffer.from(input).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");

}



function signQencodeToken(kid, privateKeyPem, uri, expiresInSeconds) {

  const header = { alg: "RS256", typ: "JWT", kid };

  const payload = { uri: uri || "", exp: Math.floor(Date.now() / 1000) + (expiresInSeconds || 3600) };

  const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`;

  const signature = crypto.sign("RSA-SHA256", Buffer.from(signingInput), privateKeyPem);

  return `${signingInput}.${signature.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;

}



app.post("/api/s3/signed-url", async (req, res) => {

  const endpointUrl = String(req.body?.endpointUrl || "").trim().replace(/\/+$/, "");

  const objectKey = String(req.body?.objectKey || "").trim();

  const expiresInSeconds = Number(req.body?.expiresInSeconds) || 3600;

  if (!endpointUrl || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" });

  let privateKeyPem;

  try {

    privateKeyPem = fs.readFileSync(QENCODE_SIGNING_KEY_PATH, "utf8");

  } catch {

    return res.status(400).json({ ok: false, error: "No Qencode signing key configured on the server" });

  }

  try {

    const uriPath = "/" + objectKey.split("/").map(encodeURIComponent).join("/");

    const token = signQencodeToken(QENCODE_SIGNING_KEY_ID, privateKeyPem, uriPath, expiresInSeconds);

    const url = `${endpointUrl}${uriPath}?auth=${token}`;

    return res.json({ ok: true, url, expiresInSeconds });

  } catch (err) {

    return res.status(500).json({ ok: false, error: err.message || "Failed to sign URL" });

  }

});



function fmtBytesSimple(bytes) {

  if (bytes < 1024) return `${bytes} B`;

  if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`;

  if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(2)} MB`;

  return `${(bytes / 1024 ** 3).toFixed(2)} GB`;

}



// ── Helper: build a remote file ID (downloaded:name) for proxying to this app's API ──

function remoteFileId(name) {

  return encodeURIComponent(`downloaded:${name}`);

}



// ── Helper: create S3 client for HF bucket operations ──

function hfS3Client(accessKeyId, secretAccessKey) {

  return new S3Client({

    endpoint: "https://s3.hf.co",

    region: "us-east-1",

    credentials: { accessKeyId, secretAccessKey },

    forcePathStyle: true,

  });

}



// ── Helper: build HF bucket S3 key from URL and filename ──

function hfS3Key(hf, name) {

  return [hf.bucket, ...(hf.path ? hf.path.split("/") : []), name].filter(Boolean).join("/");

}



// Remote rename β€” try multiple strategies:

// 1. S3 CopyObject + DeleteObject (HF bucket)

// 2. {baseUrl}/api/files/{id}/rename  (same app as remote)

// 3. {baseUrl}/rename                  (custom Python server)

// 4. {baseUrl}/                        (generic fallback)

app.post("/api/remote/rename", async (req, res) => {

  const { serverUrl, oldName, newName, hfAccessKeyId, hfSecretAccessKey, hfToken } = req.body || {};

  if (!serverUrl || !oldName || !newName) {

    return res.status(400).json({ error: "serverUrl, oldName and newName are required" });

  }



  console.log("[rename] body keys received:", Object.keys(req.body || {}));

  console.log("[rename] hfToken present:", !!hfToken, "| value:", hfToken ? hfToken.slice(0, 6) + "..." : "NONE");



  // Handle Hugging Face Buckets via S3 Gateway

  const hf = isHfBucketUrl(serverUrl);

  if (hf) {

    if (!hfAccessKeyId || !hfSecretAccessKey) {

      return res.status(400).json({ error: "HF S3 credentials required. Add them in the Remote tab." });

    }

    try {

      const oldKey = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), oldName].filter(Boolean).join("/");

      const newKey = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), newName].filter(Boolean).join("/");

      await hfBucketCopyViaGetPut(hf, oldKey, newKey, hfAccessKeyId, hfSecretAccessKey, hfToken);

      return res.json({ ok: true });

    } catch (err) {

      console.error("HF rename failed:", err, err?.$metadata, err?.Code);

      return res.status(500).json({ error: err.message || "HF bucket rename failed" });

    }

  }



  const baseUrl = String(serverUrl).trim().replace(/\/+$/, "");

  const fileId = remoteFileId(oldName);



  const attempts = [

    { url: `${baseUrl}/api/files/${fileId}/rename`, method: "POST", body: JSON.stringify({ newName }), headers: { "Content-Type": "application/json" } },

    { url: `${baseUrl}/rename`, method: "POST", body: JSON.stringify({ old_name: oldName, new_name: newName, oldName, newName }), headers: { "Content-Type": "application/json" } },

    { url: `${baseUrl}/`, method: "POST", body: JSON.stringify({ old_name: oldName, new_name: newName, oldName, newName }), headers: { "Content-Type": "application/json" } },

  ];



  let lastErr = null;

  for (const attempt of attempts) {

    try {

      const response = await fetchWithTimeout(attempt.url, { method: attempt.method, headers: attempt.headers, body: attempt.body }, 15000);

      if (response.ok) {

        const data = await response.json().catch(() => ({}));

        return res.json({ ok: true, ...data });

      }

      if (response.status === 404) { lastErr = `Remote returned 404`; continue; }

      const text = await response.text();

      return res.status(response.status).json({ error: text || `Remote returned ${response.status}` });

    } catch (err) {

      lastErr = err.message || "Connection failed";

      continue;

    }

  }

  return res.status(502).json({ error: `Remote rename failed: ${lastErr}` });

});



// Remote delete β€” try multiple strategies:

// 1. S3 DeleteObject (HF bucket)

// 2. DELETE {baseUrl}/api/files/{id}   (same app as remote)

// 3. POST {baseUrl}/delete             (custom Python server)

// 4. DELETE {baseUrl}/?name=...        (generic fallback)

app.post("/api/remote/delete", async (req, res) => {

  const { serverUrl, name, hfAccessKeyId, hfSecretAccessKey } = req.body || {};

  if (!serverUrl || !name) {

    return res.status(400).json({ error: "serverUrl and name are required" });

  }



  // Strategy 1: Hugging Face Bucket via S3 DeleteObject

  const hf = isHfBucketUrl(serverUrl);

  if (hf) {

    if (!hfAccessKeyId || !hfSecretAccessKey) {

      return res.status(400).json({ error: "HF S3 credentials required. Add them in the Remote tab." });

    }

    try {

      const key = hfS3Key(hf, name);

      const client = hfS3Client(hfAccessKeyId, hfSecretAccessKey);

      await client.send(new DeleteObjectCommand({ Bucket: hf.org, Key: key }));

      return res.json({ ok: true });

    } catch (err) {

      return res.status(500).json({ error: err.message || "HF bucket delete failed" });

    }

  }



  const baseUrl = String(serverUrl).trim().replace(/\/+$/, "");

  const fileId = remoteFileId(name);



  const attempts = [

    { url: `${baseUrl}/api/files/${fileId}`, method: "DELETE", body: null, headers: {} },

    { url: `${baseUrl}/delete`, method: "POST", body: JSON.stringify({ name }), headers: { "Content-Type": "application/json" } },

    { url: `${baseUrl}/?name=${encodeURIComponent(name)}`, method: "DELETE", body: null, headers: {} },

  ];



  let lastErr = null;

  for (const attempt of attempts) {

    try {

      const response = await fetchWithTimeout(attempt.url, { method: attempt.method, headers: attempt.headers, body: attempt.body }, 15000);

      if (response.ok) {

        const data = await response.json().catch(() => ({}));

        return res.json({ ok: true, ...data });

      }

      if (response.status === 404) { lastErr = `Remote returned 404`; continue; }

      const text = await response.text();

      return res.status(response.status).json({ error: text || `Remote returned ${response.status}` });

    } catch (err) {

      lastErr = err.message || "Connection failed";

      continue;

    }

  }

  return res.status(502).json({ error: `Remote delete failed: ${lastErr}` });

});



// Remote move: POST /api/remote/move

// Tries multiple strategies:

// 1. S3 CopyObject + DeleteObject (HF bucket)

// 2. POST {baseUrl}/api/files/{id}/move (same app as remote)

// 3. POST {baseUrl}/move               (custom Python server)

// 4. POST {baseUrl}/                   (generic fallback)

app.post("/api/remote/move", async (req, res) => {

  const { serverUrl, name, targetFolder, hfAccessKeyId, hfSecretAccessKey, hfToken } = req.body || {};

  if (!serverUrl || !name || targetFolder === undefined) {

    return res.status(400).json({ error: "serverUrl, name and targetFolder are required" });

  }



  console.log("[move] body keys received:", Object.keys(req.body || {}));

  console.log("[move] hfToken present:", !!hfToken, "| value:", hfToken ? hfToken.slice(0, 6) + "..." : "NONE");



  // Handle Hugging Face Buckets via S3 Gateway

  const hf = isHfBucketUrl(serverUrl);

  if (hf) {

    if (!hfAccessKeyId || !hfSecretAccessKey) {

      return res.status(400).json({ error: "HF S3 credentials required. Add them in the Remote tab." });

    }

    try {

      const oldKey = [hf.bucket, ...(hf.path ? hf.path.split("/") : []), name].filter(Boolean).join("/");

      const targetParts = targetFolder === "/" ? [] : targetFolder.replace(/^\//, "").split("/");

      const newKey = [hf.bucket, ...targetParts, name].filter(Boolean).join("/");



      if (oldKey !== newKey) {

        await hfBucketCopyViaGetPut(hf, oldKey, newKey, hfAccessKeyId, hfSecretAccessKey, hfToken);

      }



      return res.json({ ok: true });

    } catch (err) {

      console.error("HF move failed:", err, err?.$metadata, err?.Code);

      return res.status(500).json({ error: err.message || "HF bucket move failed" });

    }

  }



  const baseUrl = String(serverUrl).trim().replace(/\/+$/, "");

  const fileId = remoteFileId(name);



  const attempts = [

    { url: `${baseUrl}/api/files/${fileId}/move`, method: "POST", body: JSON.stringify({ targetFolder }), headers: { "Content-Type": "application/json" } },

    { url: `${baseUrl}/move`, method: "POST", body: JSON.stringify({ name, targetFolder, target_folder: targetFolder }), headers: { "Content-Type": "application/json" } },

    { url: `${baseUrl}/`, method: "POST", body: JSON.stringify({ name, targetFolder }), headers: { "Content-Type": "application/json" } },

  ];



  let lastErr = null;

  for (const attempt of attempts) {

    try {

      const response = await fetchWithTimeout(attempt.url, { method: attempt.method, headers: attempt.headers, body: attempt.body }, 15000);

      if (response.ok) {

        const data = await response.json().catch(() => ({}));

        return res.json({ ok: true, ...data });

      }

      if (response.status === 404) { lastErr = `Remote returned 404`; continue; }

      const text = await response.text();

      return res.status(response.status).json({ error: text || `Remote returned ${response.status}` });

    } catch (err) {

      lastErr = err.message || "Connection failed";

      continue;

    }

  }

  return res.status(502).json({ error: `Remote move failed: ${lastErr}` });

});



// Remote upload: POST / with FormData field "file"

app.post("/api/remote/upload", upload.single("file"), async (req, res) => {

  const serverUrl = String(req.body?.serverUrl || "").trim().replace(/\/+$/, "");

  if (!serverUrl) return res.status(400).json({ error: "serverUrl is required" });

  if (!req.file) return res.status(400).json({ error: "No file uploaded" });



  const hf = isHfBucketUrl(serverUrl);

  if (hf) {

    const accessKeyId = String(req.body?.hfAccessKeyId || "").trim();

    const secretAccessKey = String(req.body?.hfSecretAccessKey || "").trim();

    if (!accessKeyId || !secretAccessKey) {

      return res.status(400).json({ error: "This is a Hugging Face bucket. Enter its S3 access key ID and secret access key (generated from an HF access token with Write permission) to upload." });

    }

    try {

      await hfBucketUpload(hf, req.file.originalname, req.file.buffer, accessKeyId, secretAccessKey);

      return res.json({ ok: true });

    } catch (err) {

      return res.status(500).json({ error: err.message || "HF bucket upload failed" });

    }

  }



  try {

    // Build FormData for the remote server

    const formData = new FormData();

    const blob = new Blob([req.file.buffer], { type: req.file.mimetype || "application/octet-stream" });

    formData.append("file", blob, req.file.originalname);



    const response = await fetchWithTimeout(`${serverUrl}/`, {

      method: "POST",

      body: formData,

    }, 60000); // 60s timeout for uploads



    if (!response.ok) {

      const text = await response.text();

      return res.status(response.status).json({ error: text || `Remote returned ${response.status}` });

    }

    const data = await response.json().catch(() => ({}));

    return res.json({ ok: true, ...data });

  } catch (err) {

    return res.status(500).json({ error: err.message || "Remote upload failed" });

  }

});



app.post("/api/files/:id/remote-upload", async (req, res) => {

  const info = resolveFileFromId(decodeURIComponent(String(req.params.id || "")));

  if (!info) return res.status(400).json({ error: "Invalid file id" });

  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }



  const serverUrl = String(req.body?.serverUrl || "").trim().replace(/\/+$/, "");

  if (!serverUrl) return res.status(400).json({ error: "serverUrl is required" });



  const hf = isHfBucketUrl(serverUrl);

  if (hf) {

    const accessKeyId = String(req.body?.hfAccessKeyId || "").trim();

    const secretAccessKey = String(req.body?.hfSecretAccessKey || "").trim();

    if (!accessKeyId || !secretAccessKey) {

      return res.status(400).json({ error: "This is a Hugging Face bucket. Enter its S3 access key ID and secret access key (generated from an HF access token with Write permission) to upload." });

    }

    try {

      const buffer = await fsp.readFile(info.filePath);

      await hfBucketUpload(hf, info.name.split("/").pop(), buffer, accessKeyId, secretAccessKey);

      return res.json({ ok: true });

    } catch (err) {

      return res.status(500).json({ error: err.message || "HF bucket upload failed" });

    }

  }



  try {

    const buffer = await fsp.readFile(info.filePath);

    const formData = new FormData();

    const blob = new Blob([buffer], { type: "application/octet-stream" });

    formData.append("file", blob, info.name.split("/").pop());



    const response = await fetchWithTimeout(`${serverUrl}/`, {

      method: "POST",

      body: formData,

    }, 120000); // 2min timeout for larger media files



    if (!response.ok) {

      const text = await response.text();

      return res.status(response.status).json({ error: text || `Remote returned ${response.status}` });

    }

    const data = await response.json().catch(() => ({}));

    return res.json({ ok: true, ...data });

  } catch (err) {

    return res.status(500).json({ error: err.message || "Remote upload failed" });

  }

});



// Folder sync: use hf sync to upload a local folder to HuggingFace bucket

app.post("/api/remote/sync-folder", async (req, res) => {

  const { localPath, bucketUrl, hfToken } = req.body || {};

  

  if (!localPath || !bucketUrl) {

    return res.status(400).json({ error: "localPath and bucketUrl are required" });

  }



  // Verify local path exists

  let stats;

  try {

    stats = await fsp.stat(localPath);

    if (!stats.isDirectory()) {

      return res.status(400).json({ error: "localPath must be a directory" });

    }

  } catch (err) {

    return res.status(400).json({ error: `Local path not found or not readable: ${err.message}` });

  }



  // Must be HF bucket

  const hfBucket = isHfBucketUrl(bucketUrl);

  if (!hfBucket) {

    return res.status(400).json({ error: "Only HuggingFace buckets are supported for folder sync" });

  }



  const syncJobId = randomId("sync");

  const syncJob = {

    id: syncJobId,

    status: "running",

    localPath,

    bucketUrl,

    createdAt: Date.now(),

    log: [],

    error: null,

    bytesUploaded: 0,

    totalBytes: 0,

  };

  

  // Store job reference

  if (!global.syncJobs) global.syncJobs = new Map();

  global.syncJobs.set(syncJobId, syncJob);

  

  res.json({ ok: true, jobId: syncJobId });



  // Run sync in background

  (async () => {

    try {

      const hfSyncUrl = `hf://buckets/${encodeURIComponent(hfBucket.org)}/${encodeURIComponent(hfBucket.bucket)}`;

      const args = [

        "sync",

        localPath,

        hfSyncUrl,

        "--private" // private upload

      ];



      // Add token if provided (via env var to avoid exposing in process list)

      const env = { ...process.env };

      if (hfToken) {

        env.HF_TOKEN = hfToken;

      }



      syncJob.log.push(`Running: hf ${args.join(" ")}`);

      

      return new Promise((resolve) => {

        const proc = spawn("hf", args, {

          stdio: ["pipe", "pipe", "pipe"],

          env,

        });



        let stdout = "";

        let stderr = "";



        proc.stdout.on("data", (data) => {

          const text = String(data);

          stdout += text;

          syncJob.log.push(text);

        });



        proc.stderr.on("data", (data) => {

          const text = String(data);

          stderr += text;

          syncJob.log.push(`[ERROR] ${text}`);

        });



        proc.on("close", (code) => {

          if (code === 0) {

            syncJob.status = "done";

            syncJob.log.push("Sync completed successfully");

          } else {

            syncJob.status = "failed";

            syncJob.error = `hf sync exited with code ${code}: ${stderr || stdout}`;

            syncJob.log.push(`Failed with code ${code}`);

          }

          resolve();

        });



        proc.on("error", (err) => {

          syncJob.status = "failed";

          syncJob.error = err.message || "Unknown error";

          syncJob.log.push(`[ERROR] ${err.message}`);

          resolve();

        });



        // 10 minute timeout for sync

        setTimeout(() => {

          if (syncJob.status === "running") {

            proc.kill();

            syncJob.status = "failed";

            syncJob.error = "Sync timed out after 10 minutes";

            syncJob.log.push("Timeout: killed sync process");

          }

        }, 10 * 60 * 1000);

      });

    } catch (err) {

      syncJob.status = "failed";

      syncJob.error = err.message || "Unknown error";

      syncJob.log.push(`[ERROR] ${err.message}`);

    }

  })();

});



// Get sync job status

app.get("/api/remote/sync-status/:id", async (req, res) => {

  const jobId = String(req.params.id || "").trim();

  if (!jobId) return res.status(400).json({ error: "Job ID required" });



  if (!global.syncJobs) global.syncJobs = new Map();

  const job = global.syncJobs.get(jobId);

  

  if (!job) {

    return res.status(404).json({ error: "Job not found" });

  }



  return res.json({ ok: true, job });

});



app.post("/api/remote/download", async (req, res) => {

  const { url, filename, targetFolder, serverUrl, remoteName, hfPath, hfOrg, hfBucket, hfToken } = req.body || {};

  // Support both direct URL and serverUrl+remoteName for the custom Python server

  let downloadUrl = url || null;

  if (!downloadUrl && hfPath && hfOrg && hfBucket) {

    downloadUrl = `https://huggingface.co/buckets/${encodeURIComponent(String(hfOrg))}/${encodeURIComponent(String(hfBucket))}/resolve/${hfPath}?download=true`;

  } else if (!downloadUrl && serverUrl && remoteName) {

    const hf = isHfBucketUrl(String(serverUrl));

    if (hf) {

      const prefix = hf.path ? hf.path + "/" : "";

      downloadUrl = `https://huggingface.co/buckets/${encodeURIComponent(hf.org)}/${encodeURIComponent(hf.bucket)}/resolve/${prefix}${remoteName}?download=true`;

    } else {

      downloadUrl = `${String(serverUrl).trim().replace(/\/+$/, "")}/${encodeURIComponent(remoteName)}`;

    }

  }

  if (!downloadUrl) return res.status(400).json({ error: "url or serverUrl+remoteName is required" });



  const safeFolder = sanitizeFolderPath(String(targetFolder || ""));

  const targetDir = safeFolder && safeFolder !== "/"

    ? path.join(DOWNLOADS_DIR, safeFolder)

    : DOWNLOADS_DIR;

  await fsp.mkdir(targetDir, { recursive: true });



  const dlJobId = randomId("rdl");

  const dlJob = {

    id: dlJobId,

    createdAt: Date.now(),

    status: "running",

    url: String(downloadUrl || url || ""),

    filename: filename || null,

    bytesDownloaded: 0,

    totalBytes: 0,

    error: null,

    targetFolder: safeFolder || "/",

    abortController: new AbortController(),

  };

  remoteDownloadJobs.set(dlJobId, dlJob);

  res.json({ ok: true, jobId: dlJobId });



  (async () => {

    try {

      const headers = {

        "User-Agent": "Mozilla/5.0",

        "Accept": "*/*",

      };

      if (hfToken) headers.Authorization = `Bearer ${hfToken}`;

      const response = await fetch(downloadUrl, {

        signal: dlJob.abortController.signal,

        redirect: "follow",

        headers,

      });

      if (!response.ok || !response.body) {

        dlJob.status = "failed";

        dlJob.error = `Server returned ${response.status}`;

        return;

      }

      const contentLength = response.headers.get("content-length");

      dlJob.totalBytes = contentLength ? Number(contentLength) : 0;

      const requestedName = filename || remoteName || getFilenameFromHeaders(response, downloadUrl);

      const { name: finalName, fullPath: destPath } = getUniqueFilePath(targetDir, requestedName);

      dlJob.filename = finalName;

      const fileStream = fs.createWriteStream(destPath);

      const nodeReadable = Readable.fromWeb(response.body);

      nodeReadable.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; });

      await new Promise((resolve, reject) => {

        nodeReadable.on("error", reject);

        fileStream.on("error", reject);

        fileStream.on("finish", resolve);

        nodeReadable.pipe(fileStream);

      });

      dlJob.status = "done";

    } catch (err) {

      if (err.name === "AbortError") dlJob.status = "stopped";

      else { dlJob.status = "failed"; dlJob.error = err.message || "Download failed"; }

    }

  })();

});



app.get("/api/remote/download-jobs/:id", (req, res) => {

  const dlJob = remoteDownloadJobs.get(req.params.id);

  if (!dlJob) return res.status(404).json({ error: "Job not found" });

  const { abortController: _ac, ...safe } = dlJob;

  return res.json({ job: safe });

});





app.post("/api/remote/download-folder", async (req, res) => {

  const { serverUrl, folderName, targetFolder, hfToken } = req.body || {};

  const hf = isHfBucketUrl(String(serverUrl || ""));

  if (!hf) return res.status(400).json({ error: "Only HF bucket folder download is supported right now" });

  if (!folderName) return res.status(400).json({ error: "folderName is required" });



  try {

    const prefix = hf.path ? `${hf.path}/${folderName}` : String(folderName);

    const files = await listAllHfBucketFiles(hf.org, hf.bucket, prefix, String(hfToken || "").trim());



    if (!files.length) {

      return res.status(404).json({ error: "No files found in remote folder" });

    }



    const safeFolder = sanitizeFolderPath(String(targetFolder || ""));

    const targetDir = safeFolder && safeFolder !== "/"

      ? path.join(DOWNLOADS_DIR, safeFolder)

      : DOWNLOADS_DIR;

    await fsp.mkdir(targetDir, { recursive: true });



    const jobIds = [];



    for (const file of files) {

      const dlJobId = randomId("rdl");

      const dlJob = {

        id: dlJobId,

        createdAt: Date.now(),

        status: "running",

        url: `https://huggingface.co/buckets/${encodeURIComponent(file.hfOrg)}/${encodeURIComponent(file.hfBucket)}/resolve/${file.hfPath}?download=true`,

        filename: file.hfPath,

        bytesDownloaded: 0,

        totalBytes: 0,

        error: null,

        targetFolder: safeFolder || "/",

        abortController: new AbortController(),

      };

      remoteDownloadJobs.set(dlJobId, dlJob);

      jobIds.push(dlJobId);



      (async () => {

        try {

          const downloadUrl = `https://huggingface.co/buckets/${encodeURIComponent(file.hfOrg)}/${encodeURIComponent(file.hfBucket)}/resolve/${file.hfPath}?download=true`;

          const headers = {

            "User-Agent": "Mozilla/5.0",

            "Accept": "*/*",

          };

          if (hfToken) headers.Authorization = `Bearer ${hfToken}`;



          const response = await fetch(downloadUrl, {

            signal: dlJob.abortController.signal,

            redirect: "follow",

            headers,

          });



          if (!response.ok || !response.body) {

            dlJob.status = "failed";

            dlJob.error = `Server returned ${response.status}`;

            return;

          }



          const contentLength = response.headers.get("content-length");

          dlJob.totalBytes = contentLength ? Number(contentLength) : 0;



          const subPath = file.hfPath.startsWith(prefix + "/") ? file.hfPath.slice(prefix.length + 1) : file.name;

          const destFull = path.join(targetDir, folderName, subPath);

          await fsp.mkdir(path.dirname(destFull), { recursive: true });



          dlJob.filename = path.join(folderName, subPath);



          const fileStream = fs.createWriteStream(destFull);

          const nodeReadable = Readable.fromWeb(response.body);

          nodeReadable.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; });



          await new Promise((resolve, reject) => {

            nodeReadable.on("error", reject);

            fileStream.on("error", reject);

            fileStream.on("finish", resolve);

            nodeReadable.pipe(fileStream);

          });



          dlJob.status = "done";

        } catch (err) {

          if (err.name === "AbortError") dlJob.status = "stopped";

          else {

            dlJob.status = "failed";

            dlJob.error = err.message || "Download failed";

          }

        }

      })();

    }



    return res.json({ ok: true, jobIds, count: files.length });

  } catch (err) {

    return res.status(500).json({ error: err.message || "Folder download failed" });

  }

});



app.post("/api/remote/download-jobs/:id/stop", (req, res) => {

  const dlJob = remoteDownloadJobs.get(req.params.id);

  if (!dlJob) return res.status(404).json({ error: "Job not found" });

  if (dlJob.status === "running") { dlJob.abortController.abort(); dlJob.status = "stopped"; }

  return res.json({ ok: true });

});



// ── Backblaze B2 (S3-compatible) ───────────────────────────────────────────────



function b2SignS3(method, pathStr, endpointUrl, keyId, appKey, body = null) {

  return new Promise((resolve, reject) => {

    const parsed = new URL(endpointUrl);

    const host = parsed.hostname;

    const dateStr = new Date().toISOString().replace(/[:\-]/g, "").substring(0, 8);

    const amzDate = dateStr + "T000000Z";

    const service = "s3";

    const region = "us-west-002";



    const signedHeaders = "host;x-amz-content-sha256;x-amz-date";

    const bodyHash = crypto.createHash("sha256").update(body || "").digest("hex");

    const canonicalRequest = [

      method,

      pathStr,

      "",

      `host:${host}`,

      `x-amz-content-sha256:${bodyHash}`,

      `x-amz-date:${amzDate}`,

      "",

      signedHeaders,

      bodyHash,

    ].join("\n");



    const credentialScope = `${dateStr}/${region}/${service}/aws4_request`;

    const stringToSign = [

      "AWS4-HMAC-SHA256",

      amzDate,

      credentialScope,

      crypto.createHash("sha256").update(canonicalRequest).digest("hex"),

    ].join("\n");



    function hmac(key, str) {

      return crypto.createHmac("sha256", key).update(str).digest();

    }

    const dateKey = hmac(`AWS4${appKey}`, dateStr);

    const regionKey = hmac(dateKey, region);

    const serviceKey = hmac(regionKey, service);

    const signingKey = hmac(serviceKey, "aws4_request");

    const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex");



    const authorization = [

      `AWS4-HMAC-SHA256 Credential=${keyId}/${credentialScope}`,

      `SignedHeaders=${signedHeaders}`,

      `Signature=${signature}`,

    ].join(", ");



    const options = {

      hostname: host,

      port: 443,

      path: pathStr,

      method,

      headers: {

        Host: host,

        "x-amz-content-sha256": bodyHash,

        "x-amz-date": amzDate,

        Authorization: authorization,

        ...(body ? { "Content-Length": Buffer.byteLength(body), "Content-Type": "application/octet-stream" } : {}),

      },

    };



    const req = https.request(options, (res) => {

      let data = "";

      res.on("data", (chunk) => (data += chunk));

      res.on("end", () => {

        if (res.statusCode >= 200 && res.statusCode < 300) {

          resolve({ status: res.statusCode, body: data, headers: res.headers });

        } else {

          reject(new Error(`S3 request failed: ${res.statusCode} ${data.slice(0, 500)}`));

        }

      });

    });

    req.on("error", reject);

    req.end(body || undefined);

  });

}



function unescapeXml(str) {

  return str

    .replace(/&amp;/g,  "&")

    .replace(/&lt;/g,   "<")

    .replace(/&gt;/g,   ">")

    .replace(/&quot;/g, '"')

    .replace(/&apos;/g, "'");

}



function parseB2XmlList(xml) {

  const entries = [];

  const nameMatch = xml.match(/<Contents>([\s\S]*?)<\/Contents>/g) || [];

  for (const block of nameMatch) {

    const key = unescapeXml(block.match(/<Key>([^<]*)<\/Key>/)?.[1] || "");

    const size = parseInt(block.match(/<Size>(\d+)<\/Size>/)?.[1] || "0", 10);

    const lastMod = block.match(/<LastModified>([^<]*)<\/LastModified>/)?.[1] || "";

    entries.push({ key, name: key.split("/").pop(), isDir: false, size, sizeStr: `${(size / 1024).toFixed(1)} KB`, lastModified: lastMod, type: "file" });

  }

  // Parse CommonPrefixes for directories

  const prefixMatch = xml.match(/<CommonPrefixes>[\s\S]*?<Prefix>([^<]*)<\/Prefix>[\s\S]*?<\/CommonPrefixes>/g) || [];

  for (const block of prefixMatch) {

    const prefix = unescapeXml(block.match(/<Prefix>([^<]*)<\/Prefix>/)?.[1] || "");

    const name = prefix.replace(/\/$/, "").split("/").pop();

    if (name && !entries.some((e) => e.key === prefix)) {

      entries.push({ key: prefix, name, isDir: true, size: 0, type: "folder" });

    }

  }

  return entries;

}



app.get("/api/backblaze/list", async (req, res) => {

  const { bucketId, endpointUrl, keyId, appKey, prefix } = req.query;

  if (!bucketId || !endpointUrl || !keyId || !appKey) {

    return res.status(400).json({ ok: false, entries: [], error: "Missing required params (bucketId, endpointUrl, keyId, appKey)" });

  }

  try {

    let pathStr = `/${bucketId}`;

    if (prefix) pathStr += `?prefix=${encodeURIComponent(prefix)}&delimiter=/`;

    const result = await b2SignS3("GET", pathStr, endpointUrl, keyId, appKey);

    const entries = parseB2XmlList(result.body);

    return res.json({ ok: true, entries });

  } catch (err) {

    return res.status(500).json({ ok: false, entries: [], error: err.message || "Failed to list Backblaze bucket" });

  }

});



app.post("/api/backblaze/download", async (req, res) => {

  const { bucketId, endpointUrl, keyId, appKey, objectKey, targetFolder } = req.body;

  if (!bucketId || !endpointUrl || !keyId || !appKey || !objectKey) {

    return res.status(400).json({ ok: false, error: "Missing required params" });

  }

  try {

    const downloadDir = targetFolder ? path.join(DOWNLOADS_DIR, targetFolder.replace(/^\//, "")) : DOWNLOADS_DIR;

    await fsp.mkdir(downloadDir, { recursive: true });

    const filename = objectKey.split("/").pop() || objectKey;

    const filePath = path.join(downloadDir, filename);

    const destFile = fs.createWriteStream(filePath);



    const parsed = new URL(endpointUrl);

    const host = parsed.hostname;

    const dateStr = new Date().toISOString().replace(/[:\-]/g, "").substring(0, 8);

    const amzDate = dateStr + "T000000Z";

    const bodyHash = crypto.createHash("sha256").update("").digest("hex");

    const signedHeaders = "host;x-amz-content-sha256;x-amz-date";

    const pathStr = `/${bucketId}/${encodeURIComponent(objectKey)}`;

    const canonicalRequest = ["GET", pathStr, "", `host:${host}`, `x-amz-content-sha256:${bodyHash}`, `x-amz-date:${amzDate}`, "", signedHeaders, bodyHash].join("\n");

    const region = "us-west-002";

    const service = "s3";

    const credentialScope = `${dateStr}/${region}/${service}/aws4_request`;

    const stringToSign = ["AWS4-HMAC-SHA256", amzDate, credentialScope, crypto.createHash("sha256").update(canonicalRequest).digest("hex")].join("\n");

    function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); }

    const signingKey = hmac(hmac(hmac(hmac(`AWS4${appKey}`, dateStr), region), service), "aws4_request");

    const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex");

    const authorization = `AWS4-HMAC-SHA256 Credential=${keyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;



    await new Promise((resolve, reject) => {

      const opts = {

        hostname: host, port: 443, path: pathStr, method: "GET",

        headers: { Host: host, "x-amz-content-sha256": bodyHash, "x-amz-date": amzDate, Authorization: authorization },

      };

      const req = https.request(opts, (res) => {

        if (res.statusCode >= 200 && res.statusCode < 300) {

          res.pipe(destFile);

          destFile.on("finish", resolve);

        } else {

          let data = "";

          res.on("data", (chunk) => (data += chunk));

          res.on("end", () => reject(new Error(`Download failed: ${res.statusCode} ${data.slice(0, 500)}`)));

        }

      });

      req.on("error", reject);

      req.end();

    });



    return res.json({ ok: true, jobId: `b2_${Date.now()}` });

  } catch (err) {

    return res.status(500).json({ ok: false, error: err.message || "Backblaze download failed" });

  }

});



// ── Generic S3-compatible storage (Qencode media storage, Backblaze B2, or any

// other S3-style bucket). Callers provide the PATH-STYLE API host directly

// (e.g. "us-west.s3.qencode.com" or "s3.us-east-005.backblazeb2.com") β€” we never

// hardcode a provider-specific host, since that breaks every other provider.

// For Qencode specifically, this path-style host is distinct from the

// virtual-hosted CDN/playback host (https://<bucket>.media-storage.<region>.

// qencode.com) used only for direct file reads and signed-URL playback; signing

// against the CDN host looks like an auth/entitlement failure but is actually

// the wrong endpoint entirely. ───────────────────────────────────────────────

// Generate an S3-compatible SigV4 presigned GET URL (credentials in query params,

// no custom headers required β€” works from any browser or HTTP client).

function s3PresignGetUrl(host, pathStr, region, accessKeyId, secretAccessKey, expiresInSeconds) {

  const service = "s3";

  const now = new Date();

  const amzDate = now.toISOString().replace(/[:-]/g, "").replace(/\.\d{3}Z$/, "Z");

  const dateStr = amzDate.slice(0, 8);

  const credentialScope = `${dateStr}/${region}/${service}/aws4_request`;



  // Sorted query params (must NOT include X-Amz-Signature yet)

  const queryParams = {

    "X-Amz-Algorithm":     "AWS4-HMAC-SHA256",

    "X-Amz-Credential":    `${accessKeyId}/${credentialScope}`,

    "X-Amz-Date":          amzDate,

    "X-Amz-Expires":       String(expiresInSeconds || 3600),

    "X-Amz-SignedHeaders": "host",

  };

  const canonicalQueryString = Object.keys(queryParams).sort()

    .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(queryParams[k])}`)

    .join("&");



  const canonicalRequest = [

    "GET",

    pathStr,

    canonicalQueryString,

    `host:${host}\n`,

    "host",

    "UNSIGNED-PAYLOAD",

  ].join("\n");



  const stringToSign = [

    "AWS4-HMAC-SHA256",

    amzDate,

    credentialScope,

    crypto.createHash("sha256").update(canonicalRequest).digest("hex"),

  ].join("\n");



  function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); }

  const dateKey     = hmac(`AWS4${secretAccessKey}`, dateStr);

  const regionKey   = hmac(dateKey, region);

  const serviceKey  = hmac(regionKey, service);

  const signingKey  = hmac(serviceKey, "aws4_request");

  const signature   = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex");



  return `https://${host}${pathStr}?${canonicalQueryString}&X-Amz-Signature=${signature}`;

}



function parseS3ReqParams(q) {

  const bucketName = String(q.bucketName || "").trim();

  const accessKeyId = String(q.accessKeyId || "").trim();

  const secretAccessKey = String(q.secretAccessKey || "").trim();

  const region = String(q.region || "us-west").trim();

  let host = String(q.host || "").trim().replace(/^https?:\/\//, "").replace(/\/+$/, "");

  if (!bucketName || !accessKeyId || !secretAccessKey || !region || !host) return null;

  return { host, bucketName, accessKeyId, secretAccessKey, region };

}



app.post("/api/s3/presign", async (req, res) => {

  const p = parseS3ReqParams(req.body || {});

  const objectKey = String(req.body?.objectKey || "").trim();

  const expiresInSeconds = Number(req.body?.expiresInSeconds) || 3600;

  if (!p || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" });

  try {

    const pathStr = `/${encodeURIComponent(p.bucketName)}/` + objectKey.split("/").map(encodeURIComponent).join("/");

    const url = s3PresignGetUrl(p.host, pathStr, p.region, p.accessKeyId, p.secretAccessKey, expiresInSeconds);

    return res.json({ ok: true, url, expiresInSeconds });

  } catch (err) {

    return res.status(500).json({ ok: false, error: err.message || "Failed to presign URL" });

  }

});



app.get("/api/s3/list", async (req, res) => {

  const p = parseS3ReqParams(req.query);

  if (!p) return res.status(400).json({ ok: false, entries: [], error: "Missing required params (bucketName, accessKeyId, secretAccessKey, region)" });

  const prefix = String(req.query.prefix || "");

  try {

    const pathStr = `/${encodeURIComponent(p.bucketName)}`;

    const queryParams = { "list-type": "2", delimiter: "/" };

    if (prefix) queryParams.prefix = prefix;

    const result = await s3SignedRequest("GET", p.host, pathStr, queryParams, p.region, p.accessKeyId, p.secretAccessKey);

    const entries = parseB2XmlList(result.body);

    return res.json({ ok: true, entries });

  } catch (err) {

    return res.status(500).json({ ok: false, entries: [], error: err.message || "Failed to list bucket" });

  }

});



app.post("/api/s3/upload", upload.single("file"), async (req, res) => {

  const p = parseS3ReqParams(req.body || {});

  if (!p) return res.status(400).json({ ok: false, error: "Missing required params (bucketName, accessKeyId, secretAccessKey, region)" });

  if (!req.file) return res.status(400).json({ ok: false, error: "No file uploaded" });

  try {

    const pathStr = `/${encodeURIComponent(p.bucketName)}${s3KeyPath(req.body?.prefix, req.file.originalname)}`;

    await s3SignedRequest("PUT", p.host, pathStr, null, p.region, p.accessKeyId, p.secretAccessKey, req.file.buffer, req.file.mimetype || "application/octet-stream");

    return res.json({ ok: true });

  } catch (err) {

    return res.status(500).json({ ok: false, error: err.message || "Upload failed" });

  }

});



app.post("/api/s3/download", async (req, res) => {

  const objectKey = String(req.body?.objectKey || "").trim();

  const cfProxyUrl = String(req.body?.cfProxyUrl || "").trim();



  // When a Cloudflare proxy URL is set, we don't need S3 credentials β€” just do a

  // plain HTTPS fetch through the proxy (free, bypasses B2 bandwidth cap).

  // Otherwise fall back to authenticated S3 signed request.

  const p = cfProxyUrl ? { bucketName: String(req.body?.bucketName || "").trim() } : parseS3ReqParams(req.body || {});

  if (!p || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" });

  // Parse S3 creds separately β€” needed even on cfProxyUrl path for fileId HEAD lookup

  const s3ParamsCf = cfProxyUrl ? parseS3ReqParams(req.body || {}) : null;



  let downloadDir, rawFilename, destPath;

  try {

    const targetFolder = req.body?.targetFolder;

    downloadDir = targetFolder ? path.join(DOWNLOADS_DIR, String(targetFolder).replace(/^\//, "")) : DOWNLOADS_DIR;

    await fsp.mkdir(downloadDir, { recursive: true });

    rawFilename = objectKey.split("/").pop() || objectKey;

    ({ fullPath: destPath } = getUniqueFilePath(downloadDir, rawFilename));

  } catch (err) {

    return res.status(500).json({ ok: false, error: err.message || "Setup failed" });

  }



  const filename = rawFilename;

  const displayUrl = cfProxyUrl

    ? `${cfProxyUrl.replace(/\/$/, "")}/${p.bucketName}/${objectKey}`

    : `s3://${req.body?.host || ""}/${p.bucketName}/${objectKey}`;



  const dlJobId = randomId("dl");

  const dlJob = {

    id: dlJobId,

    createdAt: Date.now(),

    status: "running",

    url: displayUrl,

    filename,

    bytesDownloaded: 0,

    totalBytes: 0,

    error: null,

    abortController: new AbortController(),

  };

  downloadJobs.set(dlJobId, dlJob);

  res.json({ ok: true, jobId: dlJobId });



  (async () => {

    try {

      if (cfProxyUrl) {

        // ── Cloudflare proxy path ─────────────────────────────────────────────

        // Prefer native B2 download-by-name via the worker (?b2File= mode).

        // The worker calls b2_authorize_account itself and uses the B2 native

        // download URL β€” no S3 signing, no path-encoding issues for any filename.

        // Fall back to path-based AWS4 signing only when creds are unavailable.

        let fetchUrl, fetchHeaders;

        if (s3ParamsCf) {

          const b2File   = Buffer.from(objectKey).toString("base64");

          const b2Bucket = Buffer.from(s3ParamsCf.bucketName).toString("base64");

          const kid      = Buffer.from(s3ParamsCf.accessKeyId).toString("base64");

          const key      = Buffer.from(s3ParamsCf.secretAccessKey).toString("base64");

          fetchUrl    = `${cfProxyUrl.replace(/\/$/, "")}?b2File=${encodeURIComponent(b2File)}&b2Bucket=${encodeURIComponent(b2Bucket)}&kid=${encodeURIComponent(kid)}&key=${encodeURIComponent(key)}`;

          fetchHeaders = {};

        } else {

          // No creds in request β€” fall back to path-based AWS4 signing

          const encodedKey = objectKey.split("/").map(encodeURIComponent).join("/");

          fetchUrl    = `${cfProxyUrl.replace(/\/$/, "")}/${encodeURIComponent(p.bucketName)}/${encodedKey}`;

          fetchHeaders = {

            "X-B2-Key-Id":  Buffer.from(req.body?.accessKeyId || "").toString("base64"),

            "X-B2-App-Key": Buffer.from(req.body?.secretAccessKey || "").toString("base64"),

            "X-B2-Region":  req.body?.region || "us-east-005",

            "X-B2-Host":    req.body?.host || "s3.us-east-005.backblazeb2.com",

          };

        }



        const fetchRes = await fetch(fetchUrl, {

          signal: dlJob.abortController.signal,

          headers: fetchHeaders,

        });

        if (!fetchRes.ok) {

          const errText = await fetchRes.text().catch(() => "");

          throw new Error(`CF proxy request failed: ${fetchRes.status} ${errText.slice(0, 300)}`);

        }

        const cl = fetchRes.headers.get("content-length");

        if (cl) dlJob.totalBytes = Number(cl);

        const fileStream = fs.createWriteStream(destPath);

        const { Readable } = await import("stream");

        const nodeStream = Readable.fromWeb(fetchRes.body);

        nodeStream.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; });

        await new Promise((resolve, reject) => {

          nodeStream.on("error", reject);

          fileStream.on("error", reject);

          fileStream.on("finish", resolve);

          nodeStream.pipe(fileStream);

        });

      } else {

        // ── Direct S3 signed request path ─────────────────────────────────────

        const pathStr = `/${encodeURIComponent(p.bucketName)}/` + objectKey.split("/").map(encodeURIComponent).join("/");

        const result = await s3SignedRequest("GET", p.host, pathStr, null, p.region, p.accessKeyId, p.secretAccessKey, null, "__STREAM__");

        const cl = result.headers?.["content-length"];

        if (cl) dlJob.totalBytes = Number(cl);

        const fileStream = fs.createWriteStream(destPath);

        result.stream.on("data", (chunk) => { dlJob.bytesDownloaded += chunk.length; });

        await new Promise((resolve, reject) => {

          result.stream.on("error", reject);

          fileStream.on("error", reject);

          fileStream.on("finish", resolve);

          result.stream.pipe(fileStream);

        });

      }

      dlJob.status = "done";

    } catch (err) {

      if (err.name === "AbortError") dlJob.status = "stopped";

      else { dlJob.status = "failed"; dlJob.error = err.message || "Download failed"; }

      try { fs.unlinkSync(destPath); } catch {}

    }

  })();

});



app.post("/api/s3/delete", async (req, res) => {

  const p = parseS3ReqParams(req.body || {});

  const objectKey = String(req.body?.objectKey || "").trim();

  if (!p || !objectKey) return res.status(400).json({ ok: false, error: "Missing required params" });

  try {

    const pathStr = `/${encodeURIComponent(p.bucketName)}/` + objectKey.split("/").map(encodeURIComponent).join("/");

    await s3SignedRequest("DELETE", p.host, pathStr, null, p.region, p.accessKeyId, p.secretAccessKey);

    return res.json({ ok: true });

  } catch (err) {

    return res.status(500).json({ ok: false, error: err.message || "Delete failed" });

  }

});



// ── Stream-compute SHA-256 of a file (no full load into memory) ────────────────

function hashFileStream(filePath) {

  return new Promise((resolve, reject) => {

    const hash = crypto.createHash("sha256");

    fs.createReadStream(filePath)

      .on("data", (chunk) => hash.update(chunk))

      .on("end", () => resolve(hash.digest("hex")))

      .on("error", reject);

  });

}



// ── Streaming S3 PUT with real SHA-256 body hash (no full-file buffering) ──────

function s3StreamUpload(host, pathStr, region, accessKeyId, secretAccessKey, bodyHash, fileStream, fileSize, contentType) {

  return new Promise((resolve, reject) => {

    const now = new Date();

    const amzDate = now.toISOString().replace(/[:-]/g, "").replace(/\.\d{3}Z$/, "Z");

    const dateStr = amzDate.slice(0, 8);



    const signedHeaders = "host;x-amz-content-sha256;x-amz-date";

    const canonicalHeaders = `host:${host}\nx-amz-content-sha256:${bodyHash}\nx-amz-date:${amzDate}\n`;

    const canonicalRequest = ["PUT", pathStr, "", canonicalHeaders, signedHeaders, bodyHash].join("\n");



    const credentialScope = `${dateStr}/${region}/s3/aws4_request`;

    const stringToSign = [

      "AWS4-HMAC-SHA256", amzDate, credentialScope,

      crypto.createHash("sha256").update(canonicalRequest).digest("hex"),

    ].join("\n");



    function hmac(key, str) { return crypto.createHmac("sha256", key).update(str).digest(); }

    const sig = crypto.createHmac("sha256",

      hmac(hmac(hmac(hmac(`AWS4${secretAccessKey}`, dateStr), region), "s3"), "aws4_request")

    ).update(stringToSign).digest("hex");



    const authorization = `AWS4-HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${sig}`;



    const req2 = https.request({

      hostname: host, port: 443, path: pathStr, method: "PUT",

      headers: {

        Host: host,

        "x-amz-content-sha256": bodyHash,

        "x-amz-date": amzDate,

        Authorization: authorization,

        "Content-Length": fileSize,

        "Content-Type": contentType || "application/octet-stream",

      },

    }, (res2) => {

      let data = "";

      res2.on("data", (c) => (data += c));

      res2.on("end", () => {

        if (res2.statusCode >= 200 && res2.statusCode < 300) resolve({ status: res2.statusCode });

        else reject(new Error(`S3 upload failed: ${res2.statusCode} ${data.slice(0, 500)}`));

      });

    });

    req2.on("error", reject);

    fileStream.pipe(req2);

  });

}



// ── S3 multipart upload via AWS SDK (for files > 100 MB) ──────────────────────

// Uses @aws-sdk/client-s3 which handles SigV4 signing correctly for all

// S3-compatible providers including Backblaze B2.

const MULTIPART_THRESHOLD = 100 * 1024 * 1024;  // 100 MB β€” use single PUT below this

const MULTIPART_PART_SIZE  =  50 * 1024 * 1024;  // 50 MB per part (B2 minimum is 5 MB)



async function s3MultipartUpload(host, pathStr, region, accessKeyId, secretAccessKey, filePath, fileSize) {

  // pathStr is "/{bucket}/{key}" β€” split into bucket and key for the SDK

  const withoutLeadingSlash = pathStr.replace(/^\//, "");

  const slashIdx = withoutLeadingSlash.indexOf("/");

  const bucket = decodeURIComponent(withoutLeadingSlash.slice(0, slashIdx));

  const key    = withoutLeadingSlash.slice(slashIdx + 1).split("/").map(decodeURIComponent).join("/");



  const client = new S3Client({

    endpoint: `https://${host}`,

    region,

    credentials: { accessKeyId, secretAccessKey },

    forcePathStyle: true,   // required for Backblaze B2 and most non-AWS S3-compatible hosts

  });



  // Step 1 β€” CreateMultipartUpload

  const { UploadId } = await client.send(new CreateMultipartUploadCommand({

    Bucket: bucket,

    Key: key,

    ContentType: "application/octet-stream",

  }));

  if (!UploadId) throw new Error("CreateMultipartUpload: no UploadId returned");



  const numParts = Math.ceil(fileSize / MULTIPART_PART_SIZE);

  const parts = [];



  try {

    // Step 2 β€” UploadPart Γ— N

    for (let i = 0; i < numParts; i++) {

      const partNumber = i + 1;

      const start = i * MULTIPART_PART_SIZE;

      const end   = Math.min(start + MULTIPART_PART_SIZE, fileSize) - 1;

      const partSize = end - start + 1;



      const { ETag } = await client.send(new UploadPartCommand({

        Bucket: bucket,

        Key: key,

        UploadId,

        PartNumber: partNumber,

        ContentLength: partSize,

        Body: fs.createReadStream(filePath, { start, end }),

      }));

      if (!ETag) throw new Error(`UploadPart ${partNumber}: no ETag in response`);

      parts.push({ PartNumber: partNumber, ETag });

    }

  } catch (err) {

    // Best-effort abort so orphaned parts don't accumulate in the bucket

    client.send(new AbortMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId })).catch(() => {});

    throw err;

  }



  // Step 3 β€” CompleteMultipartUpload

  await client.send(new CompleteMultipartUploadCommand({

    Bucket: bucket,

    Key: key,

    UploadId,

    MultipartUpload: { Parts: parts },

  }));

}



// ── Upload a local file (by job ID or file ID) directly to S3 ─────────────────

app.post("/api/s3/upload-local", async (req, res) => {

  const { jobId, fileId, prefix, ...rest } = req.body || {};

  const p = parseS3ReqParams(rest);

  if (!p) return res.status(400).json({ ok: false, error: "Missing S3 params (bucketName, accessKeyId, secretAccessKey, region, host)" });



  let filePath;

  let filename;

  if (jobId) {

    const job = jobs.get(String(jobId));

    if (!job) return res.status(404).json({ ok: false, error: "Job not found" });

    if (!job.outputFilename) return res.status(400).json({ ok: false, error: "Job output filename not yet known (job may still be running)" });

    filePath = path.join(ENCODED_DIR, job.outputFilename);

    filename = job.outputFilename;

  } else if (fileId) {

    const info = resolveFileFromId(decodeURIComponent(String(fileId)));

    if (!info) return res.status(400).json({ ok: false, error: "Invalid file id" });

    filePath = info.filePath;

    filename = info.name;

  } else {

    return res.status(400).json({ ok: false, error: "jobId or fileId is required" });

  }



  let stat;

  try { stat = await fsp.stat(filePath); } catch {

    return res.status(404).json({ ok: false, error: "File not found on disk" });

  }



  try {

    const pathStr = `/${encodeURIComponent(p.bucketName)}${s3KeyPath(prefix || "", filename)}`;

    if (stat.size > MULTIPART_THRESHOLD) {

      // Large file: use multipart upload (CreateMultipartUpload β†’ UploadPart Γ— N β†’ Complete)

      await s3MultipartUpload(

        p.host, pathStr, p.region, p.accessKeyId, p.secretAccessKey,

        filePath, stat.size

      );

    } else {

      // Small file: single streaming PUT (existing path)

      const bodyHash = await hashFileStream(filePath);

      const fileStream = fs.createReadStream(filePath);

      await s3StreamUpload(p.host, pathStr, p.region, p.accessKeyId, p.secretAccessKey, bodyHash, fileStream, stat.size);

    }

    return res.json({ ok: true, filename });

  } catch (err) {

    return res.status(500).json({ ok: false, error: err.message || "Upload failed" });

  }

});



// ── Trim Segments (Simple trim with saved crop settings) ─────────────────────

app.post("/api/trim-segments", async (req, res) => {

  const { fileId, segments } = req.body || {};

  if (!fileId || !segments || !Array.isArray(segments) || segments.length === 0) {

    return res.status(400).json({ error: "fileId and segments (non-empty array) are required" });

  }



  const info = resolveFileFromId(String(fileId));

  if (!info) return res.status(400).json({ error: "Invalid file id" });

  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }



  // Validate segments

  for (const seg of segments) {

    const startSec = parseLooseClockToSeconds(String(seg.start));

    const endSec = parseLooseClockToSeconds(String(seg.end));

    if (startSec == null || endSec == null || endSec <= startSec) {

      return res.status(400).json({ error: "Invalid segment times" });

    }

  }



  // Save output to same folder as source

  const sourceDir = path.dirname(info.filePath);

  const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR;

  const relOutDir = path.relative(base, sourceDir);

  const outputFolder = relOutDir ? `/${relOutDir}` : "/";



  // Calculate total duration for progress

  const totalDuration = segments.reduce((sum, seg) => {

    return sum + (parseLooseClockToSeconds(String(seg.end)) - parseLooseClockToSeconds(String(seg.start)));

  }, 0);



  const jobId = randomId("trim_seg");

  const job = {

    id: jobId,

    createdAt: Date.now(),

    status: "running",

    _process: null,

    outputFolder,

    outputSource: info.source,

    settings: {

      inputFilename: info.name,

      segmentCount: segments.length,

      type: "trim_segments"

    },

    progress: { percent: 0, fps: 0, etaSeconds: totalDuration, sizeOutBytes: 0, log: ["Starting segment trimming..."] },

  };

  jobs.set(jobId, job);



  // Process each segment

  const outputFiles = [];

  let processedSegments = 0;



  try {

    for (let i = 0; i < segments.length; i++) {

      const seg = segments[i];

      const startSec = parseLooseClockToSeconds(String(seg.start));

      const endSec = parseLooseClockToSeconds(String(seg.end));

      const duration = endSec - startSec;



      // Get unique output filename

      const { name: outName, fullPath: outPath } = getUniqueFilePath(sourceDir, String(seg.outputFilename));



      const segJob = jobs.get(jobId);

      if (segJob) {

        segJob.progress.log.push(`Trimming segment ${i + 1}/${segments.length}: ${seg.start} - ${seg.end}`);

      }



      // Use stream copy for fast, lossless trimming

      const args = [

        "-y",

        "-ss", String(startSec),

        "-t", String(duration),

        "-i", info.filePath,

        "-c", "copy",  // Stream copy - fast and lossless

        "-avoid_negative_ts", "make_zero",

        outPath

      ];



      await new Promise((resolve, reject) => {

        const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });



        ffmpeg.stderr.on("data", (chunk) => {

          const line = chunk.toString();

          const latest = jobs.get(jobId);

          if (!latest) return;

          latest.progress.log.push(line.trim());

          if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500);

        });



        ffmpeg.on("error", reject);

        ffmpeg.on("close", (code) => {

          if (code === 0) resolve();

          else reject(new Error(`ffmpeg exited with code ${code} for segment ${i + 1}`));

        });

      });



      // Save crop settings to a JSON file alongside the trimmed segment

      if (seg.cropSettings && seg.cropSettings.enabled) {

        const cropSettingsPath = outPath + ".crop.json";

        const cropData = {

          cropEnabled: true,

          cropLeft: seg.cropSettings.left || 0,

          cropRight: seg.cropSettings.right || 0,

          cropTop: seg.cropSettings.top || 0,

          cropBottom: seg.cropSettings.bottom || 0,

          sourceFile: info.name,

          segmentStart: seg.start,

          segmentEnd: seg.end,

          createdAt: Date.now()

        };

        await fsp.writeFile(cropSettingsPath, JSON.stringify(cropData, null, 2));

        

        const latest = jobs.get(jobId);

        if (latest) {

          latest.progress.log.push(`Saved crop settings for segment ${i + 1}`);

        }

      }



      outputFiles.push(outName);

      processedSegments++;



      // Update progress

      const latest = jobs.get(jobId);

      if (latest) {

        latest.progress.percent = Math.round((processedSegments / segments.length) * 100);

      }

    }



    const final = jobs.get(jobId);

    if (final) {

      final.status = "done";

      final.progress.percent = 100;

      final.progress.etaSeconds = 0;

      final.progress.log.push(`Trimmed ${segments.length} segment(s) successfully.`);

      final.progress.log.push(`Output files: ${outputFiles.join(", ")}`);

      final.outputFilename = outputFiles.join(", ");

      persistJobHistory();

    }



    const { _process: _p, ...safeJob } = job;

    return res.json({ job: safeJob, outputFiles });



  } catch (err) {

    const failed = jobs.get(jobId);

    if (failed) {

      failed.status = "failed";

      failed.progress.log.push(`Error: ${err.message}`);

      persistJobHistory();

    }

    return res.status(500).json({ error: err.message });

  }

});



// ── Trim + Encode + Merge ──────────────────────────────────────────────────────

// Each segment is trimmed + encoded (with its own crop settings) in one ffmpeg pass,

// then all encoded segments are concatenated into a single output file.

app.post("/api/trim-encode-merge", async (req, res) => {

  const { fileId, segments, encodeSettings } = req.body || {};

  if (!fileId || !Array.isArray(segments) || segments.length === 0) {

    return res.status(400).json({ error: "fileId and segments (non-empty array) are required" });

  }



  const info = resolveFileFromId(String(fileId));

  if (!info) return res.status(400).json({ error: "Invalid file id" });

  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }



  for (const seg of segments) {

    const startSec = parseLooseClockToSeconds(String(seg.start));

    const endSec = parseLooseClockToSeconds(String(seg.end));

    if (startSec == null || endSec == null || endSec <= startSec) {

      return res.status(400).json({ error: `Invalid times for segment: ${seg.start} β†’ ${seg.end}` });

    }

  }



  const totalDuration = segments.reduce((sum, seg) => {

    return sum + (parseLooseClockToSeconds(String(seg.end)) - parseLooseClockToSeconds(String(seg.start)));

  }, 0);



  const enc = encodeSettings || {};

  const baseExt = enc.codec === "av1" ? ".mkv" : enc.codec === "h265" ? ".mkv" : ".mp4";

  const baseName = info.name.replace(/\.[^.]+$/, "");

  const desiredOutName = `${baseName}_encoded_merged${baseExt}`;

  const { name: outName, fullPath: outPath } = getUniqueFilePath(ENCODED_DIR, desiredOutName);



  const jobId = randomId("tem");

  const job = {

    id: jobId,

    createdAt: Date.now(),

    startedAt: Date.now(),

    status: "running",

    _process: null,

    outputFolder: "/",

    outputSource: "encoded",

    batchIndex: null,

    batchTotal: null,

    settings: {

      type: "trim_encode_merge",

      inputFilename: info.name,

      outputFilename: outName,

      segmentCount: segments.length,

      codec: enc.codec || "h264",

    },

    progress: {

      percent: 0, fps: 0, etaSeconds: totalDuration * 5,

      sizeOutBytes: 0, speed: 0, bitrateKbps: 0,

      log: [`Starting trim+encode+merge: ${segments.length} segment(s)...`],

    },

  };

  jobs.set(jobId, job);

  res.json({ ok: true, jobId });



  let tempDir = null;

  (async () => {

    try {

      tempDir = path.join(os.tmpdir(), `tem-${jobId}`);

      await fsp.mkdir(tempDir, { recursive: true });



      const segPaths = [];



      for (let i = 0; i < segments.length; i++) {

        const seg = segments[i];

        const startSec = parseLooseClockToSeconds(String(seg.start));

        const endSec = parseLooseClockToSeconds(String(seg.end));



        const segOut = path.join(tempDir, `seg_${String(i).padStart(3, "0")}${baseExt}`);



        // Merge per-segment crop into encode settings

        const segSettings = {

          codec: enc.codec || "h264",

          mode: enc.mode || "crf-1pass",

          crf: enc.crf ?? (enc.codec === "av1" ? 45 : enc.codec === "h265" ? 28 : 23),

          videoBitrateKbps: enc.videoBitrateKbps || 2000,

          audioBitrateKbps: enc.audioBitrateKbps || 96,

          resolution: enc.resolution || "original",

          frameRate: "original",          // prevent buildEncodeArgs pushing "-r undefined"

          sameAsOriginalAudio: Boolean(enc.sameAsOriginalAudio),

          sameAsOriginalVideo: false,     // always re-encode so crop filter applies

          h26xPreset: enc.h26xPreset || "medium",

          preset: enc.av1Preset ?? enc.preset ?? 5,   // SVT-AV1 preset (modal sends av1Preset)

          aqMode: enc.aqMode ?? 0,

          tiles: enc.tiles ?? "0",

          startTime: seg.start,

          endTime: seg.end,

          cropEnabled: Boolean(seg.cropEnabled),

          cropLeft: Number(seg.cropLeft) || 0,

          cropRight: Number(seg.cropRight) || 0,

          cropTop: Number(seg.cropTop) || 0,

          cropBottom: Number(seg.cropBottom) || 0,

        };



        const args = buildEncodeArgs(segSettings, info.filePath, segOut);



        const current = jobs.get(jobId);

        if (current) {

          current.progress.log.push(

            `[Seg ${i + 1}/${segments.length}] Encoding ${seg.start}β†’${seg.end}${seg.cropEnabled ? " + crop" : ""}…`

          );

        }



        const completedDuration = segments.slice(0, i).reduce(

          (sum, s) => sum + (parseLooseClockToSeconds(String(s.end)) - parseLooseClockToSeconds(String(s.start))), 0

        );



        await new Promise((resolve, reject) => {

          const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });

          job._process = ffmpeg;



          ffmpeg.stderr.on("data", (chunk) => {

            const line = chunk.toString();

            const cur = jobs.get(jobId);

            if (!cur) return;

            cur.progress.log.push(line.trim());

            if (cur.progress.log.length > 600) cur.progress.log = cur.progress.log.slice(-600);

            const timeMatch = line.match(/time=([0-9:.]+)/);

            if (timeMatch) {

              const secs = parseFfmpegTimeToSeconds(timeMatch[1]);

              const totalDone = completedDuration + secs;

              cur.progress.percent = Math.min(93, (totalDone / totalDuration) * 93);

              const elapsed = (Date.now() - job.startedAt) / 1000;

              const speed = elapsed > 0 ? totalDone / elapsed : 0;

              cur.progress.etaSeconds = speed > 0 ? Math.max(0, (totalDuration - totalDone) / speed) : 0;

            }

            const fpsMatch = line.match(/fps=\s*([0-9.]+)/);

            if (fpsMatch) cur.progress.fps = Number(fpsMatch[1]) || 0;

            const bitrateMatch = line.match(/bitrate=\s*([0-9.]+)kbits\/s/);

            if (bitrateMatch) cur.progress.bitrateKbps = Number(bitrateMatch[1]) || 0;

          });



          ffmpeg.on("error", reject);

          ffmpeg.on("close", (code) => {

            job._process = null;

            const cur = jobs.get(jobId);

            if (cur?.status === "stopped") return resolve(null);

            if (code === 0) resolve(null);

            else reject(new Error(`ffmpeg exited with code ${code} for segment ${i + 1}`));

          });

        });



        if (jobs.get(jobId)?.status === "stopped") throw new Error("__stopped__");



        segPaths.push(segOut);

        const cur2 = jobs.get(jobId);

        if (cur2) cur2.progress.log.push(`[Seg ${i + 1}/${segments.length}] Done.`);

      }



      // Merge encoded segments

      const cur3 = jobs.get(jobId);

      if (cur3) { cur3.progress.percent = 95; cur3.progress.log.push(`Merging ${segPaths.length} segment(s)…`); }



      if (segPaths.length === 1) {

        await safeMoveFile(segPaths[0], outPath);

      } else {

        const concatList = path.join(tempDir, "concat.txt");

        await fsp.writeFile(concatList, segPaths.map(p => `file '${p.replace(/'/g, "'\\''")}'`).join("\n"), "utf8");
        const mergeArgs = ["-y", "-f", "concat", "-safe", "0", "-i", concatList, "-c", "copy", outPath];
        await new Promise((resolve, reject) => {
          const ffmpeg = spawn("ffmpeg", mergeArgs, { stdio: ["pipe", "ignore", "pipe"] });
          job._process = ffmpeg;
          ffmpeg.stderr.on("data", (chunk) => {
            const cur = jobs.get(jobId);
            if (cur) { cur.progress.log.push(chunk.toString().trim()); }
          });
          ffmpeg.on("error", reject);
          ffmpeg.on("close", (code) => {
            job._process = null;
            if (code === 0) resolve(null);
            else reject(new Error(`Merge failed with code ${code}`));
          });
        });
      }

      const final = jobs.get(jobId);
      if (final) {
        final.status = "done";
        final.progress.percent = 100;
        final.progress.etaSeconds = 0;
        try { const st = await fsp.stat(outPath); final.progress.sizeOutBytes = st.size; } catch { /* ignore */ }
        final.progress.log.push(`Done! Output: ${outName}`);
        persistJobHistory();
      }
    } catch (err) {
      const failed = jobs.get(jobId);
      if (failed) {
        if (err.message !== "__stopped__") {
          failed.status = "failed";
          failed.progress.log.push(`Error: ${err.message}`);
        }
        persistJobHistory();
      }
    } finally {
      if (tempDir) await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
    }
  })();
});

// ── Advanced Trim & Crop ──────────────────────────────────────────────────────
app.post("/api/advanced-trim-crop", async (req, res) => {
  const { fileId, segments, outputFilename, transitionSmoothness } = req.body || {};
  if (!fileId || !segments || !Array.isArray(segments) || segments.length === 0 || !outputFilename) {
    return res.status(400).json({ error: "fileId, segments (non-empty array), and outputFilename are required" });
  }

  const info = resolveFileFromId(String(fileId));
  if (!info) return res.status(400).json({ error: "Invalid file id" });
  try { await fsp.access(info.filePath); } catch { return res.status(404).json({ error: "File not found" }); }

  // Validate segments
  for (const seg of segments) {
    const startSec = parseLooseClockToSeconds(String(seg.start));
    const endSec = parseLooseClockToSeconds(String(seg.end));
    if (startSec == null || endSec == null || endSec <= startSec) {
      return res.status(400).json({ error: "Invalid segment times" });
    }
    if (seg.crop) {
      const { left, right, top, bottom } = seg.crop;
      if (left < 0 || right < 0 || top < 0 || bottom < 0 || left > 45 || right > 45 || top > 45 || bottom > 45) {
        return res.status(400).json({ error: "Crop values must be between 0 and 45" });
      }
    }
  }

  // Save output to same folder as source
  const sourceDir = path.dirname(info.filePath);
  const { name: outName, fullPath: outPath } = getUniqueFilePath(sourceDir, String(outputFilename));

  const base = info.source === "downloaded" ? DOWNLOADS_DIR : ENCODED_DIR;
  const relOutDir = path.relative(base, sourceDir);
  const outputFolder = relOutDir ? `/${relOutDir}` : "/";

  // Calculate total duration
  const totalDuration = segments.reduce((sum, seg) => {
    return sum + (parseLooseClockToSeconds(String(seg.end)) - parseLooseClockToSeconds(String(seg.start)));
  }, 0);

  const transitionMs = Math.min(Math.max(Number(transitionSmoothness) || 300, 100), 1000); // 100-1000ms

  const jobId = randomId("adv_trim_crop");
  const job = {
    id: jobId,
    createdAt: Date.now(),
    status: "running",
    _process: null,
    outputFolder,
    outputSource: info.source,
    settings: {
      inputFilename: info.name,
      outputFilename: outName,
      segments: segments.map(s => ({
        start: s.start,
        end: s.end,
        crop: s.crop || null,
        transitionDuration: s.transitionDuration || transitionMs
      })),
      type: "advanced_trim_crop"
    },
    progress: { percent: 0, fps: 0, etaSeconds: totalDuration, sizeOutBytes: 0, log: ["Starting advanced trim & crop..."] },
  };
  jobs.set(jobId, job);

  // Build FFmpeg concat file with per-segment filtering
  const concatDir = path.join(os.tmpdir(), `adv_trim_crop_${jobId}`);
  await fsp.mkdir(concatDir, { recursive: true });

  const segmentFiles = [];
  let processedSeconds = 0;

  try {
    for (let i = 0; i < segments.length; i++) {
      const seg = segments[i];
      const startSec = parseLooseClockToSeconds(String(seg.start));
      const endSec = parseLooseClockToSeconds(String(seg.end));
      const duration = endSec - startSec;
      const segOutput = path.join(concatDir, `segment_${String(i).padStart(3, "0")}.mkv`);

      const args = ["-y", "-ss", String(startSec), "-t", String(duration), "-i", info.filePath];

      // Build filter chain
      const filters = [];
      if (seg.crop) {
        const { left = 0, right = 0, top = 0, bottom = 0 } = seg.crop;
        const cropW = 100 - left - right;
        const cropH = 100 - top - bottom;
        const cropX = left;
        const cropY = top;
        filters.push(`crop=iw*${Math.max(0, cropW) / 100}:ih*${Math.max(0, cropH) / 100}:iw*${Math.max(0, cropX) / 100}:ih*${Math.max(0, cropY) / 100}`);
      }

      args.push("-pix_fmt", "yuv420p");
      args.push("-c:v", "libx264", "-preset", "fast", "-crf", "23");
      args.push("-c:a", "libopus", "-b:a", "96k");

      if (filters.length > 0) {
        args.push("-vf", filters.join(","));
      }

      args.push(segOutput);

      const segJob = jobs.get(jobId);
      if (segJob) {
        segJob.progress.log.push(`Processing segment ${i + 1}/${segments.length}: ${seg.start} - ${seg.end}`);
      }

      await new Promise((resolve, reject) => {
        const ffmpeg = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });

        ffmpeg.stderr.on("data", (chunk) => {
          const line = chunk.toString();
          const latest = jobs.get(jobId);
          if (!latest) return;
          latest.progress.log.push(line.trim());
          if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500);

          const timeMatch = line.match(/time=([0-9:.]+)/);
          if (timeMatch) {
            const secs = parseFfmpegTimeToSeconds(timeMatch[1]);
            if (totalDuration > 0) {
              latest.progress.percent = Math.min(99.5, ((processedSeconds + secs) / totalDuration) * 100);
              latest.progress.etaSeconds = Math.max(0, totalDuration - (processedSeconds + secs));
            }
          }
        });

        ffmpeg.on("error", reject);
        ffmpeg.on("close", (code) => {
          if (code === 0) resolve();
          else reject(new Error(`ffmpeg exited with code ${code} processing segment ${i + 1}`));
        });
      });

      processedSeconds += duration;
      segmentFiles.push(segOutput);
    }

    // Create concat file
    const concatFilePath = path.join(concatDir, "concat_list.txt");
    const concatContent = segmentFiles.map(f => `file '${f.replace(/'/g, "'\\''")}'`).join("\n");

    await fsp.writeFile(concatFilePath, concatContent, "utf8");



    // Join segments using concat demuxer

    const concatArgs = ["-y", "-f", "concat", "-safe", "0", "-i", concatFilePath,

      "-c:v", "libx264", "-preset", "fast", "-crf", "23",

      "-c:a", "libopus", "-b:a", "96k",

      "-pix_fmt", "yuv420p"];



    // Add transition crossfade if we have multiple segments

    if (segmentFiles.length > 1) {

      // Use ffmpeg crossfade filters between segments

      const transitionSeconds = transitionMs / 1000;

      const crossfadeArgs = ["-y"];



      for (let i = 0; i < segmentFiles.length; i++) {

        crossfadeArgs.push("-i", segmentFiles[i]);

      }



      // Build filter complex for crossfade

      const filterParts = [];

      let prevLabel = "0:v:0";

      let prevALabel = "0:a:0";



      for (let i = 1; i < segmentFiles.length; i++) {

        const offset = duration - transitionSeconds * (i);

        const label = `v${i}`;

        const aLabel = `a${i}`;

        filterParts.push(

          `[${prevLabel}][${i}:v:0]xfade=transition=fade:offset=${Math.max(0, offset)}:duration=${transitionSeconds}[${label}]`,

          `[${prevALabel}][${i}:a:0]acrossfade=d=${transitionSeconds}:c1=tri:curve1=nofade:curve2=nofade[${aLabel}]`

        );

        prevLabel = label;

        prevALabel = aLabel;

      }



      if (filterParts.length > 0) {

        crossfadeArgs.push("-filter_complex", filterParts.join("; "));

        crossfadeArgs.push("-map", `[${prevLabel}]`);

        crossfadeArgs.push("-map", `[${prevALabel}]`);

      } else {

        crossfadeArgs.push("-map", "0:v:0");

        crossfadeArgs.push("-map", "0:a:0");

      }



      crossfadeArgs.push("-c:v", "libx264", "-preset", "fast", "-crf", "23");

      crossfadeArgs.push("-c:a", "libopus", "-b:a", "96k");

      crossfadeArgs.push("-pix_fmt", "yuv420p");

      crossfadeArgs.push(outPath);



      const latest = jobs.get(jobId);

      if (latest) {

        latest.progress.log.push("Applying smooth transitions between segments...");

      }



      await new Promise((resolve, reject) => {

        const ffmpeg = spawn("ffmpeg", crossfadeArgs, { stdio: ["pipe", "ignore", "pipe"] });



        ffmpeg.stderr.on("data", (chunk) => {

          const line = chunk.toString();

          const latest = jobs.get(jobId);

          if (!latest) return;

          latest.progress.log.push(line.trim());

          if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500);

        });



        ffmpeg.on("error", reject);

        ffmpeg.on("close", (code) => {

          if (code === 0) resolve();

          else reject(new Error(`ffmpeg exited with code ${code} during transition pass`));

        });

      });

    } else {

      // Single segment - just copy

      const latest = jobs.get(jobId);

      if (latest) {

        latest.progress.log.push("Processing single segment...");

      }



      await new Promise((resolve, reject) => {

        const ffmpeg = spawn("ffmpeg", concatArgs, { stdio: ["pipe", "ignore", "pipe"] });



        ffmpeg.stderr.on("data", (chunk) => {

          const line = chunk.toString();

          const latest = jobs.get(jobId);

          if (!latest) return;

          latest.progress.log.push(line.trim());

          if (latest.progress.log.length > 500) latest.progress.log = latest.progress.log.slice(-500);

        });



        ffmpeg.on("error", reject);

        ffmpeg.on("close", (code) => {

          if (code === 0) resolve();

          else reject(new Error(`ffmpeg exited with code ${code}`));

        });

      });

    }



    // Cleanup temp files

    await fsp.rm(concatDir, { recursive: true, force: true }).catch(() => {});



    const final = jobs.get(jobId);

    if (final) {

      final.status = "done";

      final.progress.percent = 100;

      final.progress.etaSeconds = 0;

      try {

        const st = await fsp.stat(outPath);

        final.progress.sizeOutBytes = st.size;

      } catch {}

      final.progress.log.push(`Advanced trim & crop completed. Output: ${outName}`);

      final.outputFilename = outName;

      persistJobHistory();

    }

  } catch (err) {

    await fsp.rm(concatDir, { recursive: true, force: true }).catch(() => {});

    const failed = jobs.get(jobId);

    if (failed) {

      failed.status = "failed";

      failed.progress.log.push(`Error: ${err.message}`);

      persistJobHistory();

    }

    // Don't send error here since we already sent the response

    return;

  }



  const { _process: _p, ...safeJob } = job;

  return res.json({ job: safeJob });

});



// ── Static / SPA fallback ──────────────────────────────────────────────────────

if (fs.existsSync(distDir)) {

  app.use(express.static(distDir));

  app.use((req, res, next) => {

    if (req.path.startsWith("/api")) return next();

    res.sendFile(path.join(distDir, "index.html"));

  });

} else {

  console.warn(`[warn] dist/ not found at ${distDir}. Run "npm run build" first.`);

}



app.listen(PORT, HOST, () => {

  console.log(`Server running on http://${HOST}:${PORT}`);

  console.log(`downloads: ${DOWNLOADS_DIR}`);

  console.log(`encoded:   ${ENCODED_DIR}`);

});