import requests
import time
from seleniumbase import Driver



import sys
#!/usr/bin/env python3
import json, time, requests
from pathlib import Path
from typing import Union, Optional, Dict, Any

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from typing import Optional

from selenium.webdriver.common.by import By  # assuming selenium already imported
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchWindowException
from selenium.webdriver.support.ui import WebDriverWait

#!/usr/bin/env python3
import os, sys, json, random, string, time, csv, logging, re
from datetime import datetime
from collections import defaultdict, deque
from mypiprandomdata.cli import get_random_data


import gspread
from oauth2client.service_account import ServiceAccountCredentials


######################################################################
import requests
import time
############################
API_KEY = "d52627c4e966fe8b8abee9631e279ae7gG9oBZIKsHl3n6eSOkcz5aQPDJEw72f1"
API_BASE = "https://api.clonenha.com"

SERVICE = "aws"     # aws, fb, microsoft, etc
QUANTITY = 1        # always 1 for automation

###############
API_KEY1 = "r0PBoC4fH2ZTUvQ79Uup4DgKUrEwkT"
BASE_URL = "https://daisysms.com/stubs/handler_api.php"

SERVICE1 = "am"
MAX_PRICE = 0.3     # 🔒 STRICT LIMIT
POLL_INTERVAL = 5
TIMEOUT = 120        # seconds
###################3


# -------------------------------
# STEP 1: BUY EMAIL
# -------------------------------
def buy_email(service):
    url = f"{API_BASE}/buy-email"
    params = {
        "apiKey": API_KEY,
        "service": service,
        "quantity": 1
    }

    r = requests.get(url, params=params, timeout=15).json()

    if not r.get("success"):
        raise Exception(f"Buy email failed: {r.get('message')}")

    item = r["data"][0]
    return item["email"], item["orderId"]


# -------------------------------
# STEP 2: WAIT FOR OTP
# -------------------------------
def wait_for_otp(order_id, timeout=120, interval=5):
    """
    Wait until OTP arrives or timeout happens
    """
    start = time.time()

    while time.time() - start < timeout:
        url = f"{API_BASE}/get-otp"
        params = {
            "apiKey": API_KEY,
            "orderId": order_id
        }

        r = requests.get(url, params=params, timeout=15).json()

        # ✅ OTP RECEIVED
        if r.get("success") and r.get("data") and r["data"].get("code"):
            return r["data"]["code"]

        # ❌ FAILED / REFUNDED
        if not r.get("success"):
            raise Exception(f"OTP failed: {r.get('message')}")

        # ⏳ Still waiting
        print("⏳ Waiting for OTP...")
        time.sleep(interval)

    raise TimeoutError("OTP not received in time")


def show_email_banner(driver, text):
    driver.execute_script("""
    let banner = document.getElementById("otp-email-banner");
    if (!banner) {
        banner = document.createElement("div");
        banner.id = "otp-email-banner";
        banner.style.position = "fixed";
        banner.style.top = "0";
        banner.style.left = "0";
        banner.style.width = "100%";
        banner.style.background = "#111827";
        banner.style.color = "#22c55e";
        banner.style.fontFamily = "monospace";
        banner.style.fontSize = "16px";
        banner.style.padding = "10px";
        banner.style.zIndex = "999999";
        banner.style.textAlign = "center";
        document.body.style.marginTop = "50px";
        document.body.appendChild(banner);
    }
    banner.innerText = arguments[0];
    """, text)

#################################################################################

import requests
import time


# -----------------------------------
# STEP 1: CHECK BALANCE (OPTIONAL)
# -----------------------------------
def get_balance():
    r = requests.get(BASE_URL, params={
        "api_key": API_KEY1,
        "action": "getBalance"
    }, timeout=10).text

    if r.startswith("ACCESS_BALANCE:"):
        return float(r.split(":")[1])

    raise Exception(f"Balance check failed: {r}")


# -----------------------------------
# STEP 2: RENT NUMBER (WITH PRICE CAP)
# -----------------------------------
def rent_number():
    r = requests.get(BASE_URL, params={
        "api_key": API_KEY1,
        "action": "getNumber",
        "service": SERVICE1,
        "max_price": MAX_PRICE
    }, timeout=15).text

    if r.startswith("ACCESS_NUMBER"):
        _, activation_id, phone = r.split(":")
        return activation_id, phone

    if r == "MAX_PRICE_EXCEEDED":
        raise Exception("❌ Price exceeded $0.20, not renting")

    raise Exception(f"❌ Failed renting number: {r}")


# -----------------------------------
# STEP 3: WAIT FOR OTP
# -----------------------------------
def wait_for_sms(activation_id):
    start = time.time()

    while time.time() - start < TIMEOUT:
        r = requests.get(BASE_URL, params={
            "api_key": API_KEY1,
            "action": "getStatus",
            "id": activation_id
        }, timeout=10).text

        if r.startswith("STATUS_OK"):
            otp = r.split(":")[1]
            return otp

        if r in ("STATUS_CANCEL", "NO_ACTIVATION"):
            raise Exception("❌ Activation cancelled or invalid")

        print("⏳ Waiting for SMS...")
        time.sleep(POLL_INTERVAL)

    raise TimeoutError("❌ OTP not received in time")


# -----------------------------------
# STEP 4: MARK RENTAL AS DONE
# -----------------------------------
def mark_done(activation_id):
    r = requests.get(BASE_URL, params={
        "api_key": API_KEY1,
        "action": "setStatus",
        "id": activation_id,
        "status": 6
    }, timeout=10).text

    if r != "ACCESS_ACTIVATION":
        print(f"⚠️ Could not mark done: {r}")


# -----------------------------------
# MAIN FLOW




###############################################################################

# ================= USER DATA SCRIPT =================
USER_DATA_SCRIPT = r"""
<powershell>
# ============================================================
# AWS USER DATA
# Download StarterPack + Run on First Login (DELAYED)
# Order: captchav6o.ps1 → PasswordChange.bat
# ============================================================

$ErrorActionPreference = "Stop"

$BaseUrl   = "https://muazamdot.online/StarterPack"
$TargetDir = "C:\Users\Administrator\Desktop"
$LogFile   = "C:\starterpack_userdata.log"
$TaskName  = "RunStarterPack_FirstLogin"

$Files = @(
    "PasswordChange.bat",
    "captchav6o.ps1",
    "captchav6o.bat",
    "captchav6.ps1",
    "Captchav6.bat"
)

function Log {
    param([string]$msg)
    $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$ts - $msg" | Out-File -FilePath $LogFile -Append
}

function Download-WithRetry {
    param([string]$Url,[string]$OutFile,[int]$MaxRetries = 20)
    for ($i = 1; $i -le $MaxRetries; $i++) {
        try {
            curl.exe -L --fail --silent --show-error --output "$OutFile" "$Url"
            if ((Test-Path $OutFile) -and ((Get-Item $OutFile).Length -gt 0)) { return }
        } catch {}
        Start-Sleep 3
    }
    exit 1
}

Log "===== USER DATA STARTED ====="
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
New-Item -ItemType Directory -Force -Path $TargetDir | Out-Null

foreach ($file in $Files) {
    Download-WithRetry "$BaseUrl/$file" (Join-Path $TargetDir $file)
}

$FirstLoginScript = @"
Start-Sleep 20
powershell.exe -ExecutionPolicy Bypass -File "$TargetDir\captchav6o.ps1"
Start-Process cmd.exe -ArgumentList "/c $TargetDir\PasswordChange.bat" -Wait
schtasks /delete /tn "$TaskName" /f
"@

$FirstLoginPath = "C:\run_starterpack_firstlogin.ps1"
$FirstLoginScript | Out-File $FirstLoginPath -Encoding UTF8 -Force

schtasks /create /tn "$TaskName" /tr "powershell.exe -ExecutionPolicy Bypass -File `"$FirstLoginPath`"" /sc ONLOGON /ru "Administrator" /rl HIGHEST /f
</powershell>
"""


########################################


import os
import sys

CREDENTIALS_FILE = "AWS_Auto_Mode.json"  # Google service account


def prepare_credentials_file():
    global CREDENTIALS_FILE

    # EXE folder (or script folder)
    if getattr(sys, 'frozen', False):
        base_dir = os.path.dirname(sys.executable)
    else:
        base_dir = os.path.dirname(os.path.abspath(__file__))

    exe_path = os.path.join(base_dir, CREDENTIALS_FILE)
    if os.path.exists(exe_path):
        CREDENTIALS_FILE = exe_path
        return

    cwd_path = os.path.join(os.getcwd(), CREDENTIALS_FILE)
    if os.path.exists(cwd_path):
        CREDENTIALS_FILE = cwd_path
        return

    raise FileNotFoundError(f"❌ {CREDENTIALS_FILE} not found")


prepare_credentials_file()

SHEET_NAME = "AWS_Auto_Mode"             # name of the Google Sheet

import os

filename = "Sheet_Name.txt"

# Create file if it doesn't exist
if not os.path.exists(filename):
    open(filename, "w").close()

# Read first line
with open(filename, "r", encoding="utf-8") as f:
    first_line = f.readline().strip()

# If file empty, ask user for input and write it
if not first_line:
    first_line = input("Enter worksheet name: ").strip()
    with open(filename, "w", encoding="utf-8") as f:
        f.write(first_line + "\n")

WorkSheet = first_line
print("WorkSheet =", WorkSheet)



def show_browser_error(driver, message):
    """Display a visible red banner at the top of the page with the error text."""
    safe_message = message.replace("'", "\\'").replace("\n", " ")
    script = f"""
    (function(){{
        let banner = document.getElementById('chatgpt_error_banner');
        if (!banner) {{
            banner = document.createElement('div');
            banner.id = 'chatgpt_error_banner';
            banner.style.position = 'fixed';
            banner.style.top = '0';
            banner.style.left = '0';
            banner.style.width = '100%';
            banner.style.zIndex = '999999';
            banner.style.background = '#d32f2f';
            banner.style.color = 'white';
            banner.style.fontFamily = 'monospace';
            banner.style.padding = '10px';
            banner.style.textAlign = 'center';
            banner.style.fontSize = '14px';
        }}
        banner.textContent = '⚠️ ' + '{safe_message}';
        document.body.prepend(banner);
    }})();
    """
    driver.execute_script(script)



def connect_google_sheet():
    """Connect to Google Sheets and return the worksheet named 'Mauzam'."""
    scope = [
        "https://spreadsheets.google.com/feeds",
        "https://www.googleapis.com/auth/drive"
    ]
    creds = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIALS_FILE, scope)
    client = gspread.authorize(creds)
    
    # Open spreadsheet
    spreadsheet = client.open(SHEET_NAME)
    
    # Open the worksheet by name instead of defaulting to sheet1
    sheet = spreadsheet.worksheet(WorkSheet)
    
    print(f"✅ Connected to worksheet '{WorkSheet}' in Google Sheet:", SHEET_NAME)
    return sheet


def connect_minipc_sheet():
    """Connect to Google Sheets and return the worksheet 'MiniPCv1'."""
    scope = [
        "https://spreadsheets.google.com/feeds",
        "https://www.googleapis.com/auth/drive"
    ]
    creds = ServiceAccountCredentials.from_json_keyfile_name(CREDENTIALS_FILE, scope)
    client = gspread.authorize(creds)

    spreadsheet = client.open(SHEET_NAME)
    ws_minipc = spreadsheet.worksheet("MiniPCv1")

    print("✅ Connected to worksheet 'MiniPCv1' in Google Sheet:", SHEET_NAME)
    return ws_minipc

def get_minipc_location_values(ws_minipc):
    """
    Read fixed cells from MiniPCv1:
    A16 B16 C16 D16 E16
    """

    CityValue       = (ws_minipc.acell("A16").value or "").strip()
    StateValue      = (ws_minipc.acell("B16").value or "").strip()
    ZipValue        = (ws_minipc.acell("C16").value or "").strip()
    PlanTypeValue   = (ws_minipc.acell("D16").value or "").strip()   # Free / Paid
    OSValue         = (ws_minipc.acell("E16").value or "").strip()   # Ubuntu
    proxy_user_username = (ws_minipc.acell("F16").value or "").strip()   # Proxy username
    proxy_user_pass = (ws_minipc.acell("G16").value or "").strip()   # Proxy password
    startingportrange = (ws_minipc.acell("H16").value or "").strip()   # Starting port range for proxies
    endingportrange = (ws_minipc.acell("I16").value or "").strip()   # Ending port range for proxies

    return CityValue, StateValue, ZipValue, PlanTypeValue, OSValue, proxy_user_username, proxy_user_pass, startingportrange, endingportrange


ws_minipc = connect_minipc_sheet()

CityValue, StateValue, ZipValue, PlanTypeValue, OSValue, proxy_user_username, proxy_user_pass, startingportrange, endingportrange = get_minipc_location_values(ws_minipc)

print("CityValue:", CityValue)
print("StateValue:", StateValue)
print("ZipValue:", ZipValue)
print("PlanTypeValue:", PlanTypeValue)
print("OSValue:", OSValue)
print("startingportrange:", startingportrange)
print("endingportrange:", endingportrange)



Region = ""

def get_user_data(sheet):
    """Read Email, Phone, Card, CVV from row 2 by header names, strip whitespace."""
    headers = sheet.row_values(1)
    values = sheet.row_values(2)

    # Map headers to values, stripping whitespace
    row_dict = {h.strip(): (v.strip() if isinstance(v, str) else v)
                for h, v in zip(headers, values)}

    email       = row_dict.get("Email", "")
    phonenumber = row_dict.get("Phone", "")
    card_number = row_dict.get("Card", "")
    CVV         = row_dict.get("CVV", "")
    firstname = row_dict.get("First Name", "")
    lastname = row_dict.get("Last Name", "")
    EXP_Month_CC = row_dict.get("EXP Month", "")
    EXP_Year_CC = row_dict.get("EXP Year", "")
    InstanceType = row_dict.get("InstanceType", "")
    Region = row_dict.get("Region", "")
    TotalRDPNeed = row_dict.get("TotalRDPNeed", "")



    return email, phonenumber, card_number, CVV ,firstname, lastname ,EXP_Month_CC, EXP_Year_CC,InstanceType,Region,TotalRDPNeed


# ── Usage ────────────────────────────────────────────────────────
sheet = connect_google_sheet()
email, phonenumber, card_number, CVV ,firstname , lastname ,EXP_Month_CC,EXP_Year_CC,InstanceType , Region,TotalRDPNeed= get_user_data(sheet)

print("Email:", email)
print("Phone:", phonenumber)
print("Card:", card_number)
print("CVV:", CVV)
print("First Name:", firstname)
print("Last Name:", lastname)
print("EXP Month:", EXP_Month_CC)
print("EXP Year:", EXP_Year_CC)
print("InstanceType:", InstanceType)
print("Region:", Region)
print("TotalRDPNeed:", TotalRDPNeed)
phonenumber1 = phonenumber.replace(" ", "")
if Region == "ap-southeast-1":
    regioncountry = "Singapore"
elif Region == "ap-south-1":
    regioncountry = "India"
elif Region == "us-east-2":
    regioncountry = "US"
else:
    regioncountry = "Unknown"

print("Region Country:", regioncountry)

if InstanceType in ["t3.xlarge", "t2.xlarge"]:
    instance_ram = "16GB RAM"
elif InstanceType.endswith(".large"):
    instance_ram = "8GB RAM"
else:
    instance_ram = "Unknown"

print(instance_ram)



RDP_region_RAM = f"{regioncountry} {instance_ram}"


def ask_input(prompt):
    value = ""
    while not value.strip():  # keep asking until non-empty
        value = input(prompt).replace(" ", "")  # remove ALL spaces
        if not value:
            print("This field cannot be empty. Please try again.")
    return value

# # Ask user for details
# email = ask_input("Enter your email: ")
# phonenumber = ask_input("Enter your phone number: ")
# card_number = ask_input("Enter your card number: ")
# CVV = ask_input("Enter your CVV: ")




# email_aws, order_id = buy_email(SERVICE)
# print("📧 Email:", email_aws)
# print("🆔 Order:", order_id)


order_id = '11'

username = email.split("@")[0]
email_aws = email


import time

def is_valid_phone_10(phone: str) -> bool:
    phone = (phone or "").strip()
    return phone.isdigit() and len(phone) == 10


def wait_for_new_valid_phone(sheet=sheet):
    # sheet = connect_google_sheet()   # connect ONCE

    last_seen_phone = None

    while True:
        try:
            headers = sheet.row_values(1)
            values  = sheet.row_values(2)

            row = {
                h.strip(): (v.strip() if isinstance(v, str) else v)
                for h, v in zip(headers, values)
            }

            current_phone = row.get("Phone", "")

            # 🚫 same value → ignore
            if current_phone == last_seen_phone:
                print("⏳ No change in phone. Waiting...")
                time.sleep(10)
                continue

            last_seen_phone = current_phone

            # ✅ new + valid
            if is_valid_phone_10(current_phone):
                print(f"✅ New valid phone detected: {current_phone}")
                return current_phone
            else:
                print("⏳ Phone changed but invalid. Waiting...")

        except Exception as e:
            print(f"⚠️ Sheet read error (safe retry): {e}")

        time.sleep(10)



# ── FILE PATHS ────────────────────────────────────────────────
STATE_FILE         = "target_states.txt"
STATE_PTR_FILE     = "state_ptr.txt"
DOMAIN_TRACK_FILE  = "domain_tracker.txt"
CUSTOM_DOMAIN_FILE = "custom_domains.txt"
CREDENTIALS_FILE   = "all_generated_credentials.txt"

def save_to_sheet(EMAIL, PASSWORD, card_number, phonenumber,sheet=sheet):
    """Save credentials in A7 (comma-separated) with retry protection."""
    max_retries = 2
    attempt = 0

    while attempt <= max_retries:
        try:
            # sheet = connect_google_sheet()
            data = f"{EMAIL}, {PASSWORD}, {card_number}, {phonenumber}"
            sheet.update_cell(7, 1, data)  # (row=7, col=1)
            print(f"✅ Saved credentials to A7: {data}")
            break  # Success → stop retrying

        except Exception as e:
            attempt += 1
            print(f"⚠️ Attempt {attempt} failed: {e}")

            if attempt > max_retries:
                print("❌ Skipping this entry after 2 failed attempts.")
                break

            # wait before retry
            time.sleep(2)

def humanish_scroll_to_bottom(driver, min_step=200, max_step=600, min_pause=0.05, max_pause=0.2):
    """
    Scroll down in random steps and pauses until bottom of page.
    - min_step/max_step: pixel chunk sizes (like mouse wheel deltas).
    - min_pause/max_pause: delays between steps (seconds).
    """
    last_height = driver.execute_script("return document.body.scrollHeight")

    while True:
        # choose a random step like a human wheel flick
        step = random.randint(min_step, max_step)
        driver.execute_script(f"window.scrollBy(0, {step});")

        # short, random pause
        time.sleep(random.uniform(min_pause, max_pause))

        # check if we're at the bottom
        new_height = driver.execute_script("return document.body.scrollHeight")
        scroll_top = driver.execute_script("return window.pageYOffset + window.innerHeight")
        if scroll_top >= new_height - 2:  # allow tiny tolerance
            break

from pathlib import Path
import csv
time.sleep(random.uniform(2, 8))
def save_creds(email: str, password: str, full_name: str, state: str,
               csv_path: str = "saved_creds.csv",
               txt_path: str  = "saved_creds.txt",
               retries: int = 2,
               sleep_sec: float = 1.5) -> None:
    row = [email, password, full_name, state]

    # ---- TXT always (no lock issues usually) ----
    Path(txt_path).parent.mkdir(parents=True, exist_ok=True)
    with open(txt_path, "a", encoding="utf-8") as f:
        f.write("|".join(row) + "\n")

    # ---- CSV with retry ----
    csv_file = Path(csv_path)
    wrote = False
    for attempt in range(retries + 1):
        try:
            write_header = not csv_file.exists()
            with open(csv_file, "a", newline="", encoding="utf-8") as f:
                w = csv.writer(f)
                if write_header:
                    w.writerow(["email", "password", "full_name", "state"])
                w.writerow(row)
            wrote = True
            break
        except PermissionError:
            # file is locked (e.g., open in Excel)
            if attempt < retries:
                time.sleep(sleep_sec)
            else:
                # Give up silently or log
                print(f"[WARN] CSV locked after {retries+1} tries. Skipping CSV save.")

    if wrote:
        print("[OK] Saved to CSV and TXT.")
    else:
        print("[OK] Saved to TXT only.")



import logging
def get_fake_address_line1() -> str:
    try:
        resp = requests.get("https://randomuser.me/api/?nat=us", timeout=10)
        resp.raise_for_status()
        data = resp.json()["results"][0]
        street_number = data["location"]["street"]["number"]
        street_name   = data["location"]["street"]["name"]
        return f"{street_number} {street_name}"
    except Exception as e:
        logging.error(f"Error fetching address: {e}")
        return "1234 Mockingbird Ln"


#address_line1 = get_fake_address_line1()


# ── LOGGING ───────────────────────────────────────────────────
logging.basicConfig(
    filename="profile_generator.log",
    filemode="a",
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S"
)
logging.info("🔄 Script run started (no loop).")

# ── LOAD data.json ────────────────────────────────────────────
def load_states_json():
    if getattr(sys, 'frozen', False):  # Running as EXE
        base = sys._MEIPASS
    else:  # Running as script
        base = os.path.dirname(os.path.abspath(__file__))

    data_path = os.path.join(base, "data.json")
    with open(data_path, "r", encoding="utf-8") as f:
        return json.load(f)

all_states = load_states_json()

state_index = defaultdict(list)
US_STATES = []
for state_entry in all_states:
    name = state_entry.get("name", "")
    US_STATES.append(name)
    for addr in state_entry.get("addresses", []):
        state_index[name.lower()].append(addr)
US_STATES.sort()

# ── HELPERS ───────────────────────────────────────────────────
def generate_random_word(min_len: int = 3, max_len: int = 12) -> str:
    length = random.randint(min_len, max_len)
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))

def generate_company_name(num_words: int = 2) -> str:
    return ' '.join(generate_random_word() for _ in range(num_words))

REPLACEMENTS = [
    '205','907','480','602','501','213','310','415','323','424','747','949',
    '303','203','302','305','786','754','954','404','470','678','808','208',
    '312','773','317','812','319','316','502','225','504','207','240','301',
    '617','339','313','248','612','601','314','406','402','702','603','201',
    '908','505','212','718','347','919','704','701','216','614','405','503',
    '215','412','401','803','843','605','615','901','214','346','512','713',
    '832','801','802','703','757','206','425','304','414','608','307','202'
]

def tweak_address(addr: str, min_chars: int = 2, max_chars: int = 3) -> str:
    """Inject 2–3 random letters/digits into an address."""
    if not addr.strip():
        return addr
    code = ''.join(random.choices(string.ascii_uppercase + string.digits,
                                  k=random.randint(min_chars, max_chars)))
    m = re.match(r'^(\d+)(\s+)(.*)$', addr.strip())
    if m:
        num, space, rest = m.groups()
        return random.choice([
            f"{num}{code}{space}{rest}",
            f"{num}{space}{rest} Apt {code}",
            f"{num}{space}{rest} Unit {code}",
            f"{num}{space}{rest} #{code}",
        ])
    else:
        return f"{addr} #{code}"

# ── DOMAIN ROTATION ───────────────────────────────────────────
def load_custom_domains(file_path=CUSTOM_DOMAIN_FILE):
    if not os.path.exists(file_path):
        open(file_path, "w", encoding="utf-8").close()
    with open(file_path, "r", encoding="utf-8") as f:
        return [line.strip() for line in f if line.strip()]

custom_domains = load_custom_domains() or [
    "actionvault.online", "adrenalinearcade.online", "adrenalinequest.online",
    "arcadeblast.online", "arcadeburst.online", "arcadeclash.online",
    "arcadecore.online", "arcadeedge.online", "arcadeflare.online",
    "arcadeflow.online", "arcadegear.online", "arcadegrid.online"
]

if not os.path.exists(DOMAIN_TRACK_FILE):
    open(DOMAIN_TRACK_FILE, "w", encoding="utf-8").close()

with open(DOMAIN_TRACK_FILE, "r", encoding="utf-8") as f:
    used_domains = [line.strip() for line in f if line.strip()]

def get_next_domain():
    global used_domains
    if len(used_domains) >= len(custom_domains):
        used_domains = []
    next_index = len(used_domains) % len(custom_domains)
    domain = custom_domains[next_index]
    used_domains.append(domain)
    with open(DOMAIN_TRACK_FILE, "w", encoding="utf-8") as f:
        for d in used_domains:
            f.write(d + "\n")
    return domain

# ── STATE ROTATION ────────────────────────────────────────────
def ensure_target_states():
    if not os.path.exists(STATE_FILE) or os.path.getsize(STATE_FILE) == 0:
        raw = input("Enter state(s) to use (comma or newline separated): ").strip()
        states = [s.strip() for s in raw.replace(",", "\n").splitlines() if s.strip()]
        with open(STATE_FILE, "w", encoding="utf-8") as f:
            for s in states:
                f.write(s + "\n")

    with open(STATE_FILE, "r", encoding="utf-8") as f:
        states = [line.strip() for line in f if line.strip()]

    valid = []
    for s in states:
        key = s.lower()
        if key in state_index:
            valid.append(s)
        else:
            print(f"❗️ Warning: '{s}' not found in data.json; skipping.")
    if not valid:
        raise RuntimeError("No valid states in target_states.txt")
    return valid

def get_next_state(states_list):
    idx = 0
    if os.path.exists(STATE_PTR_FILE):
        try:
            with open(STATE_PTR_FILE, "r", encoding="utf-8") as f:
                idx = int(f.read().strip() or "0")
        except Exception:
            idx = 0
    chosen = states_list[idx % len(states_list)]
    with open(STATE_PTR_FILE, "w", encoding="utf-8") as f:
        f.write(str((idx + 1) % len(states_list)))
    return chosen

# ── PROFILE BUILDER ───────────────────────────────────────────
def build_profile_from_record(rec):
    data = get_random_data()
    first, last = data.first_name, data.last_name
    company = generate_company_name()
    address = data.address

    phone = ''.join(filter(str.isdigit, rec.get("phone_number", "").replace("+1", "", 1)))
    if len(phone) >= 3:
        phone = random.choice(REPLACEMENTS) + phone[3:]

    import re, secrets, string

    AWS_SYMBOLS = "!@#$%^&*()<>[]{}|_+-="
    POOL = string.ascii_letters + string.digits + AWS_SYMBOLS

    while True:
        password = ''.join(secrets.choice(POOL) for _ in range(16))
        if sum(map(bool, (
                re.search(r'[a-z]', password),
                re.search(r'[A-Z]', password),
                re.search(r'\d', password),
                re.search(r'[!@#$%^&*()<>[\]{}|_+\-=]', password),
        ))) >= 3:
            break

    email_local = f"{first}{last}{''.join(random.choices(string.digits, k=random.randint(2, 4)))}".lower()
    email = f"{email_local}@{get_next_domain()}"

    try:
        with open(CREDENTIALS_FILE, "a", encoding="utf-8") as f:
            f.write(f"{email},{password}\n")
    except Exception as e:
        logging.error(f"Failed to auto-save credentials: {e}")

    # address = tweak_address(rec.get("street", ""))

    profile = {
        "first_name": first,
        "last_name": last,
        "company": company,
        "address": address,
        "city": rec.get("city", ""),
        "state": rec.get("state", ""),
        "zip_code": rec.get("zipcode", ""),
        "phone": phone,
        "password": password,
        "email": email
    }
    return profile

# ── RUN ONCE (no main, no loop) ───────────────────────────────
try:
    _states_list  = ensure_target_states()
    _target_state = get_next_state(_states_list)
    _key          = _target_state.lower()

    if _key not in state_index or not state_index[_key]:
        raise RuntimeError(f"No address records for state: {_target_state}")

    _record  = random.choice(state_index[_key])
    PROFILE  = build_profile_from_record(_record)





    # Expose fields
    FIRST_NAME = PROFILE["first_name"]
    LAST_NAME  = PROFILE["last_name"]
    EMAIL      = PROFILE["email"]
    PASSWORD =   PROFILE["password"]
    PHONE      = phonenumber
    # PHONE      = PROFILE["phone"]
    ADDRESS    = PROFILE["address"]
    CITY       = PROFILE["city"]
    STATE      = PROFILE["state"]
    ZIP_CODE   = PROFILE["zip_code"]
    COMPANY    = PROFILE["company"]

    logging.info(f"Generated profile for {_target_state}: {EMAIL}")

    # Optional: show result
    print("🎯 Generated profile for state:", _target_state)
    for k, v in PROFILE.items():
        print(f"{k:>12}: {v}")

except Exception as e:
    logging.exception("❌ Generation failed:")
    raise


API_URL = "http://127.0.0.1:53200"



import time
import requests
import random

# example: loaded as strings
startingportrange = str(startingportrange)
endingportrange   = str(endingportrange)

# convert once
startingportrange = int(startingportrange)
endingportrange   = int(endingportrange)


def get_random_dataimpulse_port():
    return random.randint(startingportrange, endingportrange)


import time
import requests
import random

# def get_random_dataimpulse_port():
#     return random.randint(10000, 10998)



def check_ipx_port(
    port,
    proxy_host="gw.dataimpulse.com",
    proxy_user=None,
    proxy_pass=None,
    ipx_url="https://ipx.ac/",
    timeout=6,
    require_country="US",
):
    import json, re, requests

    headers = {"User-Agent": "Mozilla/5.0"}
    data_regex = re.compile(r"var\s+DATA\s*=\s*(\{.*?\});", re.DOTALL)

    proxy_url = f"http://{proxy_user}:{proxy_pass}@{proxy_host}:{port}"
    proxies = {"http": proxy_url, "https": proxy_url}

    try:
        r = requests.get(
            ipx_url,
            proxies=proxies,
            headers=headers,
            timeout=timeout
        )
        r.raise_for_status()

        match = data_regex.search(r.text)
        if not match:
            return None

        data = json.loads(match.group(1))
        geo = data.get("geo", {})

        usage = geo.get("usage", "")
        country = geo.get("countryCode", "")
        ip_addr = data.get("ip", "")

        usage_l = usage.lower()

        DATACENTER_KEYWORDS = (
            "data center",
            "datacenter",
            "hosting",
            "cloud",
            "server",
            "non-"
        )

        RESIDENTIAL_KEYWORDS = (
            "residential",
            "mobile",
            "isp",
        )

        is_datacenter = any(k in usage_l for k in DATACENTER_KEYWORDS)

        is_residential = (
                not is_datacenter
                and any(k in usage_l for k in RESIDENTIAL_KEYWORDS)
        )

        if is_residential and country == require_country:
            print(f"✅ Port {port} validated: Residential={is_residential}, Country={country}, Usage={usage}")
            return {
                "ok": True,
                "port": port,
                "ip": ip_addr,
                "country": country,
                "usage": usage,
                "proxy": proxy_url
            }
        else:
            print(f"⚠️ Port {port} failed validation: Residential={is_residential}, Country={country}, Usage={usage}")

    except Exception:
        pass

    return None


def get_random_dataimpulse_port(startingportrange=startingportrange, endingportrange=endingportrange):
    return random.randint(startingportrange, endingportrange)

def create_profile(username):
    url = f"{API_URL}/api/v2/profile-create"

    # port = get_random_dataimpulse_port()

    MAX_TRIES = 10

    for _ in range(MAX_TRIES):
        port = get_random_dataimpulse_port()

        proxy_info = check_ipx_port(
            port=port,
            proxy_user=proxy_user_username,
            proxy_pass=proxy_user_pass,
        )

        if proxy_info:
            break
    else:
        print("❌ No valid residential proxy found")
        return None

    data = {
        "name": username,
        "proxy_config": {
            "proxy_mode": 2,
            "proxy_type": "http",
            "proxy_ip": "gw.dataimpulse.com",
            "proxy_port": str(port),
            "proxy_user": proxy_user_username,
            "proxy_password": proxy_user_pass,
        },
        "fingerprint_config": {
            "timezone_type": "1",
            "ua_type": 1,
            # "platform": "Windows",
            "platform": "Macos",
            # "system_version": "11",
            "br_version": "143",
            "ua_info": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.7499.11 Safari/537.36",
            "webrtc": "2",

        }
    }

    res = requests.post(url, json=data).json()
    print("CREATE RESPONSE:", res)

    if res.get("error", {}).get("code") == 0:
        return res["data"]   # ← returns int (profile_id)

    return None


def start_profile(profile_id, max_retries=6):
    import time
    import requests

    url_open = f"{API_URL}/api/v2/profile-open"
    url_update = f"{API_URL}/api/v2/profile-update"
    url_close = f"{API_URL}/api/v2/profile-close"

    for attempt in range(1, max_retries + 1):
        print(f"\n🔁 Proxy attempt {attempt}/{max_retries}")

        res = requests.post(
            url_open,
            json={"profile_id": profile_id, "load_profile_info_page": False},
            headers={"Content-Type": "application/json"}
        ).json()

        print("Start response:", res)

        # ✅ SUCCESS
        if res.get("error", {}).get("code") == 0:
            data = res["data"]
            print(f"✅ Profile started on port {data['debugging_port']}")
            return data

        # ❌ Proxy-related failure → rotate proxy (VALIDATED)
        msg = (res.get("error") or {}).get("message", "").lower()
        if any(k in msg for k in ("proxy", "timeout", "connection")):
            print("⚠ Proxy issue detected, rotating proxy...")

            # Close profile before proxy update
            requests.post(
                url_close,
                json={"profile_id": profile_id},
                headers={"Content-Type": "application/json"}
            )

            # 🔍 Find a validated port
            proxy_info = None
            for _ in range(5):  # small internal retries
                port = get_random_dataimpulse_port()
                proxy_info = check_ipx_port(
                    port=port,
                    proxy_user=proxy_user_username,
                    proxy_pass=proxy_user_pass,
                )
                if proxy_info:
                    break

            if not proxy_info:
                print("❌ Failed to find a valid residential proxy")
                continue

            port = proxy_info["port"]
            print(f"🔄 Updating proxy → gw.dataimpulse.com:{port}")

            upd = requests.post(
                url_update,
                json={
                    "profile_id": profile_id,
                    "proxy_config": {
                        "proxy_mode": 2,
                        "proxy_type": "http",
                        "proxy_ip": "gw.dataimpulse.com",
                        "proxy_port": str(port),
                        "proxy_user": proxy_user_username,
                        "proxy_password": proxy_user_pass,
                    }
                },
                headers={"Content-Type": "application/json"}
            ).json()

            print("Update response:", upd)
            time.sleep(1.5)
            continue

        # ❌ Non-proxy error
        print("❌ Non-proxy error, stopping retries")
        break

    print("🚫 All proxy attempts failed")
    return None



def close_profile(profile_id):
    url = f"{API_URL}/api/v2/profile-close"
    requests.post(url, json={"profile_id": profile_id}, headers={'Content-Type': 'application/json'})
    print("✅ Profile closed")


def delete_profile(profile_id):
    url = f"{API_URL}/api/v2/profile-delete"
    requests.post(url, json={"profile_id": profile_id}, headers={'Content-Type': 'application/json'})
    print("✅ Profile deleted")




from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.os_manager import ChromeType
service = Service(
            ChromeDriverManager().install()
        )
import random

def get_random_dataimpulse_port(start=10000, end=11000):
    return random.randint(start, end)
port = get_random_dataimpulse_port()



def main():
    import time
    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service

    username = email.split("@")[0]
    print(username)

    # print("🚀 Starting ixBrowser (attach-only mode)...")
    #
    # # 1️⃣ Create profile → RETURNS INT
    # profile_id = create_profile(username)
    # if not profile_id:
    #     print("❌ Failed to create profile")
    #     return
    #
    # # 2️⃣ Start profile → RETURNS DICT
    # start_data = start_profile(profile_id)
    # if not start_data:
    #     print("❌ Failed to start profile")
    #     return
    #
    # # 3️⃣ Small wait for DevTools
    # time.sleep(2)
    #
    #
    # # 4️⃣ Attach Selenium to ixBrowser
    # debug_address = start_data["debugging_address"]   # "127.0.0.1:4947"
    # ix_chromedriver = start_data["webdriver"]         # correct chromedriver
    #
    #
    # options.add_experimental_option(
    #     "debuggerAddress", debug_address
    # )
    # service = Service(ix_chromedriver)

    options = webdriver.ChromeOptions()

    # remove automation flags
    options.add_argument("--disable-blink-features=AutomationControlled")

    # optional useful settings
    options.add_argument("--start-maximized")
    options.add_argument("--disable-infobars")
    options.add_argument("--disable-extensions")

    # exclude automation switches
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)
    # options.add_argument(f"--proxy-server=http://gw.dataimpulse.com:{port}")


    driver = webdriver.Chrome(options=options)

    # hide webdriver property
    driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")


    # driver = webdriver.Chrome(
    #     # service=service,
    #     options=options
    # )

    print("✅ Selenium attached to ixBrowser successfully")

    # ---- your automation continues here ----
    # driver.get("https://ipinfo.io")

    import pyautogui
    from selenium.webdriver.common.action_chains import ActionChains

    import requests, base64, time, socket

    # --- tiny logger ---
    def dbg(msg):
        print(f"[DBG] {msg}")

    from selenium.webdriver.common.by import By  # assuming selenium already imported

    def type_like_clean(el, text, lo=0.05, hi=0.10):
        """
        Types into a Selenium element like a human (clean version):
        - Random delays between keystrokes
        - No mistakes or backspaces
        """
        try:
            el.click()
            time.sleep(0.5)  # ensure focus
        except:
            pass

        for ch in text:
            el.send_keys(ch)
            time.sleep(random.uniform(lo, hi))

    def type_like(el, text, lo=0.03, hi=0.13, mistake_chance=0.01):
        """
        Types into a Selenium element like a human:
        - Random delays between keystrokes
        - Occasional mistakes + backspaces
        """
        try:
            el.click()
            time.sleep(0.5)  # ensure focus
        except:
            pass

        for ch in text:
            # Random chance of mistake
            if random.random() < mistake_chance:
                wrong_char = random.choice("abcdefghijklmnopqrstuvwxyz1234567890")
                el.send_keys(wrong_char)
                time.sleep(random.uniform(lo, hi))
                el.send_keys(Keys.BACKSPACE)
                time.sleep(random.uniform(lo, hi))

            # Type the intended character
            el.send_keys(ch)
            time.sleep(random.uniform(lo, hi))

    # driver.maximize_window()

    # driver.get("https://sites.google.com/view/sasdfsdf/home")
    # time.sleep(2)
    #
    #
    #
    # aws_btn = WebDriverWait(driver, 15).until(
    #     EC.element_to_be_clickable((By.XPATH, "//a[@aria-label='AWS']"))
    # )
    # aws_btn.click()

    # def open_aws_and_get_cookies(url: str):
    #     driver.get(url)
    #     try:
    #
    #         print(f"Page loaded: {url}")
    #     except:
    #         print(f"Timeout: Failed to load {url} within 5 seconds.")
    #
    #
    # # Open 2-3 AWS links
    # aws_urls = [
    #     "https://www.google.com/url?q=https%3A%2F%2Faws.amazon.com%2Ffree%2F&sa=D&sntz=1&usg=AOvVaw0XQ_RzCzt3FNqtS8BLcsPe"
    #     # "https://aws.amazon.com/",
    #     "https://aws.amazon.com/ec2/"
    # ]
    #
    # # Open each URL and print the cookies
    # for url in aws_urls:
    #     open_aws_and_get_cookies(url)
    #     # Random delay between opening links (1 to 3 seconds)
    #     time.sleep(random.uniform(1, 3))

    from selenium.webdriver.common.action_chains import ActionChains

    import time
    import random

    # plan_choice = "paid"
    plan_choice = PlanTypeValue.lower()

    def human_scroll(driver, direction="down", step=80, delay_range=(0.05, 0.2),
                     pause_chance=0.1, pause_time=(0.8, 2.5), jitter_chance=0.15):
        """
        Scrolls the page like a human:
        - Uses base step size but varies it randomly
        - Random delays between scrolls
        - Occasional pauses (as if reading)
        - Occasional small jitters (scrolling back slightly)

        :param driver: Selenium driver
        :param direction: "down" or "up"
        :param step: average pixels per scroll step (varied randomly)
        :param delay_range: tuple(min, max) seconds between scrolls
        :param pause_chance: probability of pausing like a human reader
        :param pause_time: tuple(min, max) pause duration in seconds
        :param jitter_chance: probability of a small corrective scroll
        """
        start = driver.execute_script("return window.scrollY;")
        end = driver.execute_script("return document.body.scrollHeight;")

        if direction == "up":
            target = 0
            step_sign = -1
        else:
            target = end
            step_sign = 1

        y = start
        while (direction == "down" and y < target) or (direction == "up" and y > target):
            # Add variation to step (±40% randomness)
            step_size = step_sign * int(random.uniform(step * 0.6, step * 1.4))
            y += step_size

            driver.execute_script(f"window.scrollTo(0, {y});")
            time.sleep(random.uniform(*delay_range))

            # Occasionally pause like a human reading
            if random.random() < pause_chance:
                time.sleep(random.uniform(*pause_time))

            # Occasionally make a jitter (scroll back a bit)
            if random.random() < jitter_chance:
                jitter = step_sign * -1 * random.randint(10, 50)  # small opposite scroll
                driver.execute_script(f"window.scrollBy(0, {jitter});")
                time.sleep(random.uniform(0.2, 0.6))

    # driver.get("https://www.google.com/url?q=https%3A%2F%2Faws.amazon.com%2Ffree%2F&sa=D&sntz=1&usg=AOvVaw0XQ_RzCzt3FNqtS8BLcsPe")
    #driver.get(
    #    "https://www.google.com/url?q=https%3A%2F%2Faws.amazon.com%2Fsavingsplans%2Fml-pricing%2F&sa=D&sntz=1&usg=AOvVaw0U-LxAiBw7_NG8SYLV1Aqi")



    # driver.get("https://whoer.net")

    # time.sleep(600)

    ###########################################

    # url = 'https://www.google.com/url?q=https%3A%2F%2Faws.amazon.com%2Fsavingsplans%2Fml-pricing%2F&sa=D&sntz=1&usg=AOvVaw0U-LxAiBw7_NG8SYLV1Aqi'
    url = 'https://signin.aws.amazon.com/signup?request_type=register'
    #
    #
    # driver.uc_open_with_reconnect(url, reconnect_time=6)
    driver.get(url)
    #
    #
    #
    #
    # ###########################################
    WebDriverWait(driver, 120).until(lambda d: d.execute_script("return document.readyState") == "complete")
    # #
    # time.sleep(random.uniform(1, 2))
    #
    # humanish_scroll_to_bottom(driver)
    # time.sleep(random.uniform(1, 3))
    #
    #
    # aws_btn = WebDriverWait(driver, 20).until(
    #     EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*='console.aws.amazon.com/console/home']"))
    # )
    # driver.execute_script("arguments[0].click();", aws_btn)





    ###########################################
    #
    # time.sleep(random.randint(2, 4))

    # driver.get("https://google.com")
    #
    # # Accept cookies if popup appears (optional, depending on region)
    # try:
    #     agree_btn = driver.find_element(By.ID, "L2AGLb")
    #     agree_btn.click()
    # except :
    #     pass
    #
    # # Try textarea first, then input
    # try:
    #     search_box = driver.find_element(By.XPATH, "//textarea[@name='q']")
    # except:
    #     search_box = driver.find_element(By.XPATH, "//input[@name='q']")
    #
    # time.sleep(2)
    # # Type query
    # search_box.send_keys("AWS")
    # search_box.send_keys(Keys.RETURN)
    # time.sleep(2)
    # # Wait for results
    # driver.implicitly_wait(5)
    #
    # # # Click AWS official site
    # # aws_link = driver.find_element(By.PARTIAL_LINK_TEXT, "AWS")
    # # aws_link.click()
    #
    # # Find link that contains aws.amazon.com in its href
    # aws_link = driver.find_element(By.XPATH, "//a[contains(@href, 'aws.amazon.com')]")
    # aws_link.click()

    # driver.get("https://signin.aws.amazon.com/signup?request_type=register")




    # # Switch to the tab that contains AWS Console
    # for handle in driver.window_handles:
    #     driver.switch_to.window(handle)
    #     if "https://signin.aws.amazon.com/signup?request_type=register" in driver.current_url:
    #         print("✅ Switched to AWS Console tab")
    #         break



    

    # time.sleep(2)
    #
    # span_el = WebDriverWait(driver, 20).until(
    #     EC.presence_of_element_located((By.XPATH, "//span[text()='Sign in to an existing AWS account']"))
    # )
    # driver.execute_script("arguments[0].click();", span_el)
    #
    # time.sleep(random.uniform(1, 3))
    #
    # root_user_span = WebDriverWait(driver, 20).until(
    #     EC.presence_of_element_located((By.XPATH, "//span[text()='Sign in using root user email']"))
    # )
    # driver.execute_script("arguments[0].click();", root_user_span)
    # #
    # time.sleep(random.uniform(1, 4))
    #
    # humanish_scroll_to_bottom(driver)
    # time.sleep(random.uniform(1, 3))
    #
    # signup_btn = WebDriverWait(driver, 20).until(
    #     EC.element_to_be_clickable(
    #         (By.CSS_SELECTOR, "button[data-testid='sign-up']")
    #     )
    # )
    # driver.execute_script("arguments[0].click();", signup_btn)
    # #
    # time.sleep(random.uniform(2, 3))






    WebDriverWait(driver, 120).until(lambda d: d.execute_script("return document.readyState") == "complete")






    wait = WebDriverWait(driver, 20)


    username = email.split("@")[0]
    print(username)  # someone

    time.sleep(2)
    humanish_scroll_to_bottom(driver)
    time.sleep(2)

    show_email_banner(driver, f"{WorkSheet} 📧 EMAIL: {email_aws} {order_id} ")
    # type_like(driver.find_element(By.XPATH, "//input[@id='emailAddress']"), email)
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//input[@id='emailAddress']"))
        )
        type_like(element, email)


    except NoSuchWindowException:
        print("The window was already closed, switching to available one...")
        if driver.window_handles:
            driver.switch_to.window(driver.window_handles[0])

            element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "//input[@id='emailAddress']"))
            )
            type_like(element, email)
    # wait for the element, then type into it


    time.sleep(2)
    # type_like(driver.find_element(By.XPATH, "//input[@id='accountName']"), username)

    type_like(
    WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//input[@id='accountName']"))
        ),
        username
    )
    time.sleep(3)
    # driver.find_element(By.XPATH, "//span[normalize-space()='Verify email address']").click()

    button = wait.until(EC.element_to_be_clickable((By.XPATH, "//span[normalize-space()='Verify email address']")))

    # move to element before clicking (helps if it's off-screen)

    ActionChains(driver).move_to_element(button).click().perform()

    time.sleep(2)
    try:
        ActionChains(driver).move_to_element(button).click().perform()
    except:
        pass

    time.sleep(2)



    def is_verify_email_page(driver):
        try:
            driver.find_element(By.CSS_SELECTOR, "[data-testid='verify-email-submit-button']")
            return True
        except :
            return False

    show_email_banner(driver, f"{WorkSheet} 📧 EMAIL: {email_aws} {order_id} ")




    # # ── 2Captcha cfg ─────────────────────────────────────────────────────────────
    # API_KEY = "9bf3536f21a91fb8e151ba099319944a"
    # CREATE_URL = "https://api.2captcha.com/createTask"
    # RESULT_URL = "https://api.2captcha.com/getTaskResult"
    # REPORT_OK = "https://api.2captcha.com/reportCorrect"
    # REPORT_BAD = "https://api.2captcha.com/reportIncorrect"
    # OCR_HOST = "api.2captcha.com"
    #
    # def ensure_dns(host):
    #     try:
    #         socket.getaddrinfo(host, 443)
    #     except socket.gaierror:
    #         raise RuntimeError(f"Cannot resolve {host}")
    #
    # def post_with_retry(url, payload, retries=6, backoff=2):
    #     for i in range(1, retries + 1):
    #         try:
    #             r = requests.post(url, json=payload, timeout=15)
    #             r.raise_for_status()
    #             return r.json()
    #         except (requests.ConnectionError, requests.Timeout):
    #             if i == retries:
    #                 raise
    #             time.sleep(backoff ** i)
    #
    # # ── start ────────────────────────────────────────────────────────────────────
    #
    #
    # # ── start ────────────────────────────────────────────────────────────────────
    # time.sleep(9)
    # dbg("Slept 9s before solving CAPTCHA")
    #
    # try:
    #
    #     # ensure_dns(OCR_HOST)
    #     dbg("DNS OK for 2Captcha")
    #
    #     wait = WebDriverWait(driver, 20)
    #     MAX_ATTEMPTS = 4
    #
    #     for attempt in range(1, MAX_ATTEMPTS + 1):
    #         dbg(f"=== Attempt {attempt} ===")
    #         try:
    #             driver.switch_to.default_content()
    #         except:
    #             pass
    #
    #         dbg("Locating threat-mitigation iframe…")
    #         iframe = wait.until(EC.presence_of_element_located((
    #             By.ID, "core-container"
    #         )))
    #         driver.switch_to.frame(iframe)
    #
    #         dbg("Switched into iframe")
    #         time.sleep(5)
    #
    #         dbg("Grabbing CAPTCHA image…")
    #         img_b64 = ""
    #         retries = 0
    #
    #         while len(img_b64) < 500 and retries < 6:  # <<--- length validation added
    #             try:
    #                 img_el = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'img[alt="captcha"]')))
    #                 img_b64 = img_el.screenshot_as_base64
    #
    #                 if len(img_b64) < 500:
    #                     dbg(f"⚠️ Image small ({len(img_b64)} chars). Waiting reload...")
    #                     time.sleep(2)
    #                     retries += 1
    #                 else:
    #                     dbg(f"Image captured correctly ({len(img_b64)} chars)")
    #                     break
    #
    #             except Exception as e:
    #                 dbg(f"Retry screenshot failed: {e}")
    #                 retries += 1
    #                 time.sleep(2)
    #
    #         if len(img_b64) < 500:
    #             dbg("❌ CAPTCHA image still invalid after retries — refreshing attempt.")
    #             continue
    #
    #         data_uri = f"data:image/jpeg;base64,{img_b64}"
    #
    #         dbg("Sending createTask to 2Captcha…")
    #         create_payload = {
    #             "clientKey": API_KEY,
    #             "task": {
    #                 "type": "ImageToTextTask",
    #                 "body": data_uri,
    #                 "numeric": 1,
    #                 "minLength": 4,
    #                 "maxLength": 7,
    #                 "phrase": False,
    #                 "case": False,
    #                 "math": False,
    #                 "comment": "AWS numeric CAPTCHA"
    #             }
    #         }
    #         create_resp = post_with_retry(CREATE_URL, create_payload)
    #         if create_resp.get("errorId", 1) != 0:
    #             raise RuntimeError(f"createTask error: {create_resp}")
    #         task_id = create_resp["taskId"]
    #         dbg(f"taskId = {task_id}")
    #
    #         dbg("Polling result…")
    #         solution_text = None
    #         for _ in range(30):
    #             time.sleep(2)
    #             res = post_with_retry(RESULT_URL, {"clientKey": API_KEY, "taskId": task_id})
    #             if res.get("status") == "ready":
    #                 solution_text = res["solution"]["text"]
    #                 break
    #         if not solution_text:
    #             raise RuntimeError("2Captcha timed out")
    #
    #         dbg(f"Solved: {solution_text}")
    #
    #         dbg("Typing solution like human…")
    #         inp = driver.find_element(By.NAME, "captchaGuess")
    #         inp.clear()
    #         type_like(inp, solution_text)
    #
    #         dbg("Clicking Submit…")
    #         submit_btn = wait.until(EC.element_to_be_clickable((
    #             By.XPATH, "//span[normalize-space()='Submit']/ancestor::button[1]"
    #         )))
    #         submit_btn.click()
    #
    #         dbg("Waiting 2s for validation…")
    #         time.sleep(2)
    #
    #         still_there = driver.find_elements(By.CSS_SELECTOR, 'img[alt="captcha"]')
    #         if not still_there:
    #             dbg("CAPTCHA gone. Reporting correct.")
    #             post_with_retry(REPORT_OK, {"clientKey": API_KEY, "taskId": task_id})
    #             dbg("Done.")
    #             break
    #         else:
    #             dbg("CAPTCHA still visible. Reporting incorrect & retrying.")
    #             post_with_retry(REPORT_BAD, {"clientKey": API_KEY, "taskId": task_id})
    #     else:
    #         dbg("Failed after all attempts.")
    #
    #     time.sleep(5)
    #
    # except:
    #     try:
    #         driver.switch_to.default_content()
    #     except:
    #         pass
    #     pass



    # from selenium.common.exceptions import NoSuchElementException



    # ==============================
    # LOOP CHECK EVERY 5 SECONDS
    # ==============================
    while True:
        if is_verify_email_page(driver):
            print("✅ This is the AWS VERIFY EMAIL page!")
            break
        else:

            print("⏳ Not on verify-email page yet... checking again in 5 seconds.")

        time.sleep(5)

    show_email_banner(driver, f"{WorkSheet} 📧 EMAIL: {email_aws} {order_id} ")

    # # --- human typing ---
    # def type_like(elem, text, lo=0.30, hi=0.60):
    #     try:
    #         elem.click()
    #     except:
    #         pass
    #     for ch in text:
    #         elem.send_keys(ch)
    #         time.sleep(random.uniform(lo, hi))

    # ── 2Captcha cfg ─────────────────────────────────────────────────────────────
    API_KEY = "9bf3536f21a91fb8e151ba099319944a"
    CREATE_URL = "https://api.2captcha.com/createTask"
    RESULT_URL = "https://api.2captcha.com/getTaskResult"
    REPORT_OK = "https://api.2captcha.com/reportCorrect"
    REPORT_BAD = "https://api.2captcha.com/reportIncorrect"
    OCR_HOST = "api.2captcha.com"

    def ensure_dns(host):
        try:
            socket.getaddrinfo(host, 443)
        except socket.gaierror:
            raise RuntimeError(f"Cannot resolve {host}")

    def post_with_retry(url, payload, retries=6, backoff=2):
        for i in range(1, retries + 1):
            try:
                r = requests.post(url, json=payload, timeout=15)
                r.raise_for_status()
                return r.json()
            except (requests.ConnectionError, requests.Timeout):
                if i == retries:
                    raise
                time.sleep(backoff ** i)



    import imaplib, re, os, time
    from email import message_from_bytes


    IMAP_HOST = 'imap.gmail.com'
    IMAP_PORT = 993

    TARGET_ALIAS = email
    TARGET_SUBJECT = 'Verify your email address'

    USERNAME = os.environ.get('EMAIL_USER') or 'aneesarana461@gmail.com'
    PASSWORD_gmail = os.environ.get('EMAIL_PASS') or 'mseyhzonlwjsqxqc'

    CODE_REGEX = re.compile(r'\b(\d{6})\b')

    def get_aws_code(to_addr, subject_kw, tries=4, sleep_sec=5):
        for attempt in range(1, tries + 1):
            dbg(f"[IMAP] Attempt {attempt}/{tries}")
            try:
                mail = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT)
                mail.login(USERNAME, PASSWORD_gmail)
                mail.select('INBOX')
                typ, data = mail.search(None, f'TO "{to_addr}"', f'SUBJECT "{subject_kw}"')
                ids = data[0].split() if typ == 'OK' else []
                dbg(f"[IMAP] Found {len(ids)} msgs")
                if ids:
                    # newest last
                    raw = mail.fetch(ids[-1], '(RFC822)')[1][0][1]
                    msg = message_from_bytes(raw)
                    body = ""
                    if msg.is_multipart():
                        for part in msg.walk():
                            if part.get_content_type() == 'text/plain' and not part.get_content_disposition():
                                body += part.get_payload(decode=True).decode(errors='ignore')
                    else:
                        body = msg.get_payload(decode=True).decode(errors='ignore')

                    codes = CODE_REGEX.findall(body)
                    if codes:
                        code = codes[0]
                        dbg(f"[IMAP] Got code: {code}")
                        mail.logout()
                        return code
                    else:
                        dbg("[IMAP] No 6‑digit code in body")
                mail.logout()
            except Exception as e:
                dbg(f"[IMAP] Error: {e}")
            dbg(f"[IMAP] Sleeping {sleep_sec}s before retry…")
            time.sleep(sleep_sec)
        return None

    # ── Fetch OTP ────────────────────────────────────────────────────────────────
    otp_code = get_aws_code(TARGET_ALIAS, TARGET_SUBJECT)

    if not otp_code:
        dbg("FAILED: No OTP code received.")
    else:
        dbg("Typing OTP…")
        driver.switch_to.default_content()
        otp_inp = wait.until(EC.presence_of_element_located((By.ID, "otp")))
        otp_inp.clear()
        type_like(otp_inp, otp_code)

        dbg("Clicking final Submit…")
        submit_btn = wait.until(EC.element_to_be_clickable((
            By.XPATH,
            "//button[@class='full-width-button_full-width-button__4tYiw awsui_button_vjswe_lssc8_157 awsui_variant-primary_vjswe_lssc8_230']"
        )))
        submit_btn.click()
        dbg("OTP submitted.")



    # input("Press Enter after entering the OTP code manually...")
    #

    # otp = wait_for_otp(order_id)
    # otp = input("Please enter the OTP code received in the email: ")
    #
    # print("✅ OTP RECEIVED:", otp)
    #
    # show_email_banner(driver, f"{WorkSheet} 📧 EMAIL: {email_aws} ✅ OTP RECEIVED:{otp} ")
    #
    # otp_inp = wait.until(EC.presence_of_element_located((By.ID, "otp")))
    # otp_inp.clear()
    # type_like(otp_inp, otp)
    #
    # dbg("Clicking final Submit…")
    # submit_btn = wait.until(EC.element_to_be_clickable((
    #     By.XPATH,
    #     "//button[@class='full-width-button_full-width-button__4tYiw awsui_button_vjswe_lssc8_157 awsui_variant-primary_vjswe_lssc8_230']"
    # )))
    # submit_btn.click()
    # dbg("OTP submitted.")



    # Code = input("Enter the code: ")

    time.sleep(random.randint(1, 2))

    humanish_scroll_to_bottom(driver)

    time.sleep(random.randint(2, 5))

    import secrets, string



    try:
        wait = WebDriverWait(driver, 10)

        # time.sleep(2)
        # pwd_el = wait.until(EC.element_to_be_clickable((By.ID, "password")))
        # pwd_el.send_keys(PASSWORD)

        pwd_el = wait.until(EC.element_to_be_clickable((By.ID, "password")))

        # Use the helper instead of sending all at once
        type_like(pwd_el, PASSWORD)

        time.sleep(1)
        # re_el = wait.until(EC.element_to_be_clickable((By.ID, "rePassword")))
        # re_el.send_keys(PASSWORD)

        re_el = wait.until(EC.element_to_be_clickable((By.ID, "rePassword")))
        type_like(re_el, PASSWORD)

        time.sleep(1)
        button2 = driver.find_element(By.XPATH, "//span[normalize-space()='Continue (step 1 of 5)']")

        ActionChains(driver).move_to_element(button2).click().perform()

        # driver.implicitly_wait(4)
    except:
        input("Press Enter to continue... Failed at password step")
        pass
    # try:
    #     time.sleep(1)
    #     driver.find_element(By.XPATH, "//span[normalize-space()='Continue (step 1 of 5)']").click()
    # except:
    #     pass
    driver.implicitly_wait(15)
    # time.sleep(7)

    cur = driver.current_url

    delay = random.randint(2, 5)
    print(f"Waiting {delay} seconds before clicking Close...")
    time.sleep(delay)

    try:
        time.sleep(1)
        wait = WebDriverWait(driver, 10)

        # dbg("On accountplan → clicking Choose paid plan")

        try:
            # Wait up to 20 seconds until the element is visible & clickable
            wait = WebDriverWait(driver, 20)
            print("Clicking on View detail")

            humanish_scroll_to_bottom(driver)

            time.sleep(1)

            view_details = wait.until(
                EC.element_to_be_clickable((By.XPATH, "//div[text()='View additional details']"))
            )

            # Scroll into center of screen
            # driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", view_details)
            print("Clicking")
            # time.sleep(1)
            view_details.click()

            # 2) Wait 5–7 seconds
            # 2) Wait random 6–15 seconds
            delay = random.randint(2, 5)
            print(f"Waiting {delay} seconds before clicking Close...")
            time.sleep(delay)

            # 3) Click "Close"
            # Wait until "Close" is clickable
            close_button = wait.until(
                EC.element_to_be_clickable((By.XPATH, "//span[text()='Close']"))
            )

            # Scroll into center of screen
            # driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", close_button)
            time.sleep(1)
            close_button.click()
        except:
            pass

        time.sleep(3)

        delay = random.randint(2, 5)
        print(f"Waiting {delay} seconds before clicking AWS plan...")
        time.sleep(delay)

        # ---- DEFAULT LOGIC ----
        if plan_choice == "free":
            xpath = "//span[normalize-space()='Choose free plan']/ancestor::button[1]"
            print("👉 Selecting FREE plan")
        else:
            xpath = "//span[normalize-space()='Choose paid plan']/ancestor::button[1]"
            print("👉 Selecting PAID plan (default)")

        # ---- CLICK ----
        btn = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))

        ActionChains(driver) \
            .move_to_element(btn) \
            .pause(0.3) \
            .click() \
            .perform()


    except:
        print(f"Error handling plan selection")
        input("Press Enter to continue... Failed at plan selection")
        # dbg(f"Error handling plan selection: {e}")

    wait = WebDriverWait(driver, 15)


    try:
        time.sleep(3)

        # check url still on registration page
        cur = driver.current_url
        if "accountplan" in cur:
            btn = wait.until(EC.element_to_be_clickable((
                By.XPATH, "//span[normalize-space()='Choose paid plan']/ancestor::button[1]"
            )))
            btn.click()

            # input("Press Enter to continue... Not on account registration page")
            # return
        else:
            print("On account registration page")
    except:
        print(f"Error verifying still on accountplan page")
        # input("Press Enter to continue... Failed at verifying accountplan page")
        time.sleep(7)
        pass

    full_name = f"{FIRST_NAME} {LAST_NAME}"

    def click_account_type(driver, value=None, label_text=None, timeout=15):

        """
        Clicks the AWS UI radio for accountType.
          - value: "Professional" or "Personal"
          - label_text: e.g. "Business - for your work, school, or organization"
        One of value or label_text must be provided.
        """
        if not value and not label_text:
            raise ValueError("Provide value=('Professional'|'Personal') or label_text='Business ...'")

        wait = WebDriverWait(driver, timeout)

        # 1) Try by value (native input)
        inp = None
        if value:
            try:
                inp = wait.until(EC.presence_of_element_located((
                    By.XPATH, f"//input[@type='radio' and @name='accountType' and @value='{value}']"
                )))
            except:
                inp = None

        # 2) Fallback: resolve input via visible label text
        if inp is None and label_text:
            # Find the visible label span, go up to its wrapper, then down to the real input
            xpath = (
                "//span[contains(@class,'awsui_content')]"
                f"//span[contains(normalize-space(.), {repr(label_text)})]"
                "/ancestor::span[contains(@class,'awsui_label-wrapper')]"
                "//span[contains(@class,'awsui_control')]//input[@type='radio' and @name='accountType']"
            )
            inp = wait.until(EC.presence_of_element_located((By.XPATH, xpath)))

        # 3) Scroll into view (use the control wrapper if present)
        ctrl = inp.find_element(By.XPATH, "./ancestor::span[contains(@class,'awsui_control')][1]")
        driver.execute_script("arguments[0].scrollIntoView({block:'center'});", ctrl)
        time.sleep(random.uniform(0.15, 0.35))

        # 4) Try a normal click on the input first
        try:
            wait.until(EC.element_to_be_clickable((By.XPATH, "."))).click()
        except:
            # 5) JS fallback: click + dispatch events so React/AWSUI detects it
            driver.execute_script("""
                        const el = arguments[0];
                        el.click();
                        el.checked = true;
                        el.dispatchEvent(new Event('input', { bubbles: true }));
                        el.dispatchEvent(new Event('change', { bubbles: true }));
                    """, inp)

        # 6) Verify (use property, not @checked attribute)
        if not inp.is_selected():
            # last-resort: click the control circle (styled SVG/span) to trigger pointer events
            circle = ctrl.find_element(By.XPATH, ".//svg | .")
            driver.execute_script("arguments[0].scrollIntoView({block:'center'});", circle)
            try:
                circle.click()
            except Exception:
                driver.execute_script("""
                            const el = arguments[0];
                            el.click && el.click();
                        """, circle)
            if not inp.is_selected():
                raise RuntimeError("Radio still not selected")

    # time.sleep(random.uniform(10, 25))

    sleep_time = random.uniform(3, 5)
    print(sleep_time)

    time.sleep(sleep_time)

    # try:
    #
    #     # usage
    #     click_account_type(driver, "Personal")  # or "Personal"
    # except Exception as e:
    #     print(f"Error selecting account type Personal: {e}")
    #     input("Press Enter to continue... Failed at selecting account type")
    #     pass

    time.sleep(random.uniform(0.2, 0.6))

    # balance = get_balance()
    # print(f"💰 Balance: ${balance:.2f}")
    #
    # activation_id, phone_aws = rent_number()
    # if phone_aws.startswith("1") and len(phone_aws) == 11:
    #     phone_aws = phone_aws[1:]
    # else:
    #     print("Number Okay")
    # print(f"📱 AWS Phone: {phone_aws}")
    # print(f"🆔 Activation ID: {activation_id}")







    # 2) Text inputs (human-like typing)
    fields = {
        "address.fullName": firstname + " " + lastname,
        # "address.company": COMPANY,

        "address.addressLine1": ADDRESS,
        "address.city": CityValue,
        # "address.state": "KY",
        "address.postalCode": ZipValue,
        "address.phoneNumber": PHONE,
        # "address.addressLine2": "Apt 4B"  # optional
    }

    humanish_scroll_to_bottom(driver)

    try:
        for name_attr, value in fields.items():
            el = wait.until(EC.presence_of_element_located((By.NAME, name_attr)))

            # Use clean typing only for phone field
            if name_attr == "address.phoneNumber":

                while True:
                    # user_input = input("📞 Enter phone number (digits only): ").strip()
                    phonenumber1 = wait_for_new_valid_phone(sheet)

                    # execution continues ONLY after valid phone exists
                    print("🚀 Proceeding with phone:", phonenumber1)

                    user_input = phonenumber1
                    if user_input.isdigit():
                        value = user_input
                        phonenumber = value
                        break
                    else:
                        print("❌ Invalid input! Please enter digits only (no letters or symbols).")


                # # Ask user for phone number
                # while True:
                #     user_input = input("📞 Enter phone number (digits only): ").strip()
                #     if user_input.isdigit():
                #         value = user_input
                #         phonenumber = value
                #         break
                #     else:
                #         print("❌ Invalid input! Please enter digits only (no letters or symbols).")

                value = user_input
                phonenumber = value


                type_like_clean(el, value)

            else:
                type_like(el, value)

            time.sleep(random.uniform(1, 2))

        STATE_VALUE = StateValue

        # 1️⃣ Click State dropdown
        state_btn = wait.until(EC.element_to_be_clickable((By.ID, "address.state")))
        ActionChains(driver).move_to_element(state_btn).pause(0.2).click().perform()

        # 2️⃣ Wait until dropdown is OPEN
        dropdown = wait.until(EC.presence_of_element_located((
            By.XPATH, "//div[@role='dialog' and @aria-hidden='false']"
        )))

        # 3️⃣ Get ACTIVE combobox inside visible dropdown
        state_input = wait.until(EC.element_to_be_clickable((
            By.XPATH, "//div[@role='dialog' and @aria-hidden='false']//input[@role='combobox']"
        )))

        driver.execute_script("arguments[0].focus();", state_input)
        time.sleep(0.2)

        # 4️⃣ Clear safely
        state_input.send_keys(Keys.CONTROL, "a")
        state_input.send_keys(Keys.BACKSPACE)
        time.sleep(0.3)

        # 5️⃣ Type state
        state_input.send_keys(STATE_VALUE)
        time.sleep(0.8)  # IMPORTANT: let results render

        # 6️⃣ CLICK FIRST RESULT (ENTER DOES NOT WORK)
        first_option = wait.until(EC.element_to_be_clickable((
            By.XPATH,
            "//div[@role='dialog' and @aria-hidden='false']"
            "//div[@role='listbox']//div[@role='option'][1]"
        )))

        driver.execute_script("arguments[0].scrollIntoView({block:'center'});", first_option)
        ActionChains(driver).move_to_element(first_option).pause(0.2).click().perform()

        print(f"✅ State selected via click: {STATE_VALUE}")
    except:
        input("Press Enter to continue... Failed at filling address fields")

    # # 3) Country = United States (if not already selected)
    # country_select = wait.until(EC.element_to_be_clickable((By.ID, "awsui-select-1")))
    # country_select.click()
    # us = wait.until(EC.element_to_be_clickable(
    #     (By.XPATH, "//div[@id='awsui-select-1-dropdown']//span[normalize-space()='United States']")))
    # us.click()

    def click_customer_agreement(driver):
        try:
            # Wait for the checkbox to appear anywhere on the page
            checkbox = WebDriverWait(driver, 25).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, "input[type='checkbox'][aria-label*='Customer Agreement']")
                )
            )

            # Scroll into view (helps if hidden or overlapped)
            driver.execute_script("arguments[0].scrollIntoView({block:'center'});", checkbox)

            # Try normal click first
            try:
                checkbox.click()
            except:
                pass

            # If still unchecked, force check via JS + React event propagation
            driver.execute_script("""
                const el = arguments[0];
                if (!el.checked) {
                    el.checked = true;
                    el.dispatchEvent(new Event('input', { bubbles: true }));
                    el.dispatchEvent(new Event('change', { bubbles: true }));
                }
                // Also trigger on parent wrapper if needed (React synthetic)
                const parent = el.closest('.awsui_control_1wepg_1ri2i_206') || el.parentElement;
                if (parent) {
                    parent.click();
                    parent.dispatchEvent(new Event('click', { bubbles: true }));
                }
            """, checkbox)

            # Verify
            checked = driver.execute_script("return arguments[0].checked;", checkbox)
            if checked:
                print("✅ Agreement checkbox successfully ticked!")
            else:
                raise Exception("Still not checked")

        except Exception as e:
            print(f"⚠️ Failed to click checkbox automatically: {e}")
            input("Press Enter to continue manually...")

    # Example usage
    click_customer_agreement(driver)

    time.sleep(random.uniform(3, 6))


    time.sleep(1)

    import time

    def wait_for_partial_url(driver, partial_url, interval=5, timeout=300):
        """
        Wait until `partial_url` appears anywhere in the current URL.
        """
        start = time.time()

        while time.time() - start < timeout:
            current_url = driver.current_url
            print(f"🔍 Current URL: {current_url}")

            if partial_url in current_url:
                print("✅ Target partial URL detected!")
                return True

            time.sleep(interval)



    # # Scroll up like a human
    # human_scroll(driver, "up", step=80, delay_range=(0.05, 0.15))

    save_creds(email, PASSWORD, full_name, STATE)

    try:
        save_to_sheet(email, PASSWORD, card_number, phonenumber)
    except:
        print("Failed to save to sheet")

    # time.sleep(100)

    # Random float between 80 and 120
    sleep_time = random.uniform(2, 4)
    print(sleep_time)

    time.sleep(sleep_time)

    # 5) Continue
    Button_3 = wait.until(EC.element_to_be_clickable((
        By.XPATH, "//span[normalize-space()='Agree and Continue (step 2 of 5)']/ancestor::button[1]"
    )))

    ActionChains(driver).move_to_element(Button_3).click().perform()
    # Random float between 80 and 120
    sleep_time = random.uniform(1, 3)
    print(sleep_time)

    time.sleep(sleep_time)



    time.sleep(random.uniform(1, 3))

    # ========================
    # 2. Card Number
    # ========================
    # card_number_input = driver.find_element(By.ID, "cardNumber")
    # card_number_input.send_keys(card_number)  # dummy test Visa number

    try:

        # def type_like(driver, el, text, lo=0.12, hi=0.38, mistake_chance=0.08):
        #     """
        #     Hybrid typing:
        #     - Selenium clicks the element to focus it
        #     - PyAutoGUI types with human-like delays, mistakes, and backspaces
        #     """
        #     try:
        #         # Scroll into view and click element
        #         ActionChains(driver).move_to_element(el).click().perform()
        #         time.sleep(0.5)  # small delay to ensure focus
        #     except:
        #         pass
        #
        #     for ch in text:
        #         # Chance of making a typo
        #         if random.random() < mistake_chance:
        #             wrong_char = random.choice("abcdefghijklmnopqrstuvwxyz")
        #             pyautogui.write(wrong_char)
        #             time.sleep(random.uniform(lo, hi))
        #             pyautogui.press("backspace")
        #             time.sleep(random.uniform(lo, hi))
        #
        #         # Type the correct character
        #         pyautogui.write(ch)
        #         time.sleep(random.uniform(lo, hi))

        # type_like(driver.find_element(By.ID, "cardNumber"), cardNumber)
        # ========================
        # 6. Cardholder's Name
        # ========================
        # name_input = driver.find_element(By.ID, "accountHolderName")
        # name_input.clear()
        # name_input.send_keys(FULL_NAME)

        PARTIAL_URL = 'register#/paymentinformation'
        try:
            wait_for_partial_url(driver, PARTIAL_URL, interval=5, timeout=600)
            print("🎉 AWS payment page reached!")

        except Exception as e:
            print(e)



        time.sleep(random.uniform(5,8))

        # card_number_input = driver.find_element(By.ID, "cardNumber")
        # card_number_input.send_keys(card_number)  # dummy test Visa number

        type_like_clean(driver.find_element(By.ID, "cardNumber"), card_number)

        print("Card Entered")




        time.sleep(random.uniform(1, 2))

        humanish_scroll_to_bottom(driver)
        try:

            # ========================
            # 3. Expiration Month
            # ========================
            exp_month_btn = driver.find_element(By.ID, "expirationMonth")
            exp_month_btn.click()
            print("EXP Clicked")

            time.sleep(random.uniform(1, 2))

            # pick "05" (May) as an example from option list
            september_span = wait.until(
                EC.element_to_be_clickable((By.XPATH, f"//span[normalize-space()='{EXP_Month_CC}']"))
            )
            september_span.click()

            print("EXP Selected")



            time.sleep(random.uniform(1, 2))

            # ========================
            # 4. Expiration Year
            # ========================
            exp_year_btn = driver.find_element(By.ID, "expirationYear")
            exp_year_btn.click()

            print("EXP Clicked")

            time.sleep(random.uniform(1, 2))
            #
            # # pick "2026" as an example
            exp_year_option = wait.until(
                EC.element_to_be_clickable((By.XPATH, f"//span[normalize-space()='{EXP_Year_CC}']"))
            )
            exp_year_option.click()
            #
            print("EXP Selected")

            time.sleep(random.uniform(1, 2))

            # ========================
            # 5. CVV
            # ========================
            # cvv_input = driver.find_element(By.ID, "sor.cvv")
            # cvv_input.send_keys(CVV)  # dummy test CVV

            type_like_clean(driver.find_element(By.ID, "sor.cvv"), CVV)
            print("CVV Selected")
        except:
            print("Error selecting expiration date or entering CVV Please Do manually")
            pass




        time.sleep(random.uniform(1, 2))

        # type_like(driver.find_element(By.ID, "accountHolderName"), FULL_NAME)
        try:

            print("CVV Selected")
            time.sleep(random.uniform(1, 2))
            type_like(driver.find_element(By.ID, "accountHolderName"), firstname+" "+lastname)
            print("FULL_NAME Entered")

            time.sleep(random.uniform(1, 2))

            # 5) Continue
            button_5 = wait.until(EC.element_to_be_clickable((
                By.XPATH, "//span[normalize-space()='Continue (step 3 of 5)']/ancestor::button[1]"
            )))

            time.sleep(2)

            show_email_banner(driver, f"{WorkSheet} {phonenumber} ")
        except:
            pass



        # input("Press Enter to continue...")

        try:
            ActionChains(driver).move_to_element(button_5).click().perform()
            print("Button Pressed")
        except:
            print("Button not found")
            # input("Press Enter to continue...")
            pass

        sleep_time = random.uniform(3, 6)
        print(sleep_time)

        try:
            ActionChains(driver).move_to_element(button_5).click().perform()
            print("Button Pressed")
        except:
            print("Button not found")
            # input("Press Enter to continue...")
            pass

        time.sleep(sleep_time)

    except:
        print("Name Failed")
        # input("Press Enter to continue...")
        pass

    try:

        PARTIAL_URL = '/identityverification'
        try:
            wait_for_partial_url(driver, PARTIAL_URL, interval=5, timeout=600)
            print("🎉 AWS identityverification page reached!")

        except Exception as e:
            print(e)

        time.sleep(random.uniform(3, 6))

        # name_input = driver.find_element(By.ID, "awsui-input-11")
        # name_input.clear()
        # name_input.send_keys("8053056656")
        humanish_scroll_to_bottom(driver)
        time.sleep(random.uniform(1, 2))

        # type_like_clean(driver.find_element(By.ID, "phoneNumber"), phonenumber)






        time.sleep(random.uniform(1, 3))

        try:
            # 5) Continue
            button_6 = wait.until(EC.element_to_be_clickable((
                By.XPATH, "//span[normalize-space()='Send SMS (step 4 of 5)']/ancestor::button[1]"
            ))).click()

            # ActionChains(driver).move_to_element(button_6).click().perform()
        except:
            pass

        print("Send SMS Clicked")
        time.sleep(3)


        try:
            # 5) Continue
            button_6 = wait.until(EC.element_to_be_clickable((
                By.XPATH, "//span[normalize-space()='Send SMS (step 4 of 5)']/ancestor::button[1]"
            )))

            ActionChains(driver).move_to_element(button_6).click().perform()
        except:
            pass

        time.sleep(3)
        # show_email_banner(driver, f"{WorkSheet} {phonenumber} ")


        # print("Waiting for OTP SMS...")
        #
        # otp_sms = wait_for_sms(activation_id)
        # print(f"✅ OTP RECEIVED: {otp_sms}")
        #
        # otp_inp_sms = wait.until(
        #     EC.presence_of_element_located((By.ID, "smsPin"))
        # )
        #
        # otp_inp_sms.clear()
        # type_like(otp_inp_sms, otp_sms)
        #
        # dbg("Clicking OTP submit button…")
        #
        # submit_btn = wait.until(
        #     EC.element_to_be_clickable((
        #         By.CSS_SELECTOR,
        #         "button[data-testid='identity-verification-sms-submit-button']"
        #     ))
        # )
        #
        # submit_btn.click()
        # dbg("✅ OTP submitted successfully.")

        time.sleep(10)

        # try:
        #     driver.find_element(
        #         By.CSS_SELECTOR,
        #         "form#SupportPlan button[type='submit']"
        #     ).click()
        # except:
        #     pass



        # show_email_banner(driver, f"{WorkSheet} {phonenumber} ✅ OTP RECEIVED: {otp}")

    except:
        pass
# ##########################################################################################
#         try:
#
#             ensure_dns(OCR_HOST)
#             dbg("DNS OK for 2Captcha")
#
#             wait = WebDriverWait(driver, 20)
#             MAX_ATTEMPTS = 4
#
#             for attempt in range(1, MAX_ATTEMPTS + 1):
#                 dbg(f"=== Attempt {attempt} ===")
#                 try:
#                     driver.switch_to.default_content()
#                 except:
#                     pass
#
#                 dbg("Locating threat-mitigation iframe…")
#                 iframe = wait.until(EC.presence_of_element_located((
#                     By.ID, "core-container"
#                 )))
#                 driver.switch_to.frame(iframe)
#                 dbg("Switched into iframe")
#                 time.sleep(5)
#
#                 dbg("Grabbing CAPTCHA image…")
#                 img_b64 = ""
#                 retries = 0
#
#                 while len(img_b64) < 500 and retries < 6:  # <<--- length validation added
#                     try:
#                         img_el = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'img[alt="captcha"]')))
#                         img_b64 = img_el.screenshot_as_base64
#
#                         if len(img_b64) < 500:
#                             dbg(f"⚠️ Image small ({len(img_b64)} chars). Waiting reload...")
#                             time.sleep(2)
#                             retries += 1
#                         else:
#                             dbg(f"Image captured correctly ({len(img_b64)} chars)")
#                             break
#
#                     except Exception as e:
#                         dbg(f"Retry screenshot failed: {e}")
#                         retries += 1
#                         time.sleep(2)
#
#                 if len(img_b64) < 500:
#                     dbg("❌ CAPTCHA image still invalid after retries — refreshing attempt.")
#                     continue
#
#                 data_uri = f"data:image/jpeg;base64,{img_b64}"
#
#                 dbg("Sending createTask to 2Captcha…")
#                 create_payload = {
#                     "clientKey": API_KEY,
#                     "task": {
#                         "type": "ImageToTextTask",
#                         "body": data_uri,
#                         "numeric": 1,
#                         "minLength": 4,
#                         "maxLength": 7,
#                         "phrase": False,
#                         "case": False,
#                         "math": False,
#                         "comment": "AWS numeric CAPTCHA"
#                     }
#                 }
#                 create_resp = post_with_retry(CREATE_URL, create_payload)
#                 if create_resp.get("errorId", 1) != 0:
#                     raise RuntimeError(f"createTask error: {create_resp}")
#                 task_id = create_resp["taskId"]
#                 dbg(f"taskId = {task_id}")
#
#                 dbg("Polling result…")
#                 solution_text = None
#                 for _ in range(30):
#                     time.sleep(2)
#                     res = post_with_retry(RESULT_URL, {"clientKey": API_KEY, "taskId": task_id})
#                     if res.get("status") == "ready":
#                         solution_text = res["solution"]["text"]
#                         break
#                 if not solution_text:
#                     raise RuntimeError("2Captcha timed out")
#
#                 dbg(f"Solved: {solution_text}")
#
#                 dbg("Typing solution like human…")
#                 inp = driver.find_element(By.NAME, "captchaGuess")
#                 inp.clear()
#                 type_like(inp, solution_text)
#
#                 dbg("Clicking Submit…")
#                 submit_btn = wait.until(EC.element_to_be_clickable((
#                     By.XPATH, "//span[normalize-space()='Submit']/ancestor::button[1]"
#                 )))
#                 submit_btn.click()
#
#                 dbg("Waiting 2s for validation…")
#                 time.sleep(2)
#
#                 still_there = driver.find_elements(By.CSS_SELECTOR, 'img[alt="captcha"]')
#                 if not still_there:
#                     dbg("CAPTCHA gone. Reporting correct.")
#                     post_with_retry(REPORT_OK, {"clientKey": API_KEY, "taskId": task_id})
#                     dbg("Done.")
#                     break
#                 else:
#                     dbg("CAPTCHA still visible. Reporting incorrect & retrying.")
#                     post_with_retry(REPORT_BAD, {"clientKey": API_KEY, "taskId": task_id})
#             else:
#                 dbg("Failed after all attempts.")
#
#             time.sleep(5)
#
#         except:
#             try:
#                 driver.switch_to.default_content()
#             except:
#                 pass
#             pass
#     except:
#         pass
#     ##########################################################################################


    #define emty key
    key = ""

    #############################################

    import random, string, time, pyotp
    def add_mfa(driver):
        """Automate AWS IAM MFA setup and return the secret key (retries up to 3x)."""
        MAX_RETRIES = 6

        for attempt in range(1, MAX_RETRIES + 1):
            try:
                print(f"\n🔁 Attempt {attempt}/{MAX_RETRIES} to add MFA...")

                driver.get(
                    "https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-2#/security_credentials/mfa")
                time.sleep(1)
                TARGET = "security_credentials"

                for handle in driver.window_handles:
                    driver.switch_to.window(handle)
                    if TARGET in driver.current_url:
                        print("✅ Switched to MFA tab")
                        break
                time.sleep(1)

                device_name = ''.join(random.choices(string.ascii_lowercase, k=random.randint(3, 5)))
                print("💻 Device Name:", device_name)

                # === Helper functions ===
                def scroll_and_click(element):
                    driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", element)
                    time.sleep(0.5)
                    element.click()

                def scroll_and_type(element, text):
                    driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", element)
                    time.sleep(0.5)
                    element.send_keys(text)

                # === Step 1: Enter device name ===
                el = WebDriverWait(driver, 15).until(
                    EC.visibility_of_element_located((By.CSS_SELECTOR, 'div[data-testid="device-name-input"] input'))
                )
                scroll_and_type(el, device_name)

                # === Step 2: Select Authenticator app ===
                el = WebDriverWait(driver, 15).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, "//div[@data-value='virtual']//h4[contains(.,'Authenticator app')]"))
                )
                scroll_and_click(el)
                time.sleep(2)

                # (Optional human scroll if defined)
                try:
                    humanish_scroll_to_bottom(driver)
                except Exception:
                    pass

                # === Step 3: Click Next ===
                el = WebDriverWait(driver, 15).until(
                    EC.element_to_be_clickable((By.XPATH, "//button[.//span[text()='Next']]"))
                )
                scroll_and_click(el)

                # === Step 4: Show secret key ===
                el = WebDriverWait(driver, 15).until(
                    EC.element_to_be_clickable((By.XPATH, "//a[normalize-space()='Show secret key']"))
                )
                scroll_and_click(el)

                # === Step 5: Extract key ===
                key = WebDriverWait(driver, 15).until(
                    EC.visibility_of_element_located(
                        (By.XPATH, "//div[contains(@class,'awsui_content_xjuzf')]/div//span"))
                ).text
                print("🔑 Secret Key:", key)

                time.sleep(2)

                # === Step 6: First OTP ===
                totp = pyotp.TOTP(key)
                first_code = totp.now()

                time.sleep(2)
                el = WebDriverWait(driver, 15).until(
                    EC.visibility_of_element_located((By.CSS_SELECTOR, "div[data-testid='virtualMFACode1'] input"))
                )
                scroll_and_type(el, first_code)

                # === Step 7: Wait for second OTP ===
                print("Waiting for 2nd OTP...")
                while True:
                    time.sleep(7)
                    new_code = totp.now()
                    if new_code != first_code:
                        break

                el = WebDriverWait(driver, 15).until(
                    EC.visibility_of_element_located((By.CSS_SELECTOR, "div[data-testid='virtualMFACode2'] input"))
                )
                scroll_and_type(el, new_code)
                print("✅ Both OTPs entered successfully.")

                # === Step 8: Click Add MFA ===
                el = WebDriverWait(driver, 15).until(
                    EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Add MFA']]"))
                )
                scroll_and_click(el)
                print("🎉 MFA Added Successfully!")

                # ✅ Success — return key immediately
                return key

            except Exception as e:
                print(f"⚠️ Attempt {attempt} failed: {e}")
                if attempt < MAX_RETRIES:
                    print("🔁 Retrying in 3s...")
                    driver.get("https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-2#/security_credentials/")
                    time.sleep(3)
                else:
                    print("❌ All 3 attempts failed. Skipping MFA setup.")
                    pass  # Continue program even if this fails

        # Return None if all failed
        return None

    def navigate_to_ec2(driver):
        """Navigate AWS console after registration confirmation and open EC2."""
        try:
            # ✅ Check if registration confirmation page is open
            if "https://aws.amazon.com/registration-confirmation/" in driver.current_url:
                print("📄 On registration confirmation page — clicking Sign in to console...")

                # Wait and click Sign in to console
                aws_btn = WebDriverWait(driver, 20).until(
                    EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*='console.aws.amazon.com/console/home']"))
                )
                driver.execute_script("arguments[0].click();", aws_btn)

                # Wait for redirect / console login page to load
                WebDriverWait(driver, 30).until(
                    EC.any_of(
                        EC.url_contains("signin.aws.amazon.com"),
                        EC.title_contains("Sign in"),
                        EC.presence_of_element_located((By.TAG_NAME, "body"))
                    )
                )
                print("✅ Redirected to AWS sign-in page.")

            # ⏳ Sleep for a random duration between
            sleep_time = random.uniform(6, 13)
            print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
            time.sleep(sleep_time)

            humanish_scroll_to_bottom(driver)

            sleep_time = random.uniform(7, 15)
            print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
            time.sleep(sleep_time)

            # 1️⃣ Click hamburger menu
            menu_btn = WebDriverWait(driver, 15).until(
                EC.element_to_be_clickable((By.XPATH, "//nav//button[@aria-label='Open side navigation']"))
            )
            driver.execute_script("arguments[0].click();", menu_btn)
            print("✅ Side navigation clicked.")

            sleep_time = random.uniform(3, 7)
            print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
            time.sleep(sleep_time)

            # 2️⃣ Wait until the expanded nav becomes visible
            WebDriverWait(driver, 15).until(
                EC.visibility_of_element_located(
                    (By.XPATH, "//nav[@aria-label='Side navigation' and @aria-hidden='false']"))
            )
            time.sleep(1.5)  # allow animation to finish

            # 3️⃣ Click "All services"
            all_services = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH,
                                            "//nav[@aria-label='Side navigation']//span[normalize-space()='All services']/ancestor::a"))
            )
            driver.execute_script("arguments[0].click();", all_services)
            print("✅ Clicked 'All services'.")

            time.sleep(2)

            time.sleep(3)  # allow full page render
            driver.execute_script("""
                  for (const a of document.querySelectorAll('a')) {
                    if (a.innerText.trim() === 'EC2' || a.href.includes('/ec2/')) {
                      a.click();
                      break;
                    }
                  }
                """)
            print("✅ JS fallback: EC2 clicked via direct DOM scan.")

            time.sleep(10)

        except Exception as e:
            print(f"❌ Error in navigate_to_ec2: {e}")

    def launch_ec2_instances(driver):
        """Launch EC2 Windows instances with randomized server name and parameters.
           Returns the generated servername."""
        try:
            # 🧩 Generate random 3–5 letter name
            servername = ''.join(random.choices(string.ascii_lowercase, k=random.randint(3, 5)))
            print("💻 servername :", servername)


            driver.get(f"https://{Region}.console.aws.amazon.com/ec2/home?region={Region}#LaunchInstances:")
            # driver.get("https://us-east-2.console.aws.amazon.com/ec2/home?region=us-east-2#LaunchInstances:")

            time.sleep(5)
            WebDriverWait(driver, 120).until(lambda d: d.execute_script("return document.readyState") == "complete")
            time.sleep(5)

            # 1️⃣ Switch into the EC2 launch iframe
            iframe = WebDriverWait(driver, 240).until(
                EC.frame_to_be_available_and_switch_to_it((By.ID, "instance-lx-react-frame"))
            )
            print("✅ Switched into EC2 launch iframe.")

            # 2️⃣ Now find and type server name in the instance name field
            name_input = WebDriverWait(driver, 120).until(
                EC.visibility_of_element_located((By.XPATH, "//div[@data-analytics='instance-name-input']//input"))
            )
            name_input.clear()
            name_input.send_keys(servername)
            print(f"✅ Pasted {servername} into instance name field.")

            # 3️⃣ Click the Windows tile
            windows_btn = WebDriverWait(driver, 30).until(
                EC.element_to_be_clickable((By.XPATH, "//div[@data-testid='getting-started-tile-3']"))
            )
            driver.execute_script("arguments[0].click();", windows_btn)
            print("✅ Clicked on 'Windows' OS tile")

            time.sleep(5)

            # ✅ Find the AMI dropdown button
            dropdown = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH,
                                                "//div[@data-id='inline-ami-selector']//button[contains(@class,'awsui_button-trigger')]"))
            )

            # ✅ Scroll into view and force open dropdown
            driver.execute_script("""
                arguments[0].scrollIntoView({behavior:'smooth', block:'center'});
                arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles:true}));
                arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles:true}));
                arguments[0].click();
                """, dropdown)
            print("✅ Dropdown expansion triggered via JS events")

            # ✅ Locate Windows Server 2022 Base
            option = driver.find_element(By.XPATH, "//span[contains(text(),'Microsoft Windows Server 2022 Base')]")
            driver.execute_script("""
                arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});
                arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles: true}));
                arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles: true}));
                arguments[0].click();
                """, option)
            print("✅ Clicked 'Microsoft Windows Server 2022 Base' option")









            #################################################

            # ✅ Locate the Instance Type dropdown button and open it
            dropdown_btn = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH,
                                                "//div[@data-id='instance-type-selector']//button[contains(@class,'awsui_button-trigger')]"))
            )
            driver.execute_script("""
                arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});
                arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles:true}));
                arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles:true}));
                arguments[0].click();
                """, dropdown_btn)
            print("✅ Instance type dropdown opened")

            # ✅ Select 't2.large'
            option = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH, f"//span[contains(text(),'{InstanceType}')]"))
            )
            driver.execute_script("""
                arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});
                arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles: true}));
                arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles: true}));
                arguments[0].click();
                """, option)
            print(f"✅ Clicked '{InstanceType}' option")

            time.sleep(3)




            ###############################################################################

            # ✅ Locate the Instance Type dropdown button and open it
            dropdown_btn = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH,
                                                "//div[@data-id='instance-type-selector']//button[contains(@class,'awsui_button-trigger')]"))
            )
            driver.execute_script("""
                            arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});
                            arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles:true}));
                            arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles:true}));
                            arguments[0].click();
                            """, dropdown_btn)
            print("✅ Instance type dropdown opened")

            # ✅ Select 't2.large'
            option = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.XPATH, f"//span[contains(text(),'{InstanceType}')]"))
            )
            driver.execute_script("""
                            arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});
                            arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles: true}));
                            arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles: true}));
                            arguments[0].click();
                            """, option)
            print(f"✅ Clicked '{InstanceType}' option")

            time.sleep(3)



            # ✅ Set number of instances
            instances_input = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, "div[data-id='number-of-instances-summary'] input[type='number']"))
            )
            instances_input.clear()
            instances_input.send_keys(TotalRDPNeed)
            driver.execute_script("""
                arguments[0].dispatchEvent(new Event('input', { bubbles: true }));
                arguments[0].dispatchEvent(new Event('change', { bubbles: true }));
                """, instances_input)
            print("✅ Set 'Number of instances' to 4")

            # # ================= CLICK ADVANCED DETAILS =================
            # adv = WebDriverWait(driver, 30).until(lambda d: d.find_element(
            #     By.XPATH, "//span[normalize-space()='Advanced details' and @id[contains(.,'-trigger')]]"))
            # driver.execute_script("arguments[0].scrollIntoView({block:'center'});arguments[0].click();", adv)
            # time.sleep(2)
            # print("✅ Advanced details expanded")
            #
            # # ================= PASTE USER DATA =================
            # # ================= PASTE USER DATA =================
            # try:
            #
            #     USER_DATA_PATH = os.path.abspath("user_data.ps1")
            #
            #     with open(USER_DATA_PATH, "w", encoding="utf-8") as f:
            #         f.write(USER_DATA_SCRIPT)
            #
            #     print(f"📄 User data file created: {USER_DATA_PATH}")
            #
            #     # ============================================================
            #     # 2️⃣ FIND HIDDEN FILE INPUT (REAL TARGET)
            #     # ============================================================
            #
            #     file_input = WebDriverWait(driver, 30).until(
            #         EC.presence_of_element_located((
            #             By.XPATH,
            #             "//input[@type='file' and @aria-label='User data file upload button']"
            #         ))
            #     )
            #
            #     # ============================================================
            #     # 3️⃣ UPLOAD FILE (THIS COMMITS USER DATA)
            #     # ============================================================
            #
            #     file_input.send_keys(USER_DATA_PATH)
            #     print("📤 User data file uploaded via file input")
            #
            #     time.sleep(2)
            #
            #     # ============================================================
            #     # 4️⃣ VERIFY AWS ACCEPTED THE FILE (REAL CHECK)
            #     # ============================================================
            #
            #     filename = os.path.basename(USER_DATA_PATH)
            #
            #     uploaded = driver.execute_script("""
            #                 return [...document.querySelectorAll("span,div,button")]
            #                   .some(e => e.textContent && e.textContent.includes(arguments[0]));
            #                 """, filename)
            #
            #     # ============================================================
            #     # 5️⃣ OPTIONAL CLEANUP
            #     # ============================================================
            #
            #     os.remove(USER_DATA_PATH)
            #     print("🧹 User data file removed")
            # except:
            #     pass

            time.sleep(1)

            # ✅ Click "Launch instance" button
            launch_btn = WebDriverWait(driver, 25).until(
                EC.element_to_be_clickable((By.XPATH, "//span[normalize-space()='Launch instance']"))
            )
            driver.execute_script("""
                arguments[0].scrollIntoView({behavior:'smooth', block:'center'});
                arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles:true}));
                arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles:true}));
                arguments[0].click();
                """, launch_btn)
            print("🚀 Clicked on 'Launch instance' successfully")

            time.sleep(1)

            # ✅ Key pair field
            keypair_input = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "div[data-id='key-pair-name'] input[type='text']"))
            )
            keypair_input.clear()
            keypair_input.send_keys(servername)
            driver.execute_script("""
                arguments[0].dispatchEvent(new Event('input', { bubbles: true }));
                arguments[0].dispatchEvent(new Event('change', { bubbles: true }));
                """, keypair_input)
            print("✅ Entered servername into Key Pair Name field")

            # ✅ Final launch button
            launch_btn = WebDriverWait(driver, 25).until(
                EC.element_to_be_clickable((By.XPATH, "(//span[normalize-space()='Launch instance'])[2]"))
            )
            driver.execute_script("""
                arguments[0].scrollIntoView({behavior:'smooth', block:'center'});
                arguments[0].dispatchEvent(new MouseEvent('mousedown', {bubbles:true}));
                arguments[0].dispatchEvent(new MouseEvent('mouseup', {bubbles:true}));
                arguments[0].click();
                """, launch_btn)
            print("🚀 Clicked on final 'Launch instance' successfully")

            # Ensure TotalRDPNeed is int
            total_rdp = int(TotalRDPNeed)

            if "xlarge" in InstanceType.lower() or total_rdp > 1:
                print("xlarge")
                # ✅ Retry handling
                try:
                    sleep_time = random.uniform(35, 45)
                    print(f"Sleeping for {sleep_time:.2f} seconds...")
                    time.sleep(sleep_time)

                    WebDriverWait(driver, 10).until(
                        EC.element_to_be_clickable((By.XPATH, "//button[@data-id='retry-failed']"))
                    ).click()

                    sleep_time = random.uniform(7, 15)
                    print(f"Sleeping for {sleep_time:.2f} seconds...")
                    time.sleep(sleep_time)
                except:
                    pass


            time.sleep(3)
            return servername  # ✅ Return the generated name at the end

        except Exception as e:
            print(f"❌ Error in launch_ec2_instances: {e}")
            return None  # Return None if it fails

    import os
    import sys

    def get_pem_path(server_name):
        """
        Returns (pem_path, pem_content_or_None).

        Priority:
        1) <app_dir>/downloaded_files/<server_name>.pem
        2) Windows Downloads folder

        Works for .py and frozen .exe.
        """

        # ===============================
        # BASE DIRECTORY (py / exe safe)
        # ===============================
        if getattr(sys, 'frozen', False):
            base_dir = os.path.dirname(sys.executable)
        else:
            base_dir = os.path.dirname(os.path.abspath(__file__))

        # ===============================
        # APP DOWNLOAD DIRECTORY
        # ===============================
        app_download_dir = os.path.join(os.path.expanduser("~"), "downloaded_files")
        os.makedirs(app_download_dir, exist_ok=True)

        pem_filename = f"{server_name}.pem"
        app_pem_path = os.path.join(app_download_dir, pem_filename)

        # ===============================
        # 1️⃣ CHECK APP downloaded_files
        # ===============================
        if os.path.isfile(app_pem_path):
            print(f"📄 PEM found in app folder: {app_pem_path}")
            try:
                with open(app_pem_path, "r", encoding="utf-8") as f:
                    return app_pem_path, f.read()
            except Exception as e:
                print(f"⚠️ Failed to read PEM from app folder: {e}")

        # ===============================
        # 2️⃣ CHECK WINDOWS DOWNLOADS
        # ===============================
        # downloads_dir = os.path.join(os.path.expanduser("~"), "Downloads")
        downloads_dir = os.path.join(os.path.expanduser("~"), "Downloads")
        downloads_pem_path = os.path.join(downloads_dir, pem_filename)

        if os.path.isfile(downloads_pem_path):
            print(f"📥 PEM found in Windows Downloads: {downloads_pem_path}")
            try:
                with open(downloads_pem_path, "r", encoding="utf-8") as f:
                    return downloads_pem_path, f.read()
            except Exception as e:
                print(f"⚠️ Failed to read PEM from Downloads: {e}")

        # ===============================
        # ❌ NOT FOUND ANYWHERE
        # ===============================
        print(f"❌ PEM not found in app folder or Windows Downloads: {pem_filename}")
        return app_pem_path, None


    def get_public_dns_and_password(driver, timeout=20):
        """
        Returns (public_dns, password) by switching into the `compute-react-frame`
        iframe and reading the UI text. Uses multiple fallbacks for AWSUI/React.
        """
        wait = WebDriverWait(driver, timeout)

        time.sleep(5)

        try:
            driver.switch_to.default_content()
        except:
            pass

        # 1) switch to iframe (wait until present)
        try:
            iframe = wait.until(EC.presence_of_element_located((By.ID, "compute-react-frame")))
            driver.switch_to.frame(iframe)
        except:
            pass

        def js_get(selector):
            script = """
                const sel = arguments[0];
                const el = document.querySelector(sel);
                return el ? el.textContent.trim() : null;
                """
            return driver.execute_script(script, selector)

        # 2) Try to get Public DNS via XPath candidates first
        public_dns = None
        xpath_candidates = [
            "//span[contains(@class,'awsui_text-to-display') or contains(@class,'awsui_text-to-copy')]",
            "//div[.//div[contains(., 'Public DNS')]]//span[contains(text(),'.compute.amazonaws.com')]",
            "//span[contains(text(),'.compute.amazonaws.com')]",
        ]
        for xp in xpath_candidates:
            try:
                el = driver.find_element(By.XPATH, xp)
                txt = el.text.strip()
                if txt:
                    public_dns = txt
                    break
            except Exception:
                pass

        # If still None, try JS selectors
        if not public_dns:
            for sel in ("span.awsui_text-to-display_ljpwc_30z5b_13",
                        "span.awsui_text-to-copy_ljpwc_30z5b_9",
                        "span[title*='compute.amazonaws.com']",
                        "span"):
                try:
                    txt = js_get(sel)
                    if txt and "compute.amazonaws.com" in txt:
                        public_dns = txt
                        break
                except Exception:
                    continue

        # 3) Try to get Password via XPath candidates
        password = None
        pwd_xpaths = [
            "//div[normalize-space()='Password']/following::div[contains(@class,'awsui_child')][1]",
            "//div[normalize-space()='Password']/following::div[.//*[contains(@class,'awsui_child')]][1]",
            "//div[normalize-space()='Password']/following::div[1]/div",
            "//div[contains(., 'Password')]/following::div[contains(@class,'awsui_child')][1]",
            "//div[contains(@class,'awsui_child') and normalize-space()!=''][last()]"
        ]
        for xp in pwd_xpaths:
            try:
                el = driver.find_element(By.XPATH, xp)
                txt = el.text.strip()
                if txt:
                    password = txt
                    break
            except Exception:
                pass

        # If password still not found, try JS heuristic around copy button
        if not password:
            try:
                script = """
                    const btn = document.querySelector("button[data-analytics='copy-to-clipboard-password'], button[data-analytics*='copy-to-clipboard-password']");
                    if (!btn) return null;
                    let p = btn.parentElement;
                    for (let i=0; i<5 && p; i++){
                        const textEl = p.querySelector("div.awsui_child_18582_whr0e_149, div.awsui_child_18582_whr0e_149 + div, div.awsui_child_18582_whr0e_149 ~ div");
                        if (textEl && textEl.textContent.trim().length>0) return textEl.textContent.trim();
                        p = p.parentElement;
                    }
                    const els = Array.from(document.querySelectorAll("div, span"));
                    for (const el of els.reverse()){
                        const t = el.textContent.trim();
                        if (t.length>=8 && /[A-Za-z0-9\\$\\-\\._\\=\\;\\,]/.test(t)) return t;
                    }
                    return null;
                    """
                password = driver.execute_script(script)
            except Exception:
                password = None

        try:
            driver.switch_to.default_content()
        except:
            pass

        public_dns = public_dns.strip() if public_dns else None
        password = password.strip() if password else None

        print("🔎 Public DNS:", public_dns)
        print("🔑 Password:", password)

        return public_dns, password

    def retrieve_rdp_details(driver, server_name, timeout=20):
        """
        Runs the full sequence:
          - switch into compute-react-frame iframe
          - click "RDP client" tab
          - click "Get password"
          - read PEM file via get_pem_path(server_name)
          - inject PEM contents into the React/AWSUI textarea
          - click "Decrypt password"
          - read Public DNS and Password via get_public_dns_and_password
        Returns:
          (pem_path, pem_data, public_dns, password)
        """
        wait = WebDriverWait(driver, timeout)

        # ✅ Switch into the iframe
        wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "compute-react-frame")))
        print("🪟 Switched into 'compute-react-frame' iframe")

        # ✅ Wait for and click the "RDP client" tab
        rdp_tab = wait.until(
            EC.element_to_be_clickable((By.XPATH, "//button[@data-testid='RDP']//span[text()='RDP client']"))
        )
        rdp_tab.click()
        print("💻 Clicked on 'RDP client' tab successfully!")

        # ✅ Wait for the RDP details section to load
        time.sleep(2)

        get_pw_btn = wait.until(
            EC.element_to_be_clickable((By.XPATH, "//button[.//span[normalize-space()='Get password']]"))
        )
        get_pw_btn.click()
        print("🔐 Clicked on 'Get password' button successfully!")

        # PEM file handling
        pem_path, pem_data = get_pem_path(server_name)
        print("pem_data:", pem_data)

        # 🚀 Ultra-compatible React/AWSUI text injection
        textarea = wait.until(
            EC.presence_of_element_located((By.XPATH, "//textarea[@placeholder='Private key contents']"))
        )

        driver.execute_script("""
        const el = arguments[0];
        const val = arguments[1];

        // Define setter from the element's prototype
        const setter = Object.getOwnPropertyDescriptor(
            window.HTMLTextAreaElement.prototype, 'value'
        ).set;
        setter.call(el, val);

        // Fire React/AWSUI events
        el.dispatchEvent(new Event('input',  { bubbles: true }));
        el.dispatchEvent(new Event('change', { bubbles: true }));
        el.dispatchEvent(new Event('blur',   { bubbles: true }));
        """, textarea, pem_data)

        print("✅ PEM value injected using React-compatible setter")

        # Then click “Decrypt password”
        decrypt_btn = wait.until(
            EC.element_to_be_clickable((By.XPATH, "//span[normalize-space()='Decrypt password']/ancestor::button"))
        )
        driver.execute_script("arguments[0].click();", decrypt_btn)
        print("🔓 Clicked 'Decrypt password'")

        # After decrypting, fetch public DNS and password from the UI
        public_dns, password = get_public_dns_and_password(driver, timeout=timeout)

        return pem_path, pem_data, public_dns, password

    def save_rdp_data(EMAIL, PASSWORD, card_number, phonenumber, key, dns, pwd, sheet,RDP_region_RAM=RDP_region_RAM):
        """
        Save credentials and RDP details to 'RDP_Details' sheet with retry protection.

        Columns:
        A → EMAIL, PASSWORD, card_number, phonenumber (comma-separated)
        B → key
        C → dns
        D → pwd
        """
        max_retries = 2
        attempt = 0

        while attempt <= max_retries:
            try:
                # Get the target sheet
                spreadsheet = sheet.spreadsheet
                rdp_sheet = spreadsheet.worksheet("RDP_Details1")

                # Prepare values for columns A–D
                col1 = f"{EMAIL}, {PASSWORD}, {card_number}, {phonenumber}"
                col2 = key
                col3 = dns
                col4 = pwd
                col5 = RDP_region_RAM

                # Append new row
                rdp_sheet.append_row([col1, col2, col3, col4,col5])

                print(f"✅ Saved to RDP_Details → {EMAIL} / {dns}")
                break  # success

            except Exception as e:
                attempt += 1
                print(f"⚠️ Attempt {attempt} failed while saving: {e}")

                if attempt > max_retries:
                    print("❌ Skipping this entry after 2 failed attempts.")
                    break

                time.sleep(2)



    # # ⏳ Sleep for a random duration between 2m and 2m15s
    # sleep_time = random.uniform(120, 135)
    # print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
    # time.sleep(sleep_time)

    # try:
    #     navigate_to_ec2(driver)
    # except:
    #     print("Failed to navigate to EC2")
    #     input("Press Enter to continue...")
    #     pass

    # input("Should I proceed EC2 Launch Now?   ")


    def ask_next_action():
        print("\nWhat do you want to do next?")
        print("1️⃣  Proceed to create EC2 now")
        print("2️⃣  Add MFA first")

        while True:
            choice = input("Enter 1 or 2: ").strip()

            if choice in ("1", "2"):
                return choice
            else:
                print("❌ Invalid choice. Please enter 1 or 2.")

    choice = ask_next_action()

    if choice == "2":
        key = add_mfa(driver)
        print("Returned Secret Key:", key)

        save_to_sheet(
            email,
            PASSWORD,
            card_number,
            key,
            sheet
        )

        choice = ask_next_action()
        if choice == "2":
            key = add_mfa(driver)
            print("Returned Secret Key:", key)

            save_to_sheet(
                email,
                PASSWORD,
                card_number,
                key,
                sheet
            )

    print("➡️ Proceeding to EC2 launch...")
    # continue EC2 creation logic here

    print("✅ Account successful!")



    try:
        servername = launch_ec2_instances(driver)
        print("Returned servername:", servername)

        # ⏳ Sleep for a random duration between 2m and 2m15s
        sleep_time = random.uniform(10, 15)
        print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
        time.sleep(sleep_time)

        print("⏳ Waiting for launch confirmation...")
    except Exception as e:
        show_browser_error(driver, f"EC2 launch failed: {e}")
        print(f"❌ Error launching EC2 instances: {e}")
        input("Error launching EC2 instances: Please Do Manually  ")

    try:

        #witch to default content
        try:
            driver.switch_to.default_content()
        except:
            pass

        # # ✅ Wait for the launch iframe
        # launch_iframe = WebDriverWait(driver, 20).until(
        #     EC.presence_of_element_located((By.ID, "instance-lx-react-frame"))
        # )
        #
        # driver.switch_to.frame(launch_iframe)
        # print("✅ Switched to Launch iframe")
        #
        #
        # # ✅ Wait for success flash
        # flash = WebDriverWait(driver, 60).until(
        #     EC.presence_of_element_located(
        #         (By.XPATH,
        #          "//div[contains(@class,'awsui-flash')]//*[contains(text(),'successful') or contains(text(),'Successfully')]")
        #     )
        # )
        #
        # print("✅ Success Flash Found:")
        # print(flash.text)
        #
        # # ✅ Extract instance IDs and URLs
        # links = driver.find_elements(
        #     By.XPATH,
        #     "//a[contains(@href,'InstanceDetails') and contains(text(),'i-')]"
        # )
        #
        # instances = [
        #     {"id": link.text.strip(), "url": link.get_attribute("href")}
        #     for link in links
        # ]
        #
        # print("\n🚀 Launched Instances:")
        # for inst in instances:
        #     print(f"• {inst['id']} → {inst['url']}")

        timeout = 40

        # ✅ Wait for "i-" in page source
        WebDriverWait(driver, timeout).until(
            lambda d: "i-" in d.page_source
        )

        # ✅ JavaScript to search main + iframe DOM
        js = r"""
        const frame = document.getElementById("instance-lx-react-frame");
        const iframeDoc = frame?.contentWindow?.document;

        function extract(doc) {
            return [...doc.querySelectorAll("a")]
              .filter(a => a.textContent.trim().startsWith("i-"))
              .map(a => ({
                id: a.textContent.trim(),
                url: a.href
              }));
        }

        let results = [];

        // ✅ Look in iframe (preferred)
        if (iframeDoc) {
            results = extract(iframeDoc);
            if (results.length > 0) return results;
        }

        // ✅ Fallback → look in main DOM
        results = extract(document);
        return results;
        """

        instances = driver.execute_script(js)

        # ✅ Confirm only
        if instances:
            print("\n🚀 Instances Found:")
            for inst in instances:
                print(f"• {inst['id']} → {inst['url']}")
            try:
                driver.switch_to.default_content()
            except:
                pass

            main_window = driver.current_window_handle

            # print("Do You want to Create 2fa now?")
            # input("Do You want to Create 2fa now?   ")
            key = add_mfa(driver)
            print("Returned Secret Key:", key)

            save_to_sheet(email, PASSWORD, card_number, key, sheet)

            # ⏳ Sleep for a random duration between 2m and 2m15s
            sleep_time = random.uniform(9, 12)
            print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
            time.sleep(sleep_time)
        else:
            print("⚠️ Instances list is EMPTY")
            try:
                driver.switch_to.default_content()
            except:
                pass



        # print("\n🚀 Instances Found:")
        # for inst in instances:
        #     print(f"• {inst['id']} → {inst['url']}")





        for inst in instances:
            connect_url = inst["url"].replace("#InstanceDetails:", "#ConnectToInstance:")
            print(f"\n🔗 Opening {inst['id']} → {connect_url}")

            # ✅ Open in new tab
            driver.execute_script(f"window.open('{connect_url}', '_blank');")

            # ✅ Wait until a new tab is created
            WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)

            # ✅ Switch to the last opened tab
            new_tab = driver.window_handles[-1]
            driver.switch_to.window(new_tab)

            # ✅ Verify that tab loaded correct URL (wait until URL contains ConnectToInstance)
            try:
                WebDriverWait(driver, 15).until(lambda d: "ConnectToInstance" in d.current_url)
                print(f"🧭 Switched to tab for {inst['id']} successfully.")
            except:
                print(f"⚠️ Tab may not have loaded correctly for {inst['id']}, current URL: {driver.current_url}")

            # ✅ Call your custom function
            try:
                pem_path, pem_data, dns, pwd = retrieve_rdp_details(driver, servername)
                print(f"✅ Retrieved RDP details for {inst['id']}:")
                print(f"   pem_path: {pem_path}")
                print(f"   dns: {dns}")
                print(f"   pwd: {pwd[:6]}******")

                try:
                    save_rdp_data(email, PASSWORD, card_number, phonenumber, key, dns, pwd, sheet)
                except:
                    pass
            except Exception as e:
                show_browser_error(driver, f"Failed retrieving RDP details for {inst['id']}: {e}")
                print(f"❌ Error for {inst['id']}: {e}")

            # 💤 Optional pause before opening next
            time.sleep(3)

        print("\n🎯 All instance tabs opened and processed. None closed.")

    except Exception as e:
        show_browser_error(driver, f"detail getting failed: {e}")
        print(f"❌ detail getting failed: {e}")
        input("❌ detail getting failed:  Please Do Manually  ")



    choice = ask_next_action()


    #############################################
    if choice == "1":
        try:
            servername = launch_ec2_instances(driver)
            print("Returned servername:", servername)

            # ⏳ Sleep for a random duration between 2m and 2m15s
            sleep_time = random.uniform(10, 15)
            print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
            time.sleep(sleep_time)

            print("⏳ Waiting for launch confirmation...")
        except Exception as e:
            show_browser_error(driver, f"EC2 launch failed: {e}")
            print(f"❌ Error launching EC2 instances: {e}")
            input("Error launching EC2 instances: Please Do Manually  ")

        try:

            #witch to default content
            try:
                driver.switch_to.default_content()
            except:
                pass

            # # ✅ Wait for the launch iframe
            # launch_iframe = WebDriverWait(driver, 20).until(
            #     EC.presence_of_element_located((By.ID, "instance-lx-react-frame"))
            # )
            #
            # driver.switch_to.frame(launch_iframe)
            # print("✅ Switched to Launch iframe")
            #
            #
            # # ✅ Wait for success flash
            # flash = WebDriverWait(driver, 60).until(
            #     EC.presence_of_element_located(
            #         (By.XPATH,
            #          "//div[contains(@class,'awsui-flash')]//*[contains(text(),'successful') or contains(text(),'Successfully')]")
            #     )
            # )
            #
            # print("✅ Success Flash Found:")
            # print(flash.text)
            #
            # # ✅ Extract instance IDs and URLs
            # links = driver.find_elements(
            #     By.XPATH,
            #     "//a[contains(@href,'InstanceDetails') and contains(text(),'i-')]"
            # )
            #
            # instances = [
            #     {"id": link.text.strip(), "url": link.get_attribute("href")}
            #     for link in links
            # ]
            #
            # print("\n🚀 Launched Instances:")
            # for inst in instances:
            #     print(f"• {inst['id']} → {inst['url']}")

            timeout = 40

            # ✅ Wait for "i-" in page source
            WebDriverWait(driver, timeout).until(
                lambda d: "i-" in d.page_source
            )

            # ✅ JavaScript to search main + iframe DOM
            js = r"""
            const frame = document.getElementById("instance-lx-react-frame");
            const iframeDoc = frame?.contentWindow?.document;
    
            function extract(doc) {
                return [...doc.querySelectorAll("a")]
                  .filter(a => a.textContent.trim().startsWith("i-"))
                  .map(a => ({
                    id: a.textContent.trim(),
                    url: a.href
                  }));
            }
    
            let results = [];
    
            // ✅ Look in iframe (preferred)
            if (iframeDoc) {
                results = extract(iframeDoc);
                if (results.length > 0) return results;
            }
    
            // ✅ Fallback → look in main DOM
            results = extract(document);
            return results;
            """

            instances = driver.execute_script(js)

            print("\n🚀 Instances Found:")
            for inst in instances:
                print(f"• {inst['id']} → {inst['url']}")

            try:
                driver.switch_to.default_content()
            except:
                pass

            main_window = driver.current_window_handle

            # print("Do You want to Create 2fa now?")
            # input("Do You want to Create 2fa now?   ")
            key = add_mfa(driver)
            print("Returned Secret Key:", key)
            #
            # save_to_sheet(email, PASSWORD, card_number, key, sheet)

            # ⏳ Sleep for a random duration between 2m and 2m15s
            sleep_time = random.uniform(9, 12)
            print(f"💤 Sleeping for {sleep_time:.2f} seconds...")
            time.sleep(sleep_time)



            for inst in instances:
                connect_url = inst["url"].replace("#InstanceDetails:", "#ConnectToInstance:")
                print(f"\n🔗 Opening {inst['id']} → {connect_url}")

                # ✅ Open in new tab
                driver.execute_script(f"window.open('{connect_url}', '_blank');")

                # ✅ Wait until a new tab is created
                WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)

                # ✅ Switch to the last opened tab
                new_tab = driver.window_handles[-1]
                driver.switch_to.window(new_tab)

                # ✅ Verify that tab loaded correct URL (wait until URL contains ConnectToInstance)
                try:
                    WebDriverWait(driver, 15).until(lambda d: "ConnectToInstance" in d.current_url)
                    print(f"🧭 Switched to tab for {inst['id']} successfully.")
                except:
                    print(f"⚠️ Tab may not have loaded correctly for {inst['id']}, current URL: {driver.current_url}")

                # ✅ Call your custom function
                try:
                    pem_path, pem_data, dns, pwd = retrieve_rdp_details(driver, servername)
                    print(f"✅ Retrieved RDP details for {inst['id']}:")
                    print(f"   pem_path: {pem_path}")
                    print(f"   dns: {dns}")
                    print(f"   pwd: {pwd[:6]}******")

                    try:
                        save_rdp_data(email, PASSWORD, card_number, phonenumber, key, dns, pwd, sheet)
                    except:
                        pass
                except Exception as e:
                    show_browser_error(driver, f"Failed retrieving RDP details for {inst['id']}: {e}")
                    print(f"❌ Error for {inst['id']}: {e}")

                # 💤 Optional pause before opening next
                time.sleep(3)

            print("\n🎯 All instance tabs opened and processed. None closed.")

        except Exception as e:
            show_browser_error(driver, f"detail getting failed: {e}")
            print(f"❌ detail getting failed: {e}")
            input("❌ detail getting failed:  Please Do Manually  ")


    #############################

    time.sleep(50000)

    #

    time.sleep(random.uniform(2, 5))

    cur = driver.current_url
    if cur.split("#/")[-1] == "paymentinformation":
        print("all done closing now")


        ###time.sleep(5000)

        # ----------------- After you expose fields -----------------
        FULL_NAME = f"{FIRST_NAME} {LAST_NAME}"
        save_creds(EMAIL, PASSWORD, FULL_NAME, STATE)

        time.sleep(random.uniform(1, 3))



    # Cleanup
    # driver.quit()
    input("TotalfAilure")
    time.sleep(50000)

    print("🧹 All done!")


if __name__ == "__main__":
    main()
