import os
import sys
import time
import urllib.request
import paramiko

LOCAL_ZIP = r"e:\rescatado\proyecto_completo.zip"
REMOTE_ZIP = "/home/laboptimus/public_html/proyecto_completo.zip"
PHP_SCRIPT = "descomprimir_servidor.php"
PHP_PATH = r"e:\rescatado\descomprimir_servidor.php"

HOST = "laboptimus.com"
PORT = 22
USER = "laboptimus"
PASS = "Pepe2020@20251478#"

def get_sftp_connection():
    while True:
        try:
            sock = paramiko.Transport((HOST, PORT))
            sock.use_compression(False) # No comprimir sobre el zip ya comprimido para ahorrar CPU y latencia
            sock.set_keepalive(10)
            sock.connect(username=USER, password=PASS)
            sftp = paramiko.SFTPClient.from_transport(sock)
            return sock, sftp
        except Exception as e:
            print(f"\n[REINTENTO CONEXION] Reconectando en 3s... ({e})")
            time.sleep(3)

def turbo_resume():
    total_size = os.path.getsize(LOCAL_ZIP)
    total_gb = round(total_size / (1024**3), 2)
    print(f"[*] Tamano total: {total_gb} GB")
    
    sock, sftp = get_sftp_connection()
    
    # Asegurar script extractor
    try:
        sftp.put(PHP_PATH, f"/home/laboptimus/public_html/{PHP_SCRIPT}")
    except:
        pass

    CHUNK = 1024 * 1024  # 1MB buffer optimizado
    
    while True:
        try:
            remote_size = 0
            try:
                remote_attr = sftp.stat(REMOTE_ZIP)
                remote_size = remote_attr.st_size
            except IOError:
                remote_size = 0
                
            if remote_size >= total_size:
                print(f"\n[V] Archivo 100% completo en hosting ({round(remote_size/(1024**3), 2)} GB).")
                break
                
            print(f"[*] REANUDANDO TURBO desde {round(remote_size/(1024**3), 2)} GB...")
            
            # Apertura con pipelining habilitado para maxima velocidad
            remote_f = sftp.open(REMOTE_ZIP, "a+b")
            remote_f.set_pipelined(True)
            remote_f.seek(remote_size)
            
            with open(LOCAL_ZIP, "rb") as local_f:
                local_f.seek(remote_size)
                transferred = remote_size
                last_print = time.time()
                bytes_in_interval = 0
                
                while True:
                    data = local_f.read(CHUNK)
                    if not data:
                        break
                    remote_f.write(data)
                    transferred += len(data)
                    bytes_in_interval += len(data)
                    
                    now = time.time()
                    if now - last_print >= 1.5:
                        pct = round((transferred / total_size) * 100, 2)
                        cur_gb = round(transferred / (1024**3), 2)
                        speed_mb = round((bytes_in_interval / (now - last_print)) / (1024*1024), 2)
                        sys.stdout.write(f"\r[TURBO SFTP] {pct}% ({cur_gb}/{total_gb} GB) - {speed_mb} MB/s      ")
                        sys.stdout.flush()
                        last_print = now
                        bytes_in_interval = 0
                        
            remote_f.close()
            print(f"\n[V] Subida 100% completada.")
            break
            
        except Exception as e:
            print(f"\n[AVISO RED] Reconectando automaticamente: {e}")
            try: sftp.close()
            except: pass
            try: sock.close()
            except: pass
            time.sleep(2)
            sock, sftp = get_sftp_connection()

    try: sftp.close()
    except: pass
    try: sock.close()
    except: pass

    print("\n[*] Solicitando descompresion remota en el servidor...")
    url = f"https://{HOST}/{PHP_SCRIPT}"
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    try:
        with urllib.request.urlopen(req, timeout=900) as response:
            result = response.read().decode('utf-8', errors='ignore')
            print(f"[RESPUESTA DEL HOSTING]:\n{result}")
    except Exception as e:
        print(f"[AVISO] Descompresion: {e}")
        print(f"Puedes ingresar a {url} para activarlo.")

if __name__ == "__main__":
    turbo_resume()
