# -*- 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?departement=&motif_name_with_location_type=rdv_mentor_eric_45min-visio&public_link_organisation_id=3007"
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)
        r = requests.post(
            url,
            json={"chat_id": CHAT_ID, "text": msg},
            timeout=10
        )
        safe_print("TELEGRAM STATUS: " + str(r.status_code))
        safe_print("TELEGRAM RESPONSE: " + str(r.text))
    except Exception as e:
        safe_print("TELEGRAM ERROR: " + str(e))

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)))

        if is_available(html):
            safe_print("RDV DISPONIBLE - envoi notification")
            send_telegram(
                "RDV DISPONIBLE !\n\nCliquez ici pour prendre rendez-vous :\n" + URL
            )
        else:
            safe_print("Aucun RDV disponible")

        safe_print("CHECK OK")
    except Exception as e:
        safe_print("ERROR: " + str(e))

if __name__ == "__main__":
    main()