import subprocess
import os
import time
import signal

def iniciar_chrome(chrome_path,
                   user_data_dir,
                   headless=False,
                   debugging_port=9222,
                   user_agent=None,
                   ):

    # Asegúrate de que el directorio del perfil exista
    os.makedirs(user_data_dir, exist_ok=True)

    # Lista de argumentos para Chrome
    chrome_args = [
        f"--remote-debugging-port={debugging_port}",
        f"--user-data-dir={user_data_dir}",
        "--disable-blink-features=AutomationControlled",
        "--no-sandbox",
        "--disable-web-security",
        "--disable-extensions",
        "--disable-dev-shm-usage",
        "--disable-infobars",
        "--disable-popup-blocking",
        "--disable-default-apps",
        "--mute-audio",
        "--window-size=1024,1024",
        
    ]

    if not headless:
        pass
    else:
        chrome_args.append("--headless=new")  # para versiones recientes de Chrome

    if not user_agent:
        pass
    else:
        chrome_args.append(f"--user-agent={user_agent}")

    # Comando para iniciar Chrome
    chrome_process = subprocess.Popen([chrome_path] + chrome_args)

    try:
        print(f"Chrome iniciado (headless={headless}). Presiona Ctrl+C para salir.")
        while True:
            if chrome_process.poll() is not None:
                print("Chrome se ha cerrado.")
                break
            time.sleep(1)
    except KeyboardInterrupt:
        print("Terminando proceso de Chrome...")
        chrome_process.terminate()
        try:
            chrome_process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            chrome_process.kill()
        print("Chrome cerrado correctamente.")


# Ruta al ejecutable de Chrome
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"

# Directorio para el perfil de usuario
user_data_dir = os.path.abspath("./Perfiles_usuario/chrome_profile")

# Puerto para la depuración remota
port = 9222

user_agent= "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"


# Llama a la función con True o False
iniciar_chrome(chrome_path=chrome_path,
               user_data_dir=user_data_dir,
               debugging_port=port,
               headless=False,
               user_agent=user_agent)  # Cambia a True para modo headless