"""
Agent d'impression FacControl Restaurant.

A installer sur un PC du restaurant quand le serveur FacControl est en ligne :
l'agent recupere les bons cuisine / bar et les pre-additions dans la file
d'impression, puis les envoie aux imprimantes thermiques du restaurant
(reseau, USB, serie ou imprimante Windows).

Uniquement la bibliotheque standard Python 3.8+ (pywin32 / pyserial optionnels).
Lancement : python faccontrol_impression_agent.py [config.json]
"""

import base64
import json
import logging
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

import escpos

VERSION = "1.0.0"
BASE = Path(__file__).resolve().parent


def charger_config(chemin):
    with open(chemin, encoding="utf-8") as fichier:
        config = json.load(fichier)
    if not config.get("serveur") or not config.get("jeton"):
        raise SystemExit("config.json : renseignez 'serveur' et 'jeton' (jeton affiché dans FacControl > Configuration restaurant > Agents).")
    return config


def appel(config, methode, chemin, corps=None):
    url = config["serveur"].rstrip("/") + chemin
    data = json.dumps(corps).encode("utf-8") if corps is not None else None
    requete = urllib.request.Request(url, data=data, method=methode, headers={
        "Authorization": f"Bearer {config['jeton']}",
        "Content-Type": "application/json",
        "X-Agent-Version": VERSION,
    })
    with urllib.request.urlopen(requete, timeout=20) as reponse:
        return json.loads(reponse.read().decode("utf-8"))


def boucle(config):
    intervalle = float(config.get("intervalle_secondes") or 2)
    logging.info("Agent d'impression %s démarré vers %s", VERSION, config["serveur"])
    while True:
        try:
            reponse = appel(config, "GET", "/restaurant/api/agent/travaux/")
            for travail in reponse.get("travaux", []):
                succes, erreur = True, ""
                try:
                    escpos.envoyer(travail["connexion"], base64.b64decode(travail["donnees"]))
                    logging.info("Imprimé : %s (%s)", travail["titre"], travail["imprimante"])
                except escpos.ErreurImpression as exc:
                    succes, erreur = False, str(exc)
                    logging.error("Échec : %s (%s) : %s", travail["titre"], travail["imprimante"], erreur)
                appel(config, "POST", f"/restaurant/api/agent/travaux/{travail['id']}/resultat/",
                      {"succes": succes, "erreur": erreur})
        except urllib.error.HTTPError as exc:
            if exc.code == 401:
                logging.error("Jeton refusé : régénérez-le dans FacControl et mettez à jour config.json.")
                time.sleep(30)
            else:
                logging.warning("Serveur indisponible (HTTP %s)", exc.code)
                time.sleep(5)
        except (urllib.error.URLError, OSError, ValueError) as exc:
            logging.warning("Connexion au serveur impossible : %s", exc)
            time.sleep(5)
        time.sleep(intervalle)


def main():
    chemin = Path(sys.argv[1]) if len(sys.argv) > 1 else BASE / "config.json"
    config = charger_config(chemin)
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s",
        handlers=[logging.StreamHandler(), logging.FileHandler(BASE / config.get("journal", "agent.log"), encoding="utf-8")],
    )
    try:
        boucle(config)
    except KeyboardInterrupt:
        logging.info("Agent arrêté.")


if __name__ == "__main__":
    main()
