
import requests
import hashlib
import time
import os
from selenium import webdriver
from selenium.webdriver.chromium.options import ChromiumOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from dotenv import load_dotenv

# ============= KONFIGURATION =============
load_dotenv()  # Lädt .env Datei falls vorhanden

MLX_BASE = "https://api.multilogin.com"
MLX_LAUNCHER_V2 = "https://launcher.mlx.yt:45001/api/v2"
MLX_LAUNCHER_V1 = "https://launcher.mlx.yt:45001/api/v1"
LOCALHOST = "http://127.0.0.1"



# Deine Credentials
USERNAME = "e.kamuf88@gmail.com"
PASSWORD = "B9!n4g64"

FOLDER_ID = "ec4a6221-f8f3-4843-83d7-d66a3d101c68"
PROFILE_ID = "e22d9f17-bc2b-4693-853e-3701301b54e9"
# Browser Typ: "mimic" oder "stealthfox"
BROWSER_TYPE = "mimic"  # Anpassen nach Bedarf

HEADERS = {
    "Accept": "application/json",
    "Content-Type": "application/json"
}

# ============= FUNKTIONEN =============

def hash_password(password):
    """Konvertiert Passwort zu MD5 Hash"""
    return hashlib.md5(password.encode()).hexdigest()


def signin():
    """
    Authentifiziert dich bei Multilogin API
    Gibt zurück: Bearer Token
    """
    print("[*] Authentifiziere mich bei Multilogin...")
    
    payload = {
        "email": USERNAME,
        "password": hash_password(PASSWORD)
    }
    
    try:
        response = requests.post(
            f"{MLX_BASE}/user/signin",
            json=payload,
            headers=HEADERS,
            timeout=10
        )
        
        if response.status_code != 200:
            print(f"[✗] Fehler beim Login: {response.text}")
            return None
        
        token = response.json()["data"]["token"]
        print(f"[✓] Erfolgreich angemeldet")
        return token
        
    except Exception as e:
        print(f"[✗] Exception beim Sign-In: {e}")
        return None


def start_profile(token):
    """
    Startet ein Profil mit Selenium-Automation
    Gibt zurück: Selenium Port oder None
    """
    print(f"[*] Starte Profil {PROFILE_ID}...")
    
    headers = HEADERS.copy()
    headers["Authorization"] = f"Bearer {token}"
    
    try:
        response = requests.get(
            f"{MLX_LAUNCHER_V2}/profile/f/{FOLDER_ID}/p/{PROFILE_ID}/start?automation_type=selenium",
            headers=headers,
            timeout=15
        )
        
        if response.status_code != 200:
            print(f"[✗] Fehler beim Starten: {response.text}")
            return None
        
        data = response.json()
        selenium_port = data["data"]["port"]
        print(f"[✓] Profil gestartet | Port: {selenium_port}")
        return selenium_port
        
    except Exception as e:
        print(f"[✗] Exception beim Start-Profile: {e}")
        return None


def stop_profile(token):
    """
    Beendet ein Profil
    """
    print(f"[*] Beende Profil {PROFILE_ID}...")
    
    headers = HEADERS.copy()
    headers["Authorization"] = f"Bearer {token}"
    
    try:
        response = requests.get(
            f"{MLX_LAUNCHER_V1}/profile/stop/p/{PROFILE_ID}",
            headers=headers,
            timeout=10
        )
        
        if response.status_code == 200:
            print("[✓] Profil beendet")
            return True
        else:
            print(f"[✗] Fehler beim Beenden: {response.text}")
            return False
            
    except Exception as e:
        print(f"[✗] Exception beim Stop-Profile: {e}")
        return False


def create_driver(selenium_port):
    """
    Erstellt einen Selenium WebDriver
    """
    print(f"[*] Verbinde Selenium mit Port {selenium_port}...")
    
    try:
        # Wähle Browser-Optionen basierend auf Typ
        if BROWSER_TYPE == "stealthfox":
            options = FirefoxOptions()
        else:  # mimic (Standard)
            options = ChromiumOptions()
        
        driver = webdriver.Remote(
            command_executor=f"{LOCALHOST}:{selenium_port}",
            options=options
        )
        
        print("[✓] Selenium verbunden")
        return driver
        
    except Exception as e:
        print(f"[✗] Fehler beim WebDriver erstellen: {e}")
        return None


def automate_browser(driver):
    """
    Beispiel-Automatisierung
    Anpassen nach deinen Bedürfnissen
    """
    print("[*] Starte Automation...")
    
    try:
        # Beispiel: Google öffnen
        driver.get("https://www.google.com")
        print("[✓] Google.com geöffnet")
        
        # Warte bis Seite geladen ist
        wait = WebDriverWait(driver, 10)
        
        # Beispiel: Suchfeld finden und ausfüllen
        search_box = wait.until(
            EC.presence_of_element_located((By.NAME, "q"))
        )
        search_box.send_keys("Multilogin Selenium")
        print("[✓] Suchtext eingegeben")
        
        # Suchbutton klicken
        search_button = driver.find_element(By.NAME, "btnK")
        search_button.click()
        print("[✓] Suche gestartet")
        
        # 5 Sekunden warten für Ergebnisse
        time.sleep(5)
        
        # Title des Suchergebnisses abrufen
        print(f"[✓] Suchergebnis-Titel: {driver.title}")
        
    except Exception as e:
        print(f"[✗] Fehler bei Automation: {e}")


def main():
    """
    Hauptfunktion - Orchestriert alle Schritte
    """
    print("=" * 50)
    print("Multilogin + Selenium Automation")
    print("=" * 50)
    
    # 1. Authentifizieren
    token = signin()
    if not token:
        print("[✗] Konnte nicht authentifizieren. Beende.")
        return
    
    # 2. Profil starten
    selenium_port = start_profile(token)
    if not selenium_port:
        print("[✗] Konnte Profil nicht starten. Beende.")
        return
    
    # 3. Etwas warten bis Profil vollständig initialisiert ist
    time.sleep(3)
    
    # 4. WebDriver erstellen
    driver = create_driver(selenium_port)
    if not driver:
        print("[✗] Konnte WebDriver nicht erstellen. Beende.")
        return
    
    # 5. Deine Automation ausführen
    try:
        automate_browser(driver)
    finally:
        # 6. Cleanup
        driver.quit()
        time.sleep(1)
        stop_profile(token)
    
    print("[✓] Fertig!")


if __name__ == "__main__":
    main()