import subprocess
import time
import os
import traceback

# ===== CONFIG =====
DESKTOP = os.path.join(os.environ["USERPROFILE"], "Desktop")
PROXY_BAT = os.path.join(DESKTOP, "Proxy.bat")
SIGNUP_EXE = os.path.join(DESKTOP, "pinterest_SignupOnlyv2.exe")

PROXY_WAIT_SECONDS = 12
SIGNUP_TIMEOUT_SECONDS = 300
# ==================


# ---------- HARD KILL FUNCTIONS ----------

def kill_all_cmd():
    print("💣 Killing ALL cmd / bat windows...")
    subprocess.run(
        'taskkill /F /IM cmd.exe /T',
        shell=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL
    )


def kill_signup_exe():
    subprocess.run(
        'taskkill /F /IM pinterest_SignupOnlyv2.exe /T',
        shell=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL
    )


def kill_chrome():
    print("🧹 Closing all Chrome profiles...")
    subprocess.run(
        'taskkill /F /IM chrome.exe /T',
        shell=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL
    )
    subprocess.run(
        'taskkill /F /IM chromedriver.exe /T',
        shell=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL
    )


def count_cmd_windows():
    try:
        out = subprocess.check_output(
            'tasklist /FI "IMAGENAME eq cmd.exe"',
            shell=True
        ).decode(errors="ignore")

        count = out.lower().count("cmd.exe")
        return max(0, count - 1)  # subtract header
    except:
        return 0


# ---------- CORE ----------

def cleanup_end_of_iteration():
    kill_signup_exe()
    kill_chrome()

    cmd_before = count_cmd_windows()
    kill_all_cmd()
    time.sleep(2)
    cmd_after = count_cmd_windows()

    print(f"🧪 DEBUG: CMD windows before kill: {cmd_before}")
    print(f"🧪 DEBUG: CMD windows after kill : {cmd_after}")


def run_proxy():
    print("🌐 Starting Proxy.bat...")
    subprocess.Popen(
        f'start "" "{PROXY_BAT}"',
        shell=True,
        cwd=DESKTOP
    )

    print(f"⏳ Waiting {PROXY_WAIT_SECONDS} seconds for proxy...")
    time.sleep(PROXY_WAIT_SECONDS)


def run_signup():
    print("🚀 Starting pinterest_OnlySignup.exe...")
    proc = subprocess.Popen(
        f'"{SIGNUP_EXE}"',
        shell=True,
        cwd=DESKTOP
    )

    start_time = time.time()

    while True:
        if proc.poll() is not None:
            print("✅ Signup EXE finished")
            return True

        if time.time() - start_time > SIGNUP_TIMEOUT_SECONDS:
            print("⏱️ Signup timeout — killing EXE")
            kill_signup_exe()
            return False

        time.sleep(2)


def main():
    repeat_count = int(input("🔁 How many times should this repeat? : ").strip())

    for i in range(1, repeat_count + 1):
        print(f"\n===============================")
        print(f"🔄 Iteration {i}/{repeat_count}")
        print(f"===============================")

        run_proxy()
        run_signup()

        print("🧹 Cleaning EVERYTHING before next iteration...")
        cleanup_end_of_iteration()

        time.sleep(3)

    print("\n🎉 All iterations completed CLEANLY")


# ---------- NEVER AUTO-CLOSE ----------
if __name__ == "__main__":
    try:
        main()
    except Exception:
        traceback.print_exc()

    print("\n🛑 Script finished. Press ENTER to close.")
    input()
