import pyautogui
import time

# --- CONFIGURATION ---
# Increase this if your game has longer loading screens
TIMEOUT_PER_STEP = 320  # Max seconds to wait for a specific button to appear
DELAY_BETWEEN_ACTIONS = 1.0  # Time to wait after a successful click
CHECK_INTERVAL = 0.5  # How often to scan the screen (seconds)

steps = [
    "dungeon.png",
    "match.png",
    "accept.png",
    "ready.png",
    "thumbsup.png",
    "thumbsup.png",
    "thumbsup.png",
    "back.png",
]

run_count = 0
print("=== Script Started ===")
print("Please navigate to the daily dungeon screen.")
time.sleep(3)  # Give you 3 seconds to switch to the game window

while True:
    print(f"\n--- Starting Run #{run_count + 1} ---")
    
    for i, step_image in enumerate(steps):
        print(f"[Step {i+1}/{len(steps)}] Looking for: {step_image}...")
        
        start_time = time.time()
        button_pos = None
        
        # Keep looking for the current step's button until it appears or times out
        while button_pos is None:
            # INTERRUPT CHECK: Always check for "accept.png" in case the game interrupts the flow
            for interrupt_img in ["accept.png"]:
                try:
                    interrupt_pos = pyautogui.locateCenterOnScreen(interrupt_img, confidence=0.8)
                    if interrupt_pos:
                        print(f"  [!] Interrupted by unexpected pop-up: {interrupt_img}. Clicking it.")
                        pyautogui.click(interrupt_pos)
                        time.sleep(DELAY_BETWEEN_ACTIONS)
                except Exception:
                    pass

            # Primary step detection
            try:
                button_pos = pyautogui.locateCenterOnScreen(step_image, confidence=0.8)
            except Exception:
                button_pos = None
                
            if button_pos:
                print(f"  [+] Found {step_image}! Clicking standard position...")
                pyautogui.click(button_pos)
                time.sleep(DELAY_BETWEEN_ACTIONS)
                break
                
            # Check for timeout
            if time.time() - start_time > TIMEOUT_PER_STEP:
                print(f"  [X] TIMEOUT: Failed to find '{step_image}' within {TIMEOUT_PER_STEP} seconds.")
                print("      The sequence is out of sync. Restarting the loop from Step 1...")
                break
                
            time.sleep(CHECK_INTERVAL)
            
        # If we broke out of the while loop because of a timeout, restart the entire run sequence
        if button_pos is None:
            break
    else:
        # This else block executes ONLY if the for-loop completes entirely without hitting a 'break' (timeout)
        run_count += 1
        print(f"\n========================")
        print(f" SUCCESS: Run #{run_count} completed!")
        print(f"========================")
        time.sleep(2)  # Pause before starting the next loop