"""Deploy rollover button fix to server"""
import paramiko
import os

# Server configuration
SERVER = '162.240.14.22'
USERNAME = 'xygbfpsg'
PASSWORD = 'L$w2DJaAyh1('
REMOTE_PATH = '/home/xygbfpsg/loanapp.grazurifinance.co.ke'

def deploy():
    print("🚀 Deploying rollover button fix to server...")
    print("=" * 60)
    
    try:
        # Create SSH client
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        
        print(f"📡 Connecting to {SERVER}...")
        ssh.connect(SERVER, username=USERNAME, password=PASSWORD)
        print("✅ Connected successfully!\n")
        
        # Create SFTP client
        sftp = ssh.open_sftp()
        
        # Files to upload
        files_to_upload = [
            ('templates/loans/loans_table.html', 'templates/loans/loans_table.html'),
        ]
        
        print("📦 Uploading files...")
        for local_file, remote_file in files_to_upload:
            local_path = os.path.join(os.getcwd(), local_file)
            remote_path = f"{REMOTE_PATH}/{remote_file}"
            
            if os.path.exists(local_path):
                print(f"  Uploading {local_file}...")
                sftp.put(local_path, remote_path)
                print(f"  ✅ Uploaded {local_file}")
            else:
                print(f"  ⚠️ Local file not found: {local_file}")
        
        print("\n🔄 Restarting application...")
        stdin, stdout, stderr = ssh.exec_command(f'cd {REMOTE_PATH} && touch tmp/restart.txt')
        stdout.channel.recv_exit_status()
        print("✅ Application restarted")
        
        print("\n" + "=" * 60)
        print("✅ Deployment completed successfully!")
        print("\nChanges:")
        print("  - Updated loans_table.html to show Record Payment button for:")
        print("    * Loans with status='active'")
        print("    * Loans with status='rolled_over'")
        print("    * Loans with is_rolled_over=True (any status)")
        print("  - Rollover button now only shows for non-rolled active loans")
        print("\n📝 Test by:")
        print("  1. Navigate to the loans list page")
        print("  2. Find Joshua's rolled-over loan")
        print("  3. Verify the Record Payment button (💵) is visible")
        print("  4. Verify the Rollover button (↷) is NOT visible for rolled loans")
        
        sftp.close()
        ssh.close()
        
    except Exception as e:
        print(f"\n❌ Deployment failed: {str(e)}")
        raise

if __name__ == '__main__':
    deploy()
