"""Deploy button fixes to both loan list and detail pages"""
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 Record Payment button fixes 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, timeout=30)
        print("✅ Connected successfully!\n")
        
        # Create SFTP client
        sftp = ssh.open_sftp()
        
        # Files to upload
        files_to_upload = [
            ('templates/loans/loan_detail.html', 'templates/loans/loan_detail.html'),
            ('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("\n📄 loan_detail.html:")
        print("  - Record Payment button now shows for:")
        print("    * status == 'active' OR")
        print("    * status == 'rolled_over' OR")
        print("    * is_rolled_over == True")
        print("  - Rollover button only shows for non-rolled active loans")
        print("\n📄 loans_table.html:")
        print("  - Same logic applied to loans list page")
        print("\n📝 Test by:")
        print("  1. Navigate to loan 18112026-000012")
        print("  2. Verify 'Record Payment' button now appears")
        print("  3. Verify 'Request Rollover' button does NOT appear (already rolled)")
        
        sftp.close()
        ssh.close()
        
    except Exception as e:
        print(f"\n❌ Deployment failed: {str(e)}")
        import traceback
        traceback.print_exc()
        raise

if __name__ == '__main__':
    deploy()
