import threading
import time
import requests

# --- DIRECT HUGGING FACE BACKGROUND TARGETER ---
def maia_targeter_loop():
    # Explicitly define your connection parameters here
    TOKEN = "lip_OFiAuROPc2oEicqT1YQg"  # Your token hardcoded safely for your private space
    TARGET_BOTS = ["maia1", "maia5", "maia9"]
    
    # 20 second delay to give the primary engine space to spin up first
    time.sleep(20)
    print("[Background Matchmaker] Thread actively launched.")

    headers = {
        "Authorization": f"Bearer {TOKEN}"
    }
    
    challenge_data = {
        "rated": "false",
        "clock.limit": 180,      # 3 minutes
        "clock.increment": 0,    # 0 increment
        "variant": "standard",
        "keepAliveStream": "false"
    }

    while True:
        try:
            # 1. Ask Lichess if our bot profile is currently playing a match
            status_resp = requests.get("https://lichess.org/api/account", headers=headers)
            
            if status_resp.status_code == 200:
                is_playing = status_resp.json().get("playing", False)
                
                if is_playing:
                    # Bot is busy, sit back and let it finish the match
                    time.sleep(30)
                    continue
                
                # 2. Bot is idle! Attempt to target a Maia bot
                print("[Background Matchmaker] Bot is idle. Sending a targeted challenge...")
                for bot in TARGET_BOTS:
                    # Swapped out to the universal standard api endpoint
                    url = f"https://lichess.org/api/challenge/{bot}"
                    resp = requests.post(url, headers=headers, data=challenge_data)
                    
                    if resp.status_code == 200:
                        print(f"[Background Matchmaker] Success! Challenged {bot}.")
                        time.sleep(120)  # Sleep long enough for the game to initialize
                        break
                    elif resp.status_code == 429:
                        print("[Background Matchmaker] Rate limited by Lichess. Waiting 1 minute...")
                        time.sleep(60)
                        break
                    
                    time.sleep(5)  # Quick pause between trying different bots
            else:
                print(f"[Background Matchmaker] Error checking bot status: {status_resp.status_code}")
                
            time.sleep(45)  # Normal loop cycle time
            
        except Exception as e:
            print(f"[Background Matchmaker] Thread encountered an unexpected error: {e}")
            time.sleep(30)

# Immediately trigger the loop out-of-process so Hugging Face accepts the space start
threading.Thread(target=maia_targeter_loop, daemon=True).start()
# --------------------------------------------------