"""
Service metier de fiscalisation via MCF physique.

Ce module orchestre la preparation des donnees, l'appel au client MCF, la
validation des reponses et la production des elements de securite materiels.
"""



import json
import logging
import re
import unicodedata
from datetime import datetime, timedelta
from decimal import Decimal, ROUND_HALF_UP

from facturation.fiscal_rules import (
    build_mcf_item_type_candidates,
    compute_line_tax_breakdown,
    compute_product_specific_tax_amount,
    get_tax_group_rule,
    missing_tax_group_message,
    normalize_mcf_tax_rate,
    resolve_dgi_item_type_code,
)
from facturation.models import Commande, Configuration
from django.utils import timezone

from mcf_passerelle.services import PasserelleClient, RemoteMCFCommands, passerelle_active

from .client import MCFClient, MCFClientError
from .commands import SUPPORTED_TAX_GROUP_CODES as MCF_TAX_GROUP_CODES, MCFCommands, MCFTaxRateMismatchError
from .models import MCFDevice, MCFInvoiceLog, MCFStatusSnapshot
from .utils import split_response_fields


def ouvrir_commandes(device):
    """(client, commandes) du MCF de l'appareil.

    Appareil relie a une boutique par une passerelle (serveur en ligne) : les
    commandes sont executees par l'agent du PC ou le MCF est branche. Sinon,
    port serie local, comme sur une installation Windows sur place.
    """

    passerelle = passerelle_active(device)
    if passerelle is not None:
        return PasserelleClient(passerelle), RemoteMCFCommands(passerelle)
    client = MCFClient(port=device.port)
    return client, MCFCommands(client)

logger = logging.getLogger(__name__)


class MCFInvoiceServiceError(Exception):
    """Erreur metier liee a l'envoi d'une facture au MCF."""


class MCFInvalidNIFError(MCFInvoiceServiceError):
    """Erreur de format NIF detectee avant ou pendant l'appel au MCF."""


class MCFRejectedNIFError(MCFInvoiceServiceError):
    """Erreur metier lorsque le boitier rejette un NIF pourtant syntaxiquement valide."""


class MCFTaxConfigurationError(MCFInvoiceServiceError):
    """Erreur metier : un groupe de taxation n'a pas le meme taux dans FacControl et le MCF."""


class MCFUnsupportedTaxGroupError(MCFInvoiceServiceError):
    """
    Le groupe d'un article n'est pas applicable au MCF (protocole v2 : A a S, T a Z reserves).

    Ce n'est pas une erreur de la facture : elle reste fiscalisable par
    l'e-MCF, d'ou une erreur de canal qui laisse le repli possible.
    """


class MCFSynchronizationServiceError(Exception):
    """Erreur metier liee au suivi de synchronisation DGI du MCF."""


class MCFPortLocator:
    """
    Retrouve le port COM d'un MCF que Windows a renumerote.

    Apres un rebranchement sur une autre prise USB, le boitier peut passer de
    COM8 a COM13 : le port enregistre disparait alors de la liste. Les autres
    ports sont interroges par C1 et seul un MCF du meme contribuable (NIF,
    2e champ de C1) est retenu. Le MID n'est pas compare : les champs ISF/NID
    de l'appareil sont saisis a la main et ne le refletent pas toujours.
    """

    # Les ports Bluetooth peuvent bloquer plusieurs secondes a l'ouverture et
    # ne portent jamais le MCF : ils ne sont pas sondes.
    SKIPPED_PORT_MARKERS = ("BTHENUM", "BLUETOOTH")

    def __init__(self, device):
        """Prepare la recherche pour l'appareil MCF cible."""

        self.device = device

    def ensure_port(self, ports=None) -> bool:
        """Indique si l'appareil est joignable, apres relocalisation eventuelle."""

        if ports is None:
            ports = MCFClient.available_ports()
        if self.device.port in {port["device"] for port in ports}:
            return True
        return self.relocate(ports) is not None

    def relocate(self, ports):
        """Memorise et retourne le nouveau port du boitier, ou None s'il est absent."""

        for port in self._candidate_ports(ports):
            identity = self._read_identity(port)
            if identity is None or not self._matches_device(identity):
                continue

            previous_port = self.device.port
            self.device.port = port
            if self.device.pk:
                self.device.save(update_fields=["port", "updated_at"])
            logger.warning(
                "MCF '%s' introuvable sur %s, retrouve sur %s : port mis a jour.",
                self.device.name,
                previous_port,
                port,
            )
            return port
        return None

    def _candidate_ports(self, ports) -> list:
        """Liste les ports a sonder, hors port enregistre et ports Bluetooth."""

        candidates = []
        for port in ports:
            name = port.get("device")
            signature = f"{port.get('hwid', '')} {port.get('description', '')}".upper()
            if not name or name == self.device.port:
                continue
            if any(marker in signature for marker in self.SKIPPED_PORT_MARKERS):
                continue
            candidates.append(name)
        return candidates

    def _read_identity(self, port) -> dict | None:
        """Interroge un port par C1 et retourne le MID/NIF du MCF qui repond."""

        client = None
        try:
            client = MCFClient(port=port)
            result = MCFCommands(client).get_status()
        except Exception:
            # Un peripherique etranger peut repondre n'importe quoi : il est
            # simplement ignore, la vente ne doit pas echouer pendant la sonde.
            return None
        finally:
            if client:
                client.close()

        response = (result or {}).get("response") or {}
        data_text = str(response.get("data_text") or "").strip()
        if response.get("type") != "FRAME" or not data_text or data_text.startswith("E:"):
            return None

        fields = split_response_fields(data_text)
        return {
            "mid": fields[0].upper() if fields else "",
            "nif": re.sub(r"[^A-Z0-9]", "", fields[1].upper()) if len(fields) > 1 else "",
        }

    def _matches_device(self, identity) -> bool:
        """Compare le NIF lu par C1 a celui enregistre sur l'appareil."""

        expected_nif = re.sub(r"[^A-Z0-9]", "", str(self.device.company_nif or "").upper())
        return not expected_nif or identity["nif"] == expected_nif


class MCFSynchronizationService:
    """
    Service de lecture et de relance de la connexion serveur DGI du MCF.

    La logique reste concentree dans le module MCF : l'interface ne fait que
    demander un etat lisible ou declencher la commande protocolaire C2/RESTART.
    """

    ALERT_THRESHOLD_DAYS = 7
    SNAPSHOT_PREFIX = "[C2 DGI]"
    MACHINE_UNPLUGGED_MESSAGE = "Le MCF n'est pas branche dans l'ordinateur."
    PORT_BUSY_MESSAGE = (
        "Le MCF est branche sur {port}, mais ce port est occupe par un autre programme "
        "(logiciel du fournisseur MCF ou operation en cours). Fermez-le puis reessayez."
    )
    PORT_INTERRUPTED_MESSAGE = (
        "Le MCF est branche sur {port}, mais il a interrompu la communication "
        "pendant l'operation. Reessayez dans quelques secondes."
    )
    PORT_BUSY_MARKERS = ("permissionerror", "acces refuse", "access is denied")
    SERVER_STATUS_LABELS = {
        "DIS": "Deconnecte",
        "CON": "Connecte",
        "TRA": "Transfert en cours",
        "RES": "Synchronisation relancee",
    }

    def __init__(self, device=None, alert_threshold_days=None):
        """Prepare le service avec l'appareil MCF cible ou le defaut actif."""

        self.device = device or self._get_default_device()
        self.alert_threshold_days = alert_threshold_days or self.ALERT_THRESHOLD_DAYS

    def _get_default_device(self):
        """Retourne l'appareil MCF actif par defaut pour les commandes C2."""

        device = MCFDevice.get_active_default()
        if device:
            return device

        if MCFDevice.objects.active().exists():
            raise MCFSynchronizationServiceError(
                "Aucun appareil MCF actif par defaut n'est configure."
            )

        raise MCFSynchronizationServiceError("Aucun appareil MCF actif n'est configure.")

    def _format_datetime(self, value) -> str:
        """Formate une date MCF pour l'affichage utilisateur."""

        if not value:
            return ""
        return timezone.localtime(value).strftime("%d/%m/%Y %H:%M:%S")

    def _parse_server_datetime(self, value):
        """Convertit le champ DT C2 (AAAAMMJJHHmmss) en date Django."""

        raw_value = str(value or "").strip()
        if not raw_value:
            return None

        match = re.search(r"\d{14}", raw_value)
        if not match:
            return None

        try:
            parsed = datetime.strptime(match.group(0), "%Y%m%d%H%M%S")
        except ValueError:
            return None

        if timezone.is_naive(parsed):
            return timezone.make_aware(parsed, timezone.get_current_timezone())
        return parsed

    def _extract_data_text(self, result) -> str:
        """Recupere le texte utile renvoye par le MCF."""

        response = (result or {}).get("response") or {}
        return str(response.get("data_text") or response.get("text") or "").strip()

    @staticmethod
    def _normalize_error_text(message) -> str:
        """Met une erreur en minuscules sans accents pour la recherche de marqueurs."""

        normalized = unicodedata.normalize("NFD", str(message or "").lower())
        return "".join(char for char in normalized if unicodedata.category(char) != "Mn")

    @classmethod
    def _format_user_error_message(cls, message) -> str:
        """Transforme les erreurs serie techniques en message utilisateur clair."""

        raw_message = str(message or "").strip()
        if not raw_message:
            return "Impossible de verifier la synchronisation DGI."

        normalized = cls._normalize_error_text(raw_message)
        connection_markers = (
            "impossible d'ouvrir le port",
            "could not open port",
            "filenotfounderror",
            "clearcommerror",
            "le peripherique ne reconnait pas la commande",
            "le port serie mcf n'est pas ouvert",
        )
        if any(marker in normalized for marker in connection_markers):
            return cls.MACHINE_UNPLUGGED_MESSAGE

        return raw_message

    def _build_error_status(self, message, checked_at=None) -> dict:
        """Construit un etat d'erreur sans interrompre le dashboard ou le POS."""

        checked_at = checked_at or timezone.now()
        clean_message = self._format_user_error_message(message)
        return {
            "available": False,
            "success": False,
            "machine_connected": False,
            "machine_status_label": "Deconnecte",
            "needs_alert": True,
            "device": self.device,
            "device_name": getattr(self.device, "name", ""),
            "port": getattr(self.device, "port", ""),
            "server_status": "",
            "server_status_label": "",
            "last_connection_at": None,
            "last_connection_display": "",
            "last_connection_raw": "",
            "age_days": None,
            "raw_data": clean_message,
            "error": clean_message,
            "message": clean_message,
            "checked_at": checked_at,
            "checked_at_display": self._format_datetime(checked_at),
            "source": "error",
        }

    def _build_live_error_status(self, message) -> dict:
        """
        Construit l'etat d'une erreur serie qui vient de se produire.

        Une erreur d'ouverture ou de lecture ne prouve pas que le boitier est
        debranche : tant que Windows liste encore son port, on explique que le
        port est occupe ou que la communication a ete interrompue.
        """

        logger.warning("Erreur serie du MCF '%s' sur %s : %s", self.device.name, self.device.port, message)
        status = self._build_error_status(message)
        if status["message"] != self.MACHINE_UNPLUGGED_MESSAGE or not self._port_is_listed():
            return status

        if any(marker in self._normalize_error_text(message) for marker in self.PORT_BUSY_MARKERS):
            clean_message = self.PORT_BUSY_MESSAGE.format(port=self.device.port)
        else:
            clean_message = self.PORT_INTERRUPTED_MESSAGE.format(port=self.device.port)
        status.update(raw_data=clean_message, error=clean_message, message=clean_message)
        return status

    def _port_is_listed(self) -> bool:
        """Indique si Windows liste encore le port COM de l'appareil.

        Avec une passerelle, c'est l'agent de la boutique qui le signale.
        """

        passerelle = passerelle_active(self.device)
        if passerelle is not None:
            return passerelle.en_ligne and passerelle.port_present
        try:
            return self.device.port in {port["device"] for port in MCFClient.available_ports()}
        except MCFClientError:
            return False

    @classmethod
    def build_unavailable_status(cls, message) -> dict:
        """Construit un etat minimal quand aucun service ne peut etre instancie."""

        checked_at = timezone.now()
        clean_message = cls._format_user_error_message(message)
        return {
            "available": False,
            "success": False,
            "machine_connected": False,
            "machine_status_label": "Deconnecte",
            "needs_alert": True,
            "device": None,
            "device_name": "",
            "port": "",
            "server_status": "",
            "server_status_label": "",
            "last_connection_at": None,
            "last_connection_display": "",
            "last_connection_raw": "",
            "age_days": None,
            "raw_data": clean_message,
            "error": clean_message,
            "message": clean_message,
            "checked_at": checked_at,
            "checked_at_display": timezone.localtime(checked_at).strftime("%d/%m/%Y %H:%M:%S"),
            "source": "error",
        }

    def _build_status_from_data(self, data_text, *, ok=True, checked_at=None, source="live") -> dict:
        """Analyse la reponse C2 : EC, DC, DT, STA, ER."""

        checked_at = checked_at or timezone.now()
        normalized_data = str(data_text or "").strip()
        if normalized_data.startswith("R:"):
            normalized_data = normalized_data[2:].strip()

        fields = split_response_fields(normalized_data)
        server_status = fields[3].upper() if len(fields) > 3 else ""
        last_connection_raw = fields[2] if len(fields) > 2 else ""
        error_text = fields[4] if len(fields) > 4 else ""
        is_protocol_error = normalized_data.upper().startswith("E:")
        success = bool(ok) and not is_protocol_error

        last_connection_at = self._parse_server_datetime(last_connection_raw)
        age_days = None
        needs_alert = False
        if last_connection_at:
            delta = checked_at - last_connection_at
            age_days = max(delta.days, 0)
            needs_alert = delta > timedelta(days=self.alert_threshold_days)
        elif success:
            needs_alert = True
            error_text = "Date de derniere connexion DGI absente dans la reponse C2."

        status_label = self.SERVER_STATUS_LABELS.get(server_status, server_status)
        if success and last_connection_at:
            message = (
                f"Derniere connexion DGI le {self._format_datetime(last_connection_at)} "
                f"({age_days} jour(s)), statut {status_label or 'inconnu'}."
            )
        elif success:
            message = error_text
        else:
            message = error_text or normalized_data or "Lecture C2 refusee par le MCF."

        return {
            "available": success,
            "success": success,
            "machine_connected": success,
            "machine_status_label": "Connecte" if success else "Deconnecte",
            "needs_alert": needs_alert or not success,
            "device": self.device,
            "device_name": getattr(self.device, "name", ""),
            "port": getattr(self.device, "port", ""),
            "server_status": server_status,
            "server_status_label": status_label,
            "last_connection_at": last_connection_at,
            "last_connection_display": self._format_datetime(last_connection_at),
            "last_connection_raw": last_connection_raw,
            "age_days": age_days,
            "raw_data": normalized_data,
            "error": "" if success else message,
            "message": message,
            "checked_at": checked_at,
            "checked_at_display": self._format_datetime(checked_at),
            "source": source,
        }

    def _build_status_from_result(self, result, *, source="live") -> dict:
        """Transforme le retour brut du client MCF en etat exploitable."""

        return self._build_status_from_data(
            self._extract_data_text(result),
            ok=bool((result or {}).get("ok", True)),
            source=source,
        )

    def _get_daily_snapshot(self):
        """Recherche une lecture C2 deja effectuee aujourd'hui pour ce MCF."""

        now = timezone.localtime(timezone.now())
        day_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
        day_end = day_start + timedelta(days=1)
        return (
            MCFStatusSnapshot.objects.filter(
                device=self.device,
                created_at__gte=day_start,
                created_at__lt=day_end,
                message__startswith=self.SNAPSHOT_PREFIX,
            )
            .order_by("-created_at")
            .first()
        )

    def _build_status_from_snapshot(self, snapshot) -> dict:
        """Relit le snapshot journalier sans rouvrir le port serie."""

        if not snapshot.success:
            status = self._build_error_status(snapshot.raw_data or snapshot.message, snapshot.created_at)
        else:
            status = self._build_status_from_data(
                snapshot.raw_data,
                ok=True,
                checked_at=snapshot.created_at,
                source="cache",
            )
        status["snapshot"] = snapshot
        status["source"] = "cache"
        return status

    def _save_connection_snapshot(self, status, result=None, action="CHECK") -> None:
        """Conserve le resultat C2 dans les snapshots techniques existants."""

        response = (result or {}).get("response") or {}
        try:
            MCFStatusSnapshot.objects.create(
                device=self.device,
                raw_data=status.get("raw_data") or "",
                status_hex=response.get("status_hex") or "",
                syn_count=response.get("syn_count") or 0,
                success=bool(status.get("success")),
                message=f"{self.SNAPSHOT_PREFIX} {action}: {status.get('message', '')}",
            )
        except Exception:
            # Le snapshot aide au cache quotidien, mais ne doit pas bloquer l'UI.
            logger.exception("Impossible d'enregistrer le snapshot C2 DGI du MCF.")

    def _open_commands(self):
        """(client, commandes) du MCF : passerelle de la boutique, ou port local
        retrouve si Windows l'a renumerote."""

        if passerelle_active(self.device) is None:
            MCFPortLocator(self.device).ensure_port()
        return ouvrir_commandes(self.device)

    def read_connection_status(self) -> dict:
        """Execute la commande C2 pour connaitre la derniere connexion DGI."""

        client = None
        try:
            client, commands = self._open_commands()
            result = commands.get_server_connection_status()
            status = self._build_status_from_result(result, source="live")
            self._save_connection_snapshot(status, result=result, action="CHECK")
            return status
        except Exception as exc:
            status = self._build_live_error_status(str(exc))
            self._save_connection_snapshot(status, action="CHECK")
            return status
        finally:
            if client:
                client.close()

    def get_daily_connection_status(self) -> dict:
        """Retourne l'etat DGI du jour, avec lecture C2 si le cache manque."""

        snapshot = self._get_daily_snapshot()
        if snapshot:
            return self._build_status_from_snapshot(snapshot)
        return self.read_connection_status()

    def restart_synchronization(self) -> dict:
        """Execute C2/RESTART pour relancer la synchronisation serveur DGI."""

        client = None
        try:
            client, commands = self._open_commands()
            result = commands.restart_server_connection()
            status = self._build_status_from_result(result, source="restart")
            status["restart_requested"] = True
            if status.get("success"):
                status["message"] = (
                    "Synchronisation DGI du MCF relancee. "
                    f"{status.get('message', '')}"
                ).strip()
            self._save_connection_snapshot(status, result=result, action="RESTART")
            return status
        except Exception as exc:
            status = self._build_live_error_status(f"Relance de la synchronisation impossible : {exc}")
            status["restart_requested"] = True
            self._save_connection_snapshot(status, action="RESTART")
            return status
        finally:
            if client:
                client.close()


def build_mcf_sync_status_context(*, can_view=False, can_restart=False) -> dict:
    """
    Prepare le contexte d'affichage MCF-DGI pour le POS et le dashboard.

    Les vues gerent les permissions ; ce helper garde uniquement la logique
    MCF et le cache journalier dans le module MCF.
    """

    if not can_view:
        return {
            "mcf_sync_status": None,
            "mcf_sync_can_restart": False,
        }

    try:
        status = MCFSynchronizationService().get_daily_connection_status()
    except Exception as exc:
        status = MCFSynchronizationService.build_unavailable_status(str(exc))

    return {
        "mcf_sync_status": status,
        "mcf_sync_can_restart": bool(can_restart),
    }


class MCFInvoiceService:
    """
    Service d'integration du MCF physique.

    La configuration materielle et societe vient de la base via MCFDevice.
    """

    def __init__(self, device=None):
        """Initialise le service avec l'appareil MCF cible ou le defaut configure."""
        self.device = device or self._get_default_device()

    def _get_default_device(self):
        """Selectionne l'appareil MCF par defaut utilisable par le systeme."""
        device = MCFDevice.get_active_default()
        if device:
            return device

        if MCFDevice.objects.active().exists():
            raise MCFInvoiceServiceError(
                "Aucun appareil MCF actif par defaut n'est configure dans Django admin."
            )

        raise MCFInvoiceServiceError(
            "Aucun appareil MCF actif n'est configure dans Django admin."
        )

    def _normalize_text(self, value) -> str:
        """Normalise text."""

        return str(value or "").strip()

    def _normalize_nif(self, value) -> str:
        """Normalise nif."""

        return re.sub(r"[^A-Z0-9]", "", self._normalize_text(value).upper())

    def _is_valid_mcf_nif(self, value) -> bool:
        """Indique si valid mcf nif."""

        normalized = self._normalize_nif(value)
        return bool(re.fullmatch(r"[A-Z][0-9]{7}[A-Z]", normalized))

    def _raise_invalid_nif(self, subject: str) -> None:
        """Execute le traitement raise invalid nif."""

        raise MCFInvalidNIFError(f"Le format du NIF n'est pas valide pour {subject}.")

    def _is_invalid_nif_mcf_error(self, message: str) -> bool:
        """Indique si invalid nif mcf error."""

        normalized = self._normalize_text(message).lower()
        return "nif invalide" in normalized

    def _normalize_lookup_text(self, value) -> str:
        """Normalise un texte libre pour les comparaisons robustes."""

        text = unicodedata.normalize("NFD", self._normalize_text(value).lower())
        return "".join(char for char in text if unicodedata.category(char) != "Mn")

    def _parse_mcf_datetime_value(self, value) -> datetime | None:
        """Parse une date/heure MCF issue d'un log ou d'une reponse boitier."""

        raw_value = self._normalize_text(value)
        if not raw_value:
            return None

        patterns = (
            (r"\b\d{14}\b", "%Y%m%d%H%M%S"),
            (r"\b\d{2}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2}\b", "%d/%m/%Y %H:%M:%S"),
            (r"\b\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\b", "%Y-%m-%d %H:%M:%S"),
            (r"\b\d{2}-\d{2}-\d{4}\s+\d{2}:\d{2}:\d{2}\b", "%d-%m-%Y %H:%M:%S"),
        )

        for pattern, fmt in patterns:
            match = re.search(pattern, raw_value)
            if not match:
                continue
            try:
                return datetime.strptime(match.group(0), fmt)
            except ValueError:
                continue

        return None

    def _extract_datetime_from_security_payload(self, payload) -> datetime | None:
        """Recupere l'horodatage fiscal a partir d'un payload de securite MCF."""

        normalized_security = self._normalize_security_payload(payload or {})
        for candidate in (
            normalized_security.get("dt_raw"),
            normalized_security.get("date_time"),
            normalized_security.get("def_time"),
        ):
            parsed = self._parse_mcf_datetime_value(candidate)
            if parsed:
                return parsed
        return None

    def _get_last_known_mcf_fiscal_datetime(self) -> datetime | None:
        """Retourne le dernier horodatage fiscal MCF connu pour ce boitier."""

        recent_logs = (
            MCFInvoiceLog.objects.filter(device=self.device, success=True)
            .order_by("-created_at")[:10]
        )
        for invoice_log in recent_logs:
            response_payload = invoice_log.response_data or {}
            parsed = self._extract_datetime_from_security_payload(
                (response_payload or {}).get("security")
            )
            if parsed:
                return parsed

            close_data = (
                (((response_payload or {}).get("result") or {}).get("steps") or {})
                .get("close", {})
                .get("data", "")
            )
            if close_data:
                try:
                    parsed = self._extract_datetime_from_security_payload(
                        self._parse_close_response(close_data)
                    )
                except Exception:
                    parsed = None
                if parsed:
                    return parsed

        audit_candidates = [
            self._parse_mcf_datetime_value(getattr(self.device, "audit_local", "")),
            self._parse_mcf_datetime_value(getattr(self.device, "audit_distance", "")),
        ]
        audit_candidates = [candidate for candidate in audit_candidates if candidate]
        if audit_candidates:
            return max(audit_candidates)

        return None

    def _is_clock_chronology_mcf_error(self, message: str) -> bool:
        """Indique si le MCF remonte une incoherence d'horloge ou de chronologie."""

        normalized = self._normalize_lookup_text(message)
        if "erreur 162" in normalized or "error 162" in normalized:
            return True

        return any(
            marker in normalized
            for marker in (
                "horloge du mcf est incoherente",
                "dernier enregistrement fiscal",
                "heure superieure au dernier ticket fiscal",
                "horloge est reglee plus tot que le dernier enregistrement",
            )
        )

    def _build_company_identity_candidates(self, prepared_payload=None) -> list[dict]:
        """Construit les couples NIF/ISF candidats a partir du boitier et de la configuration."""
        seen = set()
        candidates = []
        missing_sources = []
        invalid_sources = []

        def add_candidate(raw_nif, raw_isf, source_label):
            nif = self._normalize_nif(raw_nif)
            isf = self._normalize_text(raw_isf)
            key = (nif, isf)

            if key in seen:
                return

            seen.add(key)

            if not nif and not isf:
                return

            if not nif or not isf:
                missing_sources.append(source_label)
                return

            if not self._is_valid_mcf_nif(nif):
                invalid_sources.append((source_label, nif))
                return

            candidates.append(
                {
                    "nif": nif,
                    "isf": isf,
                    "source_label": source_label,
                }
            )

        if prepared_payload:
            company = prepared_payload.get("company", {})
            config_nif = company.get("nif")
            config_isf = company.get("isf")
        else:
            config = Configuration.objects.first()
            config_nif = getattr(config, "nif", "") if config else ""
            config_isf = getattr(config, "isf_dgi", "") if config else ""

        # Manuel C0 : ISF = identifiant du SFE, donc celui de la Configuration,
        # deja envoye dans le JSON e-MCF. Le champ ISF de l'appareil contient
        # souvent le MID du boitier (ex. ED02001705-1) : il ne sert qu'a defaut.
        sfe_isf = self._normalize_text(config_isf) or self.device.company_isf

        add_candidate(
            self.device.company_nif,
            sfe_isf,
            f"l'appareil MCF '{self.device.name}'",
        )
        add_candidate(
            config_nif,
            sfe_isf,
            "la configuration fiscale",
        )

        if candidates:
            return candidates

        if invalid_sources:
            self._raise_invalid_nif(invalid_sources[0][0])

        if missing_sources:
            raise MCFInvoiceServiceError(
                f"Les informations societes sont incompletes pour {missing_sources[0]}."
            )

        raise MCFInvoiceServiceError(
            "Le NIF societe et l'ISF societe sont manquants pour le canal MCF."
        )

    def _translate_mcf_nif_error(self, message: str, customer: dict | None = None, company_identity: dict | None = None):
        """Traduit mcf nif error."""

        if "Commande C3" in message:
            customer_name = self._normalize_text((customer or {}).get("cnom")) or "ce client"
            customer_type = self._normalize_text((customer or {}).get("ctype")).upper() or "PP"
            if customer_type == "PP":
                return MCFRejectedNIFError(
                    f"Le MCF a rejete le NIF du client '{customer_name}'. Pour un client PP, laissez le NIF vide."
                )
            return MCFRejectedNIFError(
                f"Le MCF a rejete le NIF du client '{customer_name}'. Verifiez le NIF enregistre pour ce client."
            )

        if "Commande C0" in message:
            company_nif = self._normalize_text((company_identity or {}).get("nif"))
            source_label = self._normalize_text((company_identity or {}).get("source_label")) or "la societe configuree"
            return MCFRejectedNIFError(
                f"Le MCF a rejete le NIF societe '{company_nif}' provenant de {source_label}. "
                "Verifiez qu'il correspond exactement au NIF active sur le boitier et a l'ISF configure."
            )

        return MCFRejectedNIFError(
            "Le MCF a rejete un NIF. Verifiez le NIF societe et, pour un client PM, le NIF client."
        )

    def _normalize_customer_type_for_mcf(self, raw_type, normalized_nif="") -> str:
        """Normalise customer type for mcf."""

        code = self._normalize_text(raw_type).upper()
        if code in {"PP", "PM"}:
            return code
        if normalized_nif:
            return "PM"
        return "PP"

    def _get_company_identity(self) -> dict:
        """Recupere company identity."""

        candidate = self._build_company_identity_candidates()[0]
        return {
            "nif": candidate["nif"],
            "isf": candidate["isf"],
        }

    def _get_invoice_type(self) -> str:
        """Recupere invoice type."""

        config = Configuration.objects.first()
        invoice_type = self._normalize_text(getattr(config, "type_dgi", ""))
        return invoice_type.upper() or "FV"

    def _resolve_invoice_type(self, commande) -> str:
        """Resout invoice type."""

        invoice_type = self._normalize_text(getattr(commande, "type_facture", ""))
        return invoice_type.upper() or self._get_invoice_type()

    def _normalize_price_mode(self, value) -> str:
        """
        Le mode de prix du MCF doit venir de la configuration dynamique
        (mode_dgi) afin d'eviter tout hardcoding HT/TTC dans le code.
        """
        return "TTC" if self._normalize_text(value).lower() == "ttc" else "HT"

    def _get_price_mode(self) -> str:
        """Recupere price mode."""

        config = Configuration.objects.first()
        return self._normalize_price_mode(getattr(config, "mode_dgi", "ttc"))

    def _get_price_mode_from_prepared(self, prepared_payload) -> str:
        """Recupere price mode from prepared."""

        return self._normalize_price_mode(prepared_payload["company"].get("mode_dgi", "ttc"))

    def _build_credit_note_reference(self, original_commande, preferred_nature="RAN", canonical_reference="") -> dict:
        """Construit le couple RR/RN d'un avoir MCF conforme au protocole officiel."""

        if not original_commande:
            raise MCFInvoiceServiceError(
                "Une facture d'avoir MCF doit referencer une facture d'origine."
            )

        reference_nature = self._normalize_text(preferred_nature).upper() or "RAN"
        reference_candidates = []
        seen_candidates = set()

        def add_candidate(rn_value):
            normalized_rn = self._normalize_text(rn_value)
            key = (reference_nature, normalized_rn)
            if not normalized_rn or key in seen_candidates:
                return
            seen_candidates.add(key)
            reference_candidates.append(
                {
                    "rr": reference_nature,
                    "rn": normalized_rn,
                }
            )

        canonical_reference = self._normalize_text(canonical_reference)
        code_def_dgi = self._normalize_text(getattr(original_commande, "codedefdgi", ""))
        numero = self._normalize_text(getattr(original_commande, "numero", ""))

        # RN correspond a la reference du document source. On privilegie
        # la reference fiscale canonique, puis on garde le numero SFE en repli.
        add_candidate(canonical_reference)
        add_candidate(code_def_dgi)
        add_candidate(numero)

        if not reference_candidates:
            raise MCFInvoiceServiceError(
                "La facture d'origine MCF doit contenir une reference exploitable pour l'avoir."
            )

        return {
            "reference_type": reference_nature,
            "rr": reference_candidates[0]["rr"] if reference_candidates else "",
            "rn": reference_candidates[0]["rn"] if reference_candidates else "",
            "reference_candidates": reference_candidates,
        }

    def _map_client_type(self, commande) -> str:
        """Execute le traitement map client type."""

        client = getattr(commande, "client", None)
        if not client:
            return "PP"

        raw = getattr(client, "type_client", None) or getattr(client, "client_type", None)
        if raw:
            code = getattr(raw, "code", raw)
            code = self._normalize_text(code).upper()
            if code in {"PP", "PM"}:
                return code

        if getattr(client, "nif", None):
            return "PM"

        return "PP"

    def _map_payment_type(self, commande) -> str:
        """Execute le traitement map payment type."""

        paiement = None

        if hasattr(commande, "paiement_set"):
            paiement = commande.paiement_set.order_by("-id").first()
        elif hasattr(commande, "paiements"):
            paiement = commande.paiements.order_by("-id").first()

        if not paiement:
            return "E"

        mode = getattr(paiement, "mode_paiement", None)
        mode_code = mode.code if mode else ""
        mode_text = self._normalize_text(mode_code).lower()
        mapping = {
            "especes": "E",
            "espece": "E",
            "cash": "E",
            "virement": "V",
            "carte": "C",
            "mobile money": "M",
            "mobile_money": "M",
            "mobilemoney": "M",
            "cheque": "D",
            "autre": "A",
        }
        return mapping.get(mode_text, "E")

    def _map_item_type(self, produit) -> str:
        """Execute le traitement map item type."""

        typeart = getattr(produit, "typeart", None)
        raw = getattr(produit, "item_type", None) or getattr(typeart, "code", None) or typeart
        return resolve_dgi_item_type_code(raw)

    def _get_tax_rate(self, produit) -> Decimal:
        """Recupere tax rate."""

        tax_group = getattr(produit, "taxgroup", None)
        tax_value = getattr(tax_group, "tax", Decimal("0.00")) if tax_group else Decimal("0.00")
        return Decimal(str(tax_value or "0.00"))

    def _build_customer_dict(self, commande) -> dict:
        """Construit customer dict."""

        client = getattr(commande, "client", None)

        if not client:
            return {
                "ctype": "PP",
                "cnif": "",
                "cnom": "CLIENT PASSAGE",
                "cadd": "",
                "ctel": "",
                "ceml": "",
                "crccm": "",
            }

        client_nif = self._normalize_nif(getattr(client, "nif", ""))
        client_type = self._normalize_customer_type_for_mcf(self._map_client_type(commande), client_nif)
        client_name = getattr(client, "nom_complet", "CLIENT") or "CLIENT"

        if client_type == "PM" and not client_nif:
            raise MCFInvoiceServiceError(
                f"Le client '{client_name}' est de type PM mais n'a pas de NIF."
            )

        if client_nif and not self._is_valid_mcf_nif(client_nif):
            self._raise_invalid_nif(f"le client '{client_name}'")

        return {
            "ctype": client_type,
            "cnif": client_nif,
            "cnom": client_name,
            "cadd": getattr(client, "adresse", "") or "",
            "ctel": getattr(client, "telephone", "") or "",
            "ceml": getattr(client, "email", "") or "",
            "crccm": getattr(client, "rccm", "") or "",
        }

    def _build_invoice_dict(self, commande, company_identity=None) -> dict:
        """Construit invoice dict."""

        vendeur = getattr(commande, "vendeur", None)
        company_identity = company_identity or self._get_company_identity()
        invoice_type = self._resolve_invoice_type(commande)
        credit_note_reference = {}
        if invoice_type in {"FA", "EA"}:
            credit_note_reference = self._build_credit_note_reference(
                getattr(commande, "facture_origine", None),
                preferred_nature=getattr(commande, "avoir_nature_resolue", ""),
                canonical_reference=getattr(commande, "avoir_reference_resolue", ""),
            )

        if vendeur:
            full_name = vendeur.get_full_name().strip() if hasattr(vendeur, "get_full_name") else ""
            operator_name = full_name or getattr(vendeur, "username", "ADMIN")
            operator_id = str(vendeur.pk)
        else:
            operator_name = "ADMIN"
            operator_id = "1"

        return {
            **(
                credit_note_reference
                if invoice_type in {"FA", "EA"}
                else {}
            ),
            "opid": operator_id,
            "opn": operator_name,
            "nif": company_identity["nif"],
            "invoice_type": invoice_type,
            "pmode": self._get_price_mode(),
            "isf": company_identity["isf"],
            "fn": str(getattr(commande, "numero", "") or getattr(commande, "pk", "")),
        }

    def _build_items(self, commande) -> list:
        """Construit items."""

        if not hasattr(commande, "lignes"):
            raise MCFInvoiceServiceError("La commande ne contient pas de relation 'lignes'.")

        lignes_qs = commande.lignes.select_related("produit", "produit__taxgroup", "produit__typeart").all()
        if not lignes_qs.exists():
            raise MCFInvoiceServiceError("Impossible de fiscaliser une facture sans lignes.")

        price_mode = self._get_price_mode()
        items = []
        for ligne in lignes_qs:
            produit = getattr(ligne, "produit", None)
            if not produit:
                raise MCFInvoiceServiceError("Une ligne de commande ne contient pas de produit.")

            tax_group_obj = getattr(produit, "taxgroup", None)
            if not tax_group_obj or not getattr(tax_group_obj, "code", None):
                raise MCFInvoiceServiceError(missing_tax_group_message(
                    getattr(produit, "nom", "ARTICLE")
                ))

            tax_group = self._normalize_text(getattr(tax_group_obj, "code", "")).upper()
            sfe_rate = self._get_tax_rate(produit)
            fallback_item_types = build_mcf_item_type_candidates(
                self._map_item_type(produit),
                tax_group,
            )
            line_total = getattr(ligne, "sous_total", Decimal("0.00"))
            quantity = getattr(ligne, "quantite", Decimal("1.00"))

            items.append(
                self._with_fiscal_amounts(
                    {
                        "nom": getattr(produit, "nom", "ARTICLE"),
                        "desc": getattr(produit, "description", "") or "",
                        "itype": fallback_item_types[0],
                        "tax_group": tax_group,
                        "tax_rate": normalize_mcf_tax_rate(tax_group, sfe_rate),
                        "unit_price": getattr(ligne, "prix_unitaire", Decimal("0.00")),
                        "quantity": quantity,
                        "fallback_tax_groups": [tax_group],
                        "fallback_item_types": fallback_item_types,
                    },
                    line_total=line_total,
                    sfe_rate=sfe_rate,
                    price_mode=price_mode,
                    specific_tax_value=(
                        getattr(produit, "taxe_specifique_valeur", None)
                        if getattr(produit, "est_taxe_specifique", False)
                        else None
                    ),
                    specific_tax_amount=compute_product_specific_tax_amount(produit, line_total, quantity),
                )
            )

        return items

    def _with_fiscal_amounts(
        self,
        mcf_item,
        *,
        line_total,
        sfe_rate,
        price_mode,
        specific_tax_value=None,
        specific_tax_amount=None,
        original_price=None,
        price_change_desc="",
    ) -> dict:
        """
        Complete un article 31h selon le manuel MCF.

        MON inclut la taxe specifique (et sa TVA en mode TTC) alors que PR
        l'exclut ; la T.S. part dans ;T{TSR},{TS} et un prix modifie dans
        {PRORIG},{PRDESC}, comme pour l'API e-MCF. `expected_amount` et
        `expected_vat` reprennent le calcul de la facture SFE pour controler
        la reponse 33h groupe par groupe.
        """
        tax_group = mcf_item["tax_group"]
        line_total = Decimal(str(line_total or 0))
        sfe_rate = Decimal(str(sfe_rate or 0))
        specific_tax = Decimal(str(specific_tax_amount or 0)).quantize(
            Decimal("0.01"),
            rounding=ROUND_HALF_UP,
        )
        breakdown = compute_line_tax_breakdown(
            subtotal=line_total,
            tax_rate=sfe_rate,
            mode_dgi=price_mode,
            tax_group_code=tax_group,
            specific_tax_amount=specific_tax,
        )
        is_ttc = self._normalize_text(price_mode).lower() == "ttc"

        mcf_item.update(
            {
                "total_amount": breakdown["ttc_amount"] if is_ttc else line_total + specific_tax,
                # Le taux ne pilote la TVA que pour les groupes "rate" : lui
                # seul doit etre identique au taux programme dans le MCF.
                "sfe_tax_rate": sfe_rate if get_tax_group_rule(tax_group)["vat_mode"] == "rate" else None,
                "expected_amount": breakdown["ttc_amount"],
                "expected_vat": breakdown["tax_amount"],
            }
        )
        if specific_tax > 0 and self._normalize_text(specific_tax_value):
            mcf_item["specific_tax_rate"] = self._normalize_text(specific_tax_value)
            mcf_item["specific_tax_total"] = specific_tax
        if original_price is not None:
            mcf_item["original_price"] = Decimal(str(original_price))
            mcf_item["price_change_desc"] = (self._normalize_text(price_change_desc) or "Remise")[:24]
        return mcf_item

    def _build_expected_groups(self, items) -> dict | None:
        """Totalise par groupe A-P les montants TTC et TVA que le MCF doit enregistrer."""

        groups = {}
        for item in items:
            if item.get("expected_amount") is None:
                return None
            group = groups.setdefault(
                item["tax_group"],
                {"amount": Decimal("0"), "vat": Decimal("0"), "items": 0},
            )
            group["amount"] += item["expected_amount"]
            group["vat"] += item["expected_vat"]
            group["items"] += 1
        return groups

    def _build_payments(self, commande) -> list:
        """Construit payments."""

        return [
            {
                "payment_type": self._map_payment_type(commande),
                "amount": getattr(commande, "montant_total", Decimal("0.00")),
            }
        ]

    def _build_customer_from_prepared(self, prepared_payload) -> dict:
        """Construit customer from prepared."""

        customer = prepared_payload["customer"]
        client_nif = self._normalize_nif(customer.get("nif", ""))
        client_name = customer.get("name", "CLIENT PASSAGE")
        client_type = self._normalize_customer_type_for_mcf(customer.get("type", "PP"), client_nif)

        if client_type == "PM" and not client_nif:
            raise MCFInvoiceServiceError(
                f"Le client '{client_name}' est de type PM mais n'a pas de NIF."
            )

        if client_nif and not self._is_valid_mcf_nif(client_nif):
            self._raise_invalid_nif(f"le client '{client_name}'")

        return {
            "ctype": client_type,
            "cnif": client_nif,
            "cnom": client_name,
            "cadd": customer.get("address", ""),
            "ctel": customer.get("contact", ""),
            "ceml": customer.get("email", ""),
            "crccm": customer.get("rccm", ""),
        }

    def _build_invoice_from_prepared(self, prepared_payload, company_identity=None, commande=None) -> dict:
        """Construit invoice from prepared."""

        company_identity = company_identity or self._get_company_identity()
        invoice_data = {
            "opid": prepared_payload["operator"]["id"],
            "opn": prepared_payload["operator"]["name"],
            "nif": company_identity["nif"],
            "invoice_type": prepared_payload["commande"]["type_facture"],
            "pmode": self._get_price_mode_from_prepared(prepared_payload),
            "isf": company_identity["isf"],
            "fn": prepared_payload["commande"]["numero"],
        }
        if invoice_data["invoice_type"] in {"FA", "EA"}:
            credit_note_payload = prepared_payload.get("credit_note") or {}
            reference_data = {}
            original_commande = getattr(commande, "facture_origine", None) if commande is not None else None
            if original_commande:
                reference_data = self._build_credit_note_reference(
                    original_commande,
                    preferred_nature=credit_note_payload.get("nature")
                    or prepared_payload["commande"].get("type_facture_origine", ""),
                    canonical_reference=credit_note_payload.get("reference", ""),
                )

            fallback_rr = prepared_payload["commande"].get("rr", "")
            fallback_rn = prepared_payload["commande"].get("rn", "")
            fallback_candidates = []
            if fallback_rr and fallback_rn:
                fallback_candidates.append({"rr": fallback_rr, "rn": fallback_rn})

            invoice_data.update(
                {
                    "reference_type": reference_data.get("reference_type")
                    or self._normalize_text(
                        credit_note_payload.get("nature")
                        or prepared_payload["commande"].get("type_facture_origine", "")
                    ).upper()
                    or "RAN",
                    "rr": reference_data.get("rr", fallback_rr),
                    "rn": reference_data.get("rn", fallback_rn),
                    "reference_candidates": reference_data.get("reference_candidates") or fallback_candidates,
                }
            )
        return invoice_data

    def _build_items_from_prepared(self, prepared_payload) -> list:
        """Construit items from prepared."""

        credit_note_payload = prepared_payload.get("credit_note") or {}
        commande_payload = prepared_payload.get("commande") or {}
        credit_note_nature = self._normalize_text(
            credit_note_payload.get("nature")
            or commande_payload.get("type_facture_origine")
        ).upper()
        is_correction_credit_note = (
            self._normalize_text(commande_payload.get("type_facture")).upper() in {"FA", "EA"}
            and credit_note_nature == "COR"
        )
        price_mode = self._normalize_text((prepared_payload.get("company") or {}).get("mode_dgi") or "ttc").lower()
        items = []
        for item in prepared_payload["items"]:
            unit_price = Decimal(str(item["unit_price"]))
            quantity = Decimal(str(item["quantity"]))
            line_total = Decimal(str(item["line_total"]))
            if is_correction_credit_note:
                line_total = (unit_price * quantity).quantize(Decimal("0.01"))

            fallback_item_types = build_mcf_item_type_candidates(
                self._map_item_type(type("PreparedItem", (), {"item_type": item["item_type"], "typeart": None})()),
                item["tax_group"],
            )
            sfe_rate = Decimal(str(item["tax_rate"]))
            items.append(
                self._with_fiscal_amounts(
                    {
                        "nom": item["name"],
                        "desc": item.get("description", "") or "",
                        "itype": fallback_item_types[0],
                        "tax_group": item["tax_group"],
                        "tax_rate": normalize_mcf_tax_rate(item["tax_group"], sfe_rate),
                        "unit_price": unit_price,
                        "quantity": quantity,
                        "fallback_tax_groups": [item["tax_group"]],
                        "fallback_item_types": fallback_item_types,
                    },
                    line_total=line_total,
                    sfe_rate=sfe_rate,
                    price_mode=price_mode,
                    specific_tax_value=item.get("specific_tax_value"),
                    specific_tax_amount=item.get("specific_tax_amount"),
                    original_price=item.get("original_price"),
                    price_change_desc=item.get("price_modification"),
                )
            )
        return items

    def _build_payments_from_prepared(self, prepared_payload) -> list:
        """Construit payments from prepared."""

        mode_mapping = {
            "ESPECES": "E",
            "CASH": "E",
            "VIREMENT": "V",
            "CARTE": "C",
            "MOBILE_MONEY": "M",
            "MOBILE MONEY": "M",
            "CHEQUE": "D",
            "AUTRE": "A",
            "E": "E",
            "V": "V",
            "C": "C",
            "M": "M",
            "D": "D",
            "A": "A",
        }
        payments = []
        for payment in prepared_payload["payments"]:
            raw_mode = self._normalize_text(payment.get("mode_code") or payment.get("name") or "E").upper()
            payments.append(
                {
                    "payment_type": mode_mapping.get(raw_mode, "E"),
                    "amount": Decimal(str(payment.get("amount", 0) or 0)),
                }
            )
        return payments or [
            {
                "payment_type": "E",
                "amount": Decimal(str(prepared_payload["totals"]["total_ttc"])),
            }
        ]

    def _ensure_tax_groups_supported(self, items):
        """Refuse, avant toute ouverture de facture, un groupe hors du protocole MCF."""

        unsupported = {}
        for item in items:
            code = self._normalize_text(item.get("tax_group")).upper()
            if code not in MCF_TAX_GROUP_CODES:
                unsupported.setdefault(code, item.get("nom") or "ARTICLE")
        if unsupported:
            details = ", ".join(f"« {name} » (groupe {code})" for code, name in sorted(unsupported.items()))
            raise MCFUnsupportedTaxGroupError(
                f"Le MCF physique ne gere que les groupes de taxation {MCF_TAX_GROUP_CODES[0]} a "
                f"{MCF_TAX_GROUP_CODES[-1]} (T a Z sont reserves par la DGI) : {details}."
            )

    def _validate_before_send(self, commande):
        """Execute le traitement validate before send."""

        if not commande:
            raise MCFInvoiceServiceError("Commande introuvable.")

        total = getattr(commande, "montant_total", None)
        if total is None:
            raise MCFInvoiceServiceError("Montant total introuvable sur la commande.")

        try:
            total_decimal = Decimal(str(total))
        except Exception as exc:
            raise MCFInvoiceServiceError("Montant total invalide sur la commande.") from exc

        if total_decimal <= 0:
            raise MCFInvoiceServiceError(
                "Impossible de fiscaliser une facture avec un montant total nul ou negatif."
            )

    def _json_safe(self, value):
        """Execute le traitement json safe."""

        return json.loads(json.dumps(value, default=str))

    def _serialize_raw(self, value):
        """Execute le traitement serialize raw."""

        if isinstance(value, (bytes, bytearray)):
            return value.hex().upper()
        return self._normalize_text(value)

    def _is_duplicate_invoice_number_error(self, message: str) -> bool:
        """Indique si duplicate invoice number error."""

        return "invoice number is already used" in self._normalize_text(message).lower()

    def _is_invalid_original_reference_mcf_error(self, message: str) -> bool:
        """Indique si le MCF rejette la reference de la facture source d'un avoir."""

        normalized = self._normalize_lookup_text(message)
        if "facture originale" not in normalized and "original invoice" not in normalized:
            return False

        return (
            "reference de la facture originale" in normalized
            or "original invoice reference" in normalized
        ) and (
            "pas valide" in normalized
            or "n'est pas valide" in normalized
            or "introuvable" in normalized
            or "not valid" in normalized
            or "not found" in normalized
        )

    def _is_temporary_server_unavailable_mcf_error(self, message: str) -> bool:
        """Indique si le MCF remonte une indisponibilite serveur transitoire."""

        normalized = self._normalize_lookup_text(message)
        if self._is_clock_chronology_mcf_error(normalized):
            return False

        if "service unavailable" in normalized:
            return True

        if "serveur mcf" not in normalized and "mcf server" not in normalized:
            return False

        return any(
            marker in normalized
            for marker in (
                "temporairement indisponible",
                "indisponible",
                "temporarily unavailable",
                "unavailable",
            )
        )

    def _get_credit_note_reference_candidates(self, invoice: dict | None) -> list[dict]:
        """Retourne les references source candidates d'un avoir MCF."""

        invoice = invoice or {}
        raw_candidates = invoice.get("reference_candidates") or [
            {
                "rr": invoice.get("rr"),
                "rn": invoice.get("rn"),
            }
        ]
        candidates = []
        seen = set()

        for candidate in raw_candidates:
            rr = self._normalize_text((candidate or {}).get("rr")).upper()
            rn = self._normalize_text((candidate or {}).get("rn"))
            key = (rr, rn)
            if not rr or not rn or key in seen:
                continue
            seen.add(key)
            candidates.append({"rr": rr, "rn": rn})

        return candidates

    def _rotate_local_invoice_number(self, commande, prepared_payload=None) -> str:
        """Execute le traitement rotate local invoice number."""

        if not hasattr(commande, "reserve_new_numero"):
            raise MCFInvoiceServiceError(
                "Impossible de recalculer le numero de facture local pour un nouvel essai MCF."
            )

        previous_numero = self._normalize_text(getattr(commande, "numero", ""))
        new_numero = commande.reserve_new_numero()
        if prepared_payload is not None:
            prepared_payload.setdefault("commande", {})
            prepared_payload["commande"]["numero"] = new_numero

        logger.warning(
            "Numero de facture MCF deja utilise pour la commande %s: %s -> %s",
            getattr(commande, "pk", None),
            previous_numero,
            new_numero,
        )
        return new_numero

    def _rotate_prepared_invoice_number(self, commande, prepared_payload) -> str:
        """Execute le traitement rotate prepared invoice number."""

        invoice_payload = prepared_payload.setdefault("commande", {})
        previous_numero = self._normalize_text(invoice_payload.get("numero"))
        invoice_type = self._normalize_text(invoice_payload.get("type_facture")) or self._resolve_invoice_type(commande)

        temp_commande = Commande(
            point_de_vente=getattr(commande, "point_de_vente", None),
            vendeur=getattr(commande, "vendeur", None),
            type_facture=invoice_type,
        )
        temp_commande.date_commande = getattr(commande, "date_commande", None) or timezone.now()
        new_numero = temp_commande.build_next_numero()
        invoice_payload["numero"] = new_numero

        logger.warning(
            "Numero fiscal MCF complementaire deja utilise pour la commande %s: %s -> %s",
            getattr(commande, "pk", None),
            previous_numero,
            new_numero,
        )
        return new_numero

    def _format_close_datetime(self, raw_value: str) -> str:
        """Execute le traitement format close datetime."""

        try:
            return datetime.strptime(raw_value, "%Y%m%d%H%M%S").strftime("%d/%m/%Y %H:%M:%S")
        except ValueError:
            return raw_value

    def _normalize_security_payload(self, security: dict | None) -> dict:
        """Normalise security payload."""

        security = dict(security or {})
        dt_raw = self._normalize_text(security.get("dt_raw"))
        date_time = self._normalize_text(
            security.get("date_time")
            or security.get("def_time")
            or security.get("dt_display")
            or (self._format_close_datetime(dt_raw) if dt_raw else "")
        )
        code_def_dgi = self._normalize_text(
            security.get("code_def_dgi") or security.get("sig")
        )
        counters = self._normalize_text(
            security.get("counters") or security.get("def_counters")
        )
        nim = self._normalize_text(
            security.get("nim")
            or security.get("def_nim")
            or security.get("mid")
            or security.get("isf")
            or self.device.company_isf
        )
        qr_code = self._normalize_text(
            security.get("qr_code") or security.get("qr_payload")
        )

        if not qr_code and nim and code_def_dgi and dt_raw and self._normalize_text(security.get("nif")):
            qr_code = f"RDCDEF01;{nim};{code_def_dgi};{self._normalize_text(security.get('nif'))};{dt_raw}"

        security.update(
            {
                "date_time": date_time,
                "code_def_dgi": code_def_dgi,
                "counters": counters,
                "nim": nim,
                "qr_code": qr_code,
                "def_time": date_time,
                "def_counters": counters,
                "def_nim": nim,
                "qr_payload": qr_code,
            }
        )
        return security

    def _save_status_snapshot(self, status_step):
        """Execute le traitement save status snapshot."""

        if not status_step:
            return

        response = (status_step or {}).get("response") or {}
        MCFStatusSnapshot.objects.create(
            device=self.device,
            raw_data=self._serialize_raw(response.get("raw") or response.get("cleaned_raw")),
            status_hex=response.get("status_hex"),
            syn_count=response.get("syn_count") or 0,
            success=bool((status_step or {}).get("ok", True)),
            message=response.get("data_text") or response.get("text") or "",
        )

    def _safe_save_status_snapshot(self, status_step, commande=None):
        """Sauvegarde le snapshot MCF sans bloquer une fiscalisation deja reussie."""

        try:
            self._save_status_snapshot(status_step)
        except Exception:
            logger.exception(
                "Impossible d'enregistrer le snapshot MCF pour la commande %s.",
                getattr(commande, "pk", None),
            )

    def _safe_create_log(self, **kwargs):
        """Persiste un log MCF en mode best-effort pour ne pas casser le flux metier."""

        try:
            return self._create_log(**kwargs)
        except Exception:
            commande = kwargs.get("commande")
            logger.exception(
                "Impossible d'enregistrer le log MCF pour la commande %s.",
                getattr(commande, "pk", None),
            )
            return None

    def _parse_close_response(self, close_data: str) -> dict:
        """Analyse close response."""

        if not close_data:
            raise MCFInvoiceServiceError(f"Reponse 38h invalide ou absente : {close_data}")

        normalized_data = close_data[2:] if close_data.startswith("R:") else close_data
        parts = [part.strip() for part in normalized_data.split(",")]
        if len(parts) < 7:
            raise MCFInvoiceServiceError(f"Reponse 38h incomplete : {close_data}")

        returned_isf = ""
        if len(parts) >= 8:
            fc, tc, ft, dt_raw, mid, nif, fn, sig = parts[:8]
        else:
            fc, tc, ft, dt_raw, returned_isf, nif, sig = parts[:7]
            mid = returned_isf
            fn = ""

        dt_display = self._format_close_datetime(dt_raw)
        nim = mid or returned_isf or self._normalize_text(self.device.company_isf)
        security = {
            "fc": fc,
            "tc": tc,
            "ft": ft,
            "dt_raw": dt_raw,
            "dt_display": dt_display,
            "date_time": dt_display,
            "mid": mid,
            "isf": returned_isf or self._normalize_text(self.device.company_isf),
            "nif": nif,
            "fn": fn,
            "sig": sig,
            "code_def_dgi": sig,
            "counters": f"{fc}/{tc} {ft}".strip(),
            "nim": nim,
            "qr_code": f"RDCDEF01;{nim};{sig};{nif};{dt_raw}",
        }
        return self._normalize_security_payload(security)

    def _build_log_payload(self, commande, customer, invoice, items, payments):
        """Construit log payload."""

        return {
            "commande_id": getattr(commande, "pk", None),
            "device": {
                "id": self.device.pk,
                "name": self.device.name,
                "port": self.device.port,
                "company_nif": self.device.company_nif,
                "company_isf": self.device.company_isf,
            },
            "customer": customer,
            "invoice": invoice,
            "items": items,
            "payments": payments,
        }

    def _create_log(self, commande, request_data, success, response_data=None, message=""):
        """Execute le traitement create log."""

        return MCFInvoiceLog.objects.create(
            commande_id=getattr(commande, "pk", 0) or 0,
            device=self.device,
            request_data=self._json_safe(request_data) if request_data else None,
            response_data=self._json_safe(response_data) if response_data else None,
            success=success,
            message=message or None,
        )

    def send_invoice(self, commande, prepared_payload=None) -> dict:
        """Execute le traitement send invoice."""

        persist_logs = bool(getattr(commande, "pk", None))
        allow_existing_success = not bool((prepared_payload or {}).get("bypass_existing_log"))
        if allow_existing_success and persist_logs:
            existing_log = (
                MCFInvoiceLog.objects.filter(
                    commande_id=getattr(commande, "pk", None),
                    device=self.device,
                    success=True,
                )
                .order_by("-created_at")
                .first()
            )
            if existing_log:
                response_payload = self._json_safe(existing_log.response_data or {})
                security = self._normalize_security_payload(
                    (response_payload or {}).get("security") or response_payload
                )
                if response_payload is not None:
                    response_payload["security"] = self._json_safe(security)
                return {
                    "success": True,
                    "already_sent": True,
                    "device": self.device.name,
                    "port": self.device.port,
                    "log_id": existing_log.pk,
                    "security": security,
                    "response": response_payload,
                }

        duplicate_retry_available = True
        company_identities = self._build_company_identity_candidates(prepared_payload=prepared_payload)
        company_identity_index = 0
        retry_without_customer_nif = False
        credit_note_reference_candidates = None
        credit_note_reference_index = 0

        while True:
            client = None
            result = None
            request_payload = None
            invoice = {}
            current_company_identity = company_identities[company_identity_index]

            try:
                if prepared_payload:
                    total_ttc = Decimal(str(prepared_payload["totals"]["total_ttc"]))
                    total_tva = Decimal(str(prepared_payload["totals"].get("total_vat", 0) or 0))
                    if total_ttc <= 0:
                        raise MCFInvoiceServiceError(
                            "Impossible de fiscaliser une correction MCF avec un montant total nul ou negatif."
                        )
                    customer = self._build_customer_from_prepared(prepared_payload)
                    invoice = self._build_invoice_from_prepared(
                        prepared_payload,
                        company_identity=current_company_identity,
                        commande=commande,
                    )
                    items = self._build_items_from_prepared(prepared_payload)
                    payments = self._build_payments_from_prepared(prepared_payload)
                else:
                    self._validate_before_send(commande)
                    customer = self._build_customer_dict(commande)
                    invoice = self._build_invoice_dict(
                        commande,
                        company_identity=current_company_identity,
                    )
                    items = self._build_items(commande)
                    payments = self._build_payments(commande)
                    total_ttc = Decimal(str(getattr(commande, "montant_total", Decimal("0.00"))))
                    total_tva = Decimal(str(getattr(commande, "tva_montant", Decimal("0.00"))))

                self._ensure_tax_groups_supported(items)

                if invoice.get("invoice_type") in {"FA", "EA"}:
                    if credit_note_reference_candidates is None:
                        credit_note_reference_candidates = self._get_credit_note_reference_candidates(invoice)

                    if credit_note_reference_candidates:
                        current_reference_candidates = credit_note_reference_candidates[credit_note_reference_index:]
                        if not current_reference_candidates:
                            raise MCFInvoiceServiceError(
                                "Aucune reference exploitable ne reste disponible pour la facture d'avoir MCF."
                            )

                        current_reference = current_reference_candidates[0]
                        invoice["rr"] = current_reference["rr"]
                        invoice["rn"] = current_reference["rn"]
                        invoice["reference_candidates"] = current_reference_candidates

                if retry_without_customer_nif:
                    customer = {
                        **customer,
                        "cnif": "",
                    }

                customer_nif_optional = (
                    self._normalize_text(customer.get("ctype")).upper() == "PP"
                    and bool(self._normalize_text(customer.get("cnif")))
                )
                request_payload = self._build_log_payload(commande, customer, invoice, items, payments)
                if prepared_payload:
                    request_payload["fiscal_transaction_id"] = prepared_payload.get("fiscal_transaction_id")
                    request_payload["operation_type"] = prepared_payload.get("operation_type")
                    request_payload["source_numero"] = (prepared_payload.get("commande") or {}).get("source_numero")
                    request_payload["source_codedefdgi"] = (prepared_payload.get("commande") or {}).get("source_codedefdgi")

                # Port local ou passerelle de la boutique : toute la facture
                # part en un seul appel (send_invoice_flow).
                client, mcf = ouvrir_commandes(self.device)
                minimum_finalize_datetime = self._get_last_known_mcf_fiscal_datetime()
                current_system_datetime = timezone.localtime(timezone.now()).replace(
                    tzinfo=None,
                    microsecond=0,
                )

                result = mcf.send_invoice_flow(
                    customer=customer,
                    invoice=invoice,
                    items=items,
                    payments=payments,
                    expected_total=total_ttc,
                    expected_vat=total_tva,
                    minimum_finalize_datetime=minimum_finalize_datetime,
                    system_datetime=current_system_datetime,
                    expected_groups=self._build_expected_groups(items),
                )

                self._safe_save_status_snapshot(
                    ((result or {}).get("steps") or {}).get("status"),
                    commande=commande,
                )

                close_step = ((result or {}).get("steps") or {}).get("close") or {}
                if not close_step.get("ok"):
                    raise MCFInvoiceServiceError(
                        f"La commande 38h n'a pas abouti : {close_step.get('data', '')}"
                    )

                security = self._normalize_security_payload(
                    self._parse_close_response(close_step.get("data", ""))
                )
                response_payload = {
                    "device": {
                        "id": self.device.pk,
                        "name": self.device.name,
                        "port": self.device.port,
                    },
                    "result": result,
                    "security": security,
                }
                log_payload = {
                    "request_data": self._json_safe(request_payload) if request_payload else None,
                    "response_data": self._json_safe(response_payload),
                    "success": True,
                    "message": "Facture envoyee au MCF avec succes.",
                }

                if persist_logs:
                    self._safe_create_log(
                        commande=commande,
                        request_data=request_payload,
                        success=True,
                        response_data=response_payload,
                        message="Facture envoyee au MCF avec succes.",
                    )

                return {
                    "success": True,
                    "device": self.device.name,
                    "port": self.device.port,
                    "security": security,
                    "response": self._json_safe(response_payload),
                    "log_payload": log_payload,
                }

            except (MCFClientError, ValueError, KeyError, AttributeError, MCFInvoiceServiceError) as exc:
                message = str(exc)
                business_exc = None

                if duplicate_retry_available and self._is_duplicate_invoice_number_error(message):
                    duplicate_retry_available = False
                    if prepared_payload and prepared_payload.get("preserve_original_numero"):
                        self._rotate_prepared_invoice_number(commande, prepared_payload)
                    else:
                        self._rotate_local_invoice_number(commande, prepared_payload=prepared_payload)
                    continue

                if (
                    isinstance(exc, MCFClientError)
                    and self._is_invalid_original_reference_mcf_error(message)
                    and invoice.get("invoice_type") in {"FA", "EA"}
                    and credit_note_reference_candidates
                    and credit_note_reference_index + 1 < len(credit_note_reference_candidates)
                ):
                    failed_reference = credit_note_reference_candidates[credit_note_reference_index]
                    credit_note_reference_index += 1
                    next_reference = credit_note_reference_candidates[credit_note_reference_index]
                    retry_without_customer_nif = False
                    logger.warning(
                        "MCF n'a pas retrouve la facture d'origine pour la commande %s avec RN=%s. "
                        "Nouvel essai avec RN=%s.",
                        getattr(commande, "pk", None),
                        failed_reference["rn"],
                        next_reference["rn"],
                    )
                    continue

                if (
                    isinstance(exc, MCFClientError)
                    and self._is_invalid_nif_mcf_error(message)
                    and "Commande C3" in message
                    and not retry_without_customer_nif
                    and customer_nif_optional
                ):
                    retry_without_customer_nif = True
                    logger.warning(
                        "MCF a rejete le NIF du client PP pour la commande %s. Nouvel essai sans NIF client.",
                        getattr(commande, "pk", None),
                    )
                    continue

                if (
                    isinstance(exc, MCFClientError)
                    and self._is_invalid_nif_mcf_error(message)
                    and "Commande C0" in message
                    and company_identity_index + 1 < len(company_identities)
                ):
                    previous_identity = current_company_identity
                    company_identity_index += 1
                    retry_without_customer_nif = False
                    logger.warning(
                        "MCF a rejete le NIF societe %s (%s) pour la commande %s. Nouvel essai avec %s (%s).",
                        previous_identity["nif"],
                        previous_identity["source_label"],
                        getattr(commande, "pk", None),
                        company_identities[company_identity_index]["nif"],
                        company_identities[company_identity_index]["source_label"],
                    )
                    continue

                if isinstance(exc, MCFTaxRateMismatchError):
                    business_exc = MCFTaxConfigurationError(message)
                elif isinstance(exc, MCFInvalidNIFError):
                    business_exc = exc
                elif self._is_invalid_nif_mcf_error(message):
                    business_exc = self._translate_mcf_nif_error(
                        message,
                        customer=locals().get("customer"),
                        company_identity=current_company_identity,
                    )

                if business_exc is not None:
                    message = str(business_exc)

                if business_exc is not None:
                    logger.warning(
                        "Facture MCF rejetee pour erreur metier, commande %s: %s",
                        getattr(commande, "pk", None),
                        message,
                    )
                elif self._is_clock_chronology_mcf_error(message):
                    logger.warning(
                        "Incoherence d'horloge MCF detectee pour la commande %s: %s",
                        getattr(commande, "pk", None),
                        message,
                    )
                elif self._is_temporary_server_unavailable_mcf_error(message):
                    logger.warning(
                        "Indisponibilite temporaire du serveur MCF pour la commande %s: %s",
                        getattr(commande, "pk", None),
                        message,
                    )
                elif isinstance(exc, MCFUnsupportedTaxGroupError):
                    logger.warning("Commande %s non fiscalisable par le MCF : %s", getattr(commande, "pk", None), message)
                else:
                    logger.exception(
                        "Erreur MCF lors de la fiscalisation de la commande %s",
                        getattr(commande, "pk", None),
                    )
                if persist_logs:
                    self._safe_create_log(
                        commande=commande,
                        request_data=request_payload,
                        success=False,
                        response_data={"error": message, "partial_result": result},
                        message=message,
                    )
                if business_exc is not None:
                    raise business_exc from exc
                raise MCFInvoiceServiceError(message) from exc

            finally:
                if client:
                    client.close()
