import paramiko
import os
import sys

# CONFIG
HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
REMOTE_BASE = "/var/www/html/repondeur_mail_grok"
LOCAL_BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

FILES_TO_DEPLOY = [
    "scripts/diagnose_presta.php"
]

def run_sudo(ssh, command, password):
    """Run command with sudo"""
    cmd = f"echo '{password}' | sudo -S {command}"
    stdin, stdout, stderr = ssh.exec_command(cmd)
    return stdout.read().decode(), stderr.read().decode()

def main():
    print(f"Connecting to {HOST}...")
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        
        # 1. Prepare Permissions (Sudo)
        # Not strictly needed if we just dump to existing scripts folder but let's be safe
        run_sudo(ssh, f"chown -R {USER}:{USER} {REMOTE_BASE}", PASS)
        
        sftp = ssh.open_sftp()
        
        # Upload
        for rel_path in FILES_TO_DEPLOY:
            local_path = os.path.join(LOCAL_BASE, rel_path)
            remote_path = os.path.join(REMOTE_BASE, rel_path)
            print(f"Uploading {rel_path}...")
            sftp.put(local_path, remote_path)
            
        # 2. Restore Permissions
        run_sudo(ssh, f"chown -R www-data:www-data {REMOTE_BASE}/data", PASS)

        # Run Diag
        print("Running diagnose_presta.php remotely...")
        stdin, stdout, stderr = ssh.exec_command(f"php {REMOTE_BASE}/scripts/diagnose_presta.php")
        print(stdout.read().decode())
        print(stderr.read().decode())

        ssh.close()

    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
