# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import os
import sys
import requests

reload(sys)
sys.setdefaultencoding("utf-8")

os.chdir(os.path.dirname(os.path.abspath(__file__)))

URL = "https://rdv.anct.gouv.fr/prendre_rdv?date=2026-05-21+09%3A00%3A00+%2B0200&departement=&lieu_id=6965&motif_name_with_location_type=motif_test-public_office&public_link_organisation_id=3002"
STATE_FILE = os.path.join(os.path.dirname(__file__), "state.txt")
TOKEN = "8622262761:AAHSsOQqhBlVsX0EWkhOBKIW1nsQii3dTLc"
CHAT_ID = 5916747460

def safe_print(msg):
    try:
        if isinstance(msg, unicode):
            msg = msg.encode("utf-8", "ignore")
        sys.stdout.write(str(msg) + "\n")
        sys.stdout.flush()
    except:
        pass

def send_telegram(msg):
    try:
        url = "https://api.telegram.org/bot{}/sendMessage".format(TOKEN)
        requests.post(url, json={"chat_id": CHAT_ID, "text": msg}, timeout=10)
    except:
        safe_print("Telegram error")

def normalize(text):
    try:
        if isinstance(text, bytes):
            text = text.decode("utf-8", "ignore")
        text = text.lower()
        text = text.replace(u"\xe9", "e")
        text = text.replace(u"\xe8", "e")
        text = text.replace(u"\xea", "e")
        text = text.replace(u"\xe0", "a")
        text = text.replace(u"\xf9", "u")
        text = text.replace(u"\xe7", "c")
    except:
        text = ""
    return text

def is_available(html):
    html = normalize(html)
    if "aucun creneau" in html: return False
    if "malheureusement" in html: return False
    if "complet" in html: return False
    if "choisir un creneau" in html: return True
    if "selectionner un creneau" in html: return True
    if "prendre un rendez-vous" in html: return True
    return False

def main():
    try:
        safe_print("BOT START")
        headers = {"User-Agent": "Mozilla/5.0", "Accept-Language": "fr-FR,fr;q=0.9"}
        r = requests.get(URL, headers=headers, timeout=20)
        r.encoding = "utf-8"
        html = r.text
        safe_print("STATUS: " + str(r.status_code))
        safe_print("HTML SIZE: " + str(len(html)))

        current = "available" if is_available(html) else "none"
        previous = None
        if os.path.exists(STATE_FILE):
            with open(STATE_FILE, "r") as f:
                previous = f.read().strip()

        if current != previous:
            if current == "available":
                send_telegram("RDV DISPONIBLE ANCT : " + URL)
            else:
                safe_print("Toujours rien")
            with open(STATE_FILE, "w") as f:
                f.write(current)

        safe_print("CHECK OK: " + current)
    except Exception as e:
        safe_print("ERROR: " + str(e))

if __name__ == "__main__":
    main()