import re
import requests

def get_puzzle_number():
    url = "https://cemantle.certitudes.org/"
    headers = {
        "User-Agent": "Mozilla/5.0",
    }
    resp = requests.get(url, headers=headers, timeout=10)
    if resp.status_code == 200:
        m = re.search(r'data-puzzle-number="(\d+)"', resp.text)
        if m:
            return m.group(1)
    raise Exception("Impossible de récupérer le numéro du puzzle")

def check_words_api(wordlist_path, output_path, max_words=None):
    puzzle_number = get_puzzle_number()
    url = f"https://cemantle.certitudes.org/score?n={puzzle_number}"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "Mozilla/5.0",
        "Origin": "https://cemantle.certitudes.org",
        "Referer": "https://cemantle.certitudes.org/",
    }
    with open(wordlist_path, 'r', encoding='utf-8') as fin:
        words = [w.strip() for w in fin if w.strip()]
    if max_words:
        words = words[:max_words]
    with open(output_path, 'w', encoding='utf-8') as fout:
        for idx, word in enumerate(words):
            data = f"word={word}".encode("utf-8")
            try:
                resp = requests.post(url, headers=headers, data=data, timeout=10)
                js = resp.json()
                if "s" in js:
                    fout.write(word + '\n')
                    print(f"Valide: {word}")
            except Exception as e:
                print(f"Erreur pour {word}: {e}")
    print(f"Tri terminé. Les mots valides sont dans {output_path}")

if __name__ == "__main__":
    check_words_api("english_words.txt", "cemantle_valid_english_words.txt")
