"""
File d'impression des bons cuisine / bar (ESC/POS).

Chaque bon devient un TravailImpression par imprimante active de sa
destination. Mode DIRECT : le serveur FacControl imprime aussitot. Mode AGENT :
l'agent installe au restaurant le recupere par l'API. Un echec n'efface rien :
le ticket reste dans la file et se relance.
"""

import base64
import hashlib
import logging
import secrets
from datetime import timedelta

from django.db import transaction
from django.utils import timezone
from django.utils.translation import gettext as _

from .. import escpos
from ..models import AgentImpression, BonPreparation, ImprimanteThermique, TravailImpression

logger = logging.getLogger(__name__)

DELAI_REPRISE_AGENT = timedelta(minutes=2)


def _qte(value):
    return f"{value.normalize():f}" if hasattr(value, "normalize") else f"{value:g}"


def _montant(value):
    texte = f"{value:,.2f}".replace(",", " ")
    return texte[:-3] if texte.endswith(".00") else texte


def _nom(user):
    return (user.get_full_name() or user.username).strip() if user else ""


def ticket_bon(bon, imprimante):
    """Bon cuisine / bar (ou bon d'annulation) a la maniere des bons Hilton."""
    from facturation.models import Configuration

    commande = bon.commande
    config = Configuration.objects.first()
    ticket = escpos.Ticket(imprimante.caracteres_par_ligne, imprimante.encodage)
    if imprimante.bip:
        ticket.bip()
    if config and config.nom_entreprise:
        ticket.texte(config.nom_entreprise, gras=True, align="center")
    titre = _("COMMANDE %(dest)s") % {"dest": str(bon.get_destination_display()).upper()}
    ticket.texte(titre, double=True, gras=True, align="center")
    if bon.type_bon == BonPreparation.TYPE_ANNULATION:
        ticket.texte(f" {_('ANNULATION')} ", grand=True, inverse=True, align="center")
    elif bon.type_bon == BonPreparation.TYPE_SUITE:
        ticket.texte(_("SUITE"), gras=True, align="center")
    ticket.texte(commande.destination_label.upper(), grand=True, align="center")
    ticket.separateur()
    ticket.colonnes(_("Bon n° %(n)s") % {"n": bon.numero}, timezone.localtime(bon.created_at).strftime("%d/%m/%Y %H:%M"))
    ticket.texte(_("Commande : %(numero)s") % {"numero": commande.numero})
    serveur = _nom(commande.serveur) or _("%(nom)s (Caisse)") % {"nom": _nom(bon.cree_par)}
    ticket.colonnes(_("Serveur : %(nom)s") % {"nom": serveur}, _("Pers. %(n)s") % {"n": commande.couverts})
    ticket.separateur()
    if imprimante.imprimer_prix:
        ticket.colonnes(_("Article"), _("Qté      Prix"), gras=True)
        ticket.separateur()
    signe = "-" if bon.type_bon == BonPreparation.TYPE_ANNULATION else ""
    total = 0
    for ligne in bon.lignes.all():
        if imprimante.imprimer_prix:
            ticket.colonnes(ligne.designation, f"{signe}{_qte(ligne.quantite)}  {_montant(ligne.prix_unitaire)}", gras=True)
            total += ligne.quantite * ligne.prix_unitaire
        else:
            ticket.texte(f"{signe}{_qte(ligne.quantite)} x {ligne.designation}", double=True, gras=True)
    ticket.separateur()
    if imprimante.imprimer_prix:
        ticket.colonnes(_("Total"), f"{signe}{_montant(total)}", gras=True)
    if bon.motif:
        ticket.texte(_("Motif : %(motif)s") % {"motif": bon.motif}, gras=True)
    if commande.observation and bon.type_bon != BonPreparation.TYPE_ANNULATION:
        ticket.texte(_("Obs : %(obs)s") % {"obs": commande.observation}, gras=True)
    ticket.coupe() if imprimante.coupe_papier else ticket.saut(4)
    return ticket


def ticket_test(imprimante):
    ticket = escpos.Ticket(imprimante.caracteres_par_ligne, imprimante.encodage)
    if imprimante.bip:
        ticket.bip()
    ticket.texte(_("TEST D'IMPRESSION"), grand=True, align="center")
    ticket.texte(f"{imprimante.get_destination_display()} - {imprimante.nom}", gras=True, align="center")
    ticket.texte(imprimante.description_connexion(), align="center")
    ticket.texte(timezone.localtime().strftime("%d/%m/%Y %H:%M:%S"), align="center")
    ticket.separateur()
    ticket.texte("Accents : é è à ç ù ô €")
    ticket.texte("1234567890" * (imprimante.caracteres_par_ligne // 10))
    ticket.coupe() if imprimante.coupe_papier else ticket.saut(4)
    return ticket


def _creer_travail(imprimante, ticket, titre, user=None, bon=None):
    return TravailImpression.objects.create(
        imprimante=imprimante, bon=bon, titre=titre[:150], apercu=ticket.apercu(),
        donnees=base64.b64encode(ticket.octets() * max(imprimante.copies, 1)).decode("ascii"), cree_par=user,
    )


def imprimantes_de(point_de_vente, destination):
    return list(ImprimanteThermique.objects.filter(point_de_vente=point_de_vente, destination=destination, actif=True)
                .select_related("agent"))


def mettre_bon_en_file(bon, user=None, reimpression=False):
    prefixe = _("Réimpression ") if reimpression else ""
    titre = f"{prefixe}{bon.get_destination_display()} - {bon.get_type_bon_display()} n° {bon.numero} - {bon.commande.destination_label}"
    return [
        _creer_travail(imprimante, ticket_bon(bon, imprimante), titre, user=user, bon=bon)
        for imprimante in imprimantes_de(bon.commande.point_de_vente, bon.destination)
    ]


def mettre_test_en_file(imprimante, user=None):
    return _creer_travail(imprimante, ticket_test(imprimante), _("Test - %(nom)s") % {"nom": imprimante.nom}, user=user)


def enregistrer_resultat(travail, succes, erreur=""):
    now = timezone.now()
    if succes:
        travail.statut, travail.imprime_le, travail.erreur = TravailImpression.STATUT_IMPRIME, now, ""
        ImprimanteThermique.objects.filter(pk=travail.imprimante_id).update(dernier_succes=now)
    else:
        travail.statut = TravailImpression.STATUT_ECHEC
        travail.erreur = (erreur or _("Erreur inconnue"))[:2000]
        ImprimanteThermique.objects.filter(pk=travail.imprimante_id).update(derniere_erreur=travail.erreur, derniere_erreur_le=now)
        logger.warning("Impression restaurant en echec (%s) : %s", travail.imprimante, travail.erreur)
    travail.save(update_fields=["statut", "imprime_le", "erreur"])


def imprimer_maintenant(travail):
    """Envoie un travail a son imprimante ; retourne True si imprime."""
    travail.statut = TravailImpression.STATUT_EN_COURS
    travail.tentatives += 1
    travail.pris_le = timezone.now()
    travail.save(update_fields=["statut", "tentatives", "pris_le"])
    try:
        escpos.envoyer(travail.imprimante.connexion_payload(), base64.b64decode(travail.donnees))
    except escpos.ErreurImpression as exc:
        enregistrer_resultat(travail, False, str(exc))
        return False
    enregistrer_resultat(travail, True)
    return True


def traiter_travaux(travaux):
    """Imprime les travaux DIRECT ; les travaux AGENT attendent l'agent. Retourne le nombre d'echecs."""
    return sum(
        1 for travail in travaux
        if travail.imprimante.mode_envoi == ImprimanteThermique.ENVOI_DIRECT and not imprimer_maintenant(travail)
    )


def imprimer_apres_validation(travaux):
    """Les impressions DIRECT partent une fois la transaction enregistree."""
    if travaux:
        transaction.on_commit(lambda: traiter_travaux(travaux))


def relancer(travail):
    if travail.imprimante.mode_envoi == ImprimanteThermique.ENVOI_DIRECT:
        return imprimer_maintenant(travail)
    travail.statut, travail.erreur = TravailImpression.STATUT_EN_ATTENTE, ""
    travail.save(update_fields=["statut", "erreur"])
    return True


# --------------------------------------------------------------------------
# Agent d'impression
# --------------------------------------------------------------------------

def empreinte(token):
    return hashlib.sha256(token.encode("utf-8")).hexdigest()


def generer_jeton(agent):
    token = AgentImpression.TOKEN_PREFIX + secrets.token_urlsafe(32)
    agent.jeton_empreinte = empreinte(token)
    agent.jeton_apercu = token[:10]
    agent.save(update_fields=["jeton_empreinte", "jeton_apercu"])
    return token


def agent_par_jeton(token):
    if not token or not token.startswith(AgentImpression.TOKEN_PREFIX):
        return None
    return AgentImpression.objects.filter(jeton_empreinte=empreinte(token), actif=True).first()


def prendre_travaux(agent, limite=10):
    now = timezone.now()
    base = TravailImpression.objects.filter(
        imprimante__agent=agent, imprimante__mode_envoi=ImprimanteThermique.ENVOI_AGENT, imprimante__actif=True,
    )
    base.filter(statut=TravailImpression.STATUT_EN_COURS, pris_le__lt=now - DELAI_REPRISE_AGENT).update(
        statut=TravailImpression.STATUT_EN_ATTENTE)
    with transaction.atomic():
        travaux = list(base.select_for_update().filter(statut=TravailImpression.STATUT_EN_ATTENTE)
                       .select_related("imprimante").order_by("created_at", "pk")[:limite])
        for travail in travaux:
            travail.statut = TravailImpression.STATUT_EN_COURS
            travail.tentatives += 1
            travail.pris_le = now
            travail.save(update_fields=["statut", "tentatives", "pris_le"])
    return travaux
