import time
import requests

# --- CONFIGURATION ---
TOKEN = "lip_OFiAuROPc2oEicqT1YQg"  # Your Lichess Token
TARGET_BOTS = ["maia1", "maia5", "maia9"]

# Challenge settings (3 mins blitz, casual)
CHALLENGE_DATA = {
    "rated": "false",
    "clock.limit": 180,    # 180 seconds = 3 minutes
    "clock.increment": 0,  # 0 seconds increment
    "variant": "standard"
}
# ---------------------

HEADERS = {"Authorization": f"Bearer {TOKEN}"}

def check_my_bot_status():
    """Checks if your bot is currently busy playing a game."""
    try:
        response = requests.get("https://lichess.org/api/account", headers=HEADERS)
        if response.status_code == 200:
            # If the account data returns an active game ID, your bot is busy
            return response.json().get("playing", False)
    except Exception as e:
        print(f"Error checking status: {e}")
    return True # Default to True on failure to avoid spamming challenges

def send_challenge(target):
    """Sends a direct challenge to a specific bot."""
    url = f"https://lichess.org/api/challenge/{target}"
    try:
        response = requests.post(url, headers=HEADERS, data=CHALLENGE_DATA)
        if response.status_code == 200:
            print(f"[SUCCESS] Sent a challenge to {target}!")
            return True
        elif response.status_code == 400:
            # Often means the target bot is already completely full/busy
            print(f"[BUSY] Tried challenging {target}, but they declined or are full.")
        else:
            print(f"[INFO] Couldn't challenge {target}. Status Code: {response.status_code}")
    except Exception as e:
        print(f"Network error: {e}")
    return False

def main():
    print("Targeted Maia Matchmaker Loop Started...")
    print("This script will cycle through Maia 1, 5, and 9 whenever your bot is idle.")
    
    while True:
        # 1. Check if your bot is already playing someone else
        if check_my_bot_status():
            print("Your bot is currently in a match. Waiting 30 seconds...")
            time.sleep(30)
            continue
        
        # 2. If free, try to challenge the Maias one by one
        print("Your bot is idle! Attempting to challenge targets...")
        for bot in TARGET_BOTS:
            success = send_challenge(bot)
            if success:
                # Give Lichess a moment to process the match creation
                print("Match created successfully. Pausing script for 2 minutes...")
                time.sleep(120) 
                break 
            # Tiny cooldown between hitting different bots to avoid rate limits
            time.sleep(2)
            
        # Cooldown period before checking if your bot is idle again
        time.sleep(45)

if __name__ == "__main__":
    main()