import paramiko
import os
import sys

# CONFIG
HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
REMOTE_BASE = "/var/www/html"
REMOTE_DIR = f"{REMOTE_BASE}/repondeur_mail_grok"
LOCAL_DIR = os.getcwd()

def run_sudo(ssh, command, password):
    """Run command with sudo"""
    cmd = f"echo '{password}' | sudo -S {command}"
    stdin, stdout, stderr = ssh.exec_command(cmd)
    out = stdout.read().decode()
    err = stderr.read().decode()
    if err and "password" not in err.lower(): # Sudo prompt often prints to stderr
         # Ignorer 'sudo: unable to resolve host' warnings
         pass
    return out, err

def create_remote_dir_recursive(sftp, remote_path):
    """Recursively create remote directories via SFTP (if permissions allow)"""
    # Now unused because we use sudo mkdir
    pass

def upload_dir(sftp, local_dir, remote_dir):
    for root, dirs, files in os.walk(local_dir):
        rel_path = os.path.relpath(root, local_dir)
        if rel_path == ".":
            current_remote = remote_dir
        else:
            current_remote = os.path.join(remote_dir, rel_path)
            try:
                sftp.stat(current_remote)
            except IOError:
                sftp.mkdir(current_remote)
                print(f"mkdir {current_remote}")

        for file in files:
            if file.startswith('.'): continue
            if rel_path == "." and file == "deploy_vps.py": continue
            
            local_file = os.path.join(root, file)
            remote_file = os.path.join(current_remote, file)
            
            print(f"Uploading {local_file} -> {remote_file}")
            try:
                sftp.put(local_file, remote_file)
            except Exception as e:
                print(f"Failed to upload {file}: {e}")

def cleanup_old_deployment(ssh):
    """Remove the old nested directory and its cron jobs"""
    old_dir = "/var/www/html/bot_whatsapp/repondeur_mail_grok"
    print("Checking for old deployment...")
    try:
        # Check if exists
        sftp = ssh.open_sftp()
        try:
            sftp.stat(old_dir)
            print(f"Removing old directory: {old_dir}")
            run_sudo(ssh, f"rm -rf {old_dir}", PASS)
        except IOError:
            pass # Doesn't exist
            
    except Exception as e:
        print(f"Warning during cleanup: {e}")

def setup_cron(ssh):
    print("Configuring Cron...")
    
    # New validated lines
    cron_lines = [
        f"*/5 * * * * php {REMOTE_DIR}/scripts/scan.php >> {REMOTE_DIR}/data/logs/scan.log 2>&1",
        f"* * * * * php {REMOTE_DIR}/scripts/sender.php >> {REMOTE_DIR}/data/logs/sender.log 2>&1"
    ]
    
    stdin, stdout, stderr = ssh.exec_command("crontab -l")
    current_cron = stdout.read().decode('utf-8').strip()
    
    # Remove old lines containing "repondeur_mail_grok" to avoid duplicates
    # This is a bit aggressive but safe since we are reinstalling
    lines = current_cron.split('\n')
    clean_lines = [line for line in lines if "repondeur_mail_grok" not in line and line.strip() != ""]
    
    # Add new lines
    new_cron_content = "\n".join(clean_lines) + "\n" + "\n".join(cron_lines) + "\n"
    
    # Write back
    cmd = f'echo "{new_cron_content}" | crontab -'
    ssh.exec_command(cmd)
    print("Cron updated (Old paths removed).")

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 Directories with SUDO
        print("Preparing Remote Directories (Sudo)...")
        # Ensure base exists
        run_sudo(ssh, f"mkdir -p {REMOTE_BASE}", PASS)
        # Ensure permissions on base (or just create target)
        run_sudo(ssh, f"mkdir -p {REMOTE_DIR}", PASS)
        run_sudo(ssh, f"mkdir -p {REMOTE_DIR}/data/logs", PASS)
        
        # Take ownership so we can SFTP
        run_sudo(ssh, f"chown -R {USER}:{USER} {REMOTE_DIR}", PASS)
        # Also give general permissions just in case
        run_sudo(ssh, f"chmod -R 755 {REMOTE_DIR}", PASS)
        
        # 2. Upload
        print("Starting Upload...")
        sftp = ssh.open_sftp()
        upload_dir(sftp, LOCAL_DIR, REMOTE_DIR)
        
        # 3. Final Permissions with SUDO
        print("Setting Final Permissions...")
        run_sudo(ssh, f"chmod -R 777 {REMOTE_DIR}/data", PASS)
        run_sudo(ssh, f"chown -R www-data:www-data {REMOTE_DIR}/data", PASS) 
        # Warning: if we chown to www-data, ubuntu user might lose write access for next deploy?
        # Better: chown ubuntu:www-data and chmod 775/777.
        # Let's stick to 777 for data to be safe for now, ownership is tricky without group management.
        
        # 3. Final Permissions with SUDO
        print("Setting Final Permissions...")
        run_sudo(ssh, f"chmod -R 777 {REMOTE_DIR}/data", PASS)
        run_sudo(ssh, f"chown -R www-data:www-data {REMOTE_DIR}/data", PASS) 
        
        # 4. Cleanup Old
        cleanup_old_deployment(ssh)

        # 5. Cron
        setup_cron(ssh)
        
        ssh.close()
        print("✅ Deployment Success!")
        
    except Exception as e:
        print(f"❌ Deployment Failed: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()
