import email
import imaplib
from email.header import decode_header
from email.utils import parseaddr


class EmailIngestor:
    def __init__(self, config, logger, ticket_service):
        self.config = config
        self.logger = logger
        self.ticket_service = ticket_service

    def import_unseen(self):
        if not self.config.getboolean("EMAIL", "enable_email_ingestion", fallback=False):
            self.logger.info("Ingestion email desactivee")
            return 0

        host = self.config.get("EMAIL", "imap_host")
        port = self.config.getint("EMAIL", "imap_port", fallback=993)
        username = self.config.get("EMAIL", "imap_username")
        password = self.config.get("EMAIL", "imap_password")
        mailbox = self.config.get("EMAIL", "mailbox", fallback="INBOX")
        delete_after_import = self.config.getboolean("EMAIL", "delete_after_import", fallback=False)

        imported = 0
        with imaplib.IMAP4_SSL(host, port) as client:
            client.login(username, password)
            client.select(mailbox)
            status, data = client.search(None, "UNSEEN")
            if status != "OK":
                self.logger.warning("Recherche IMAP UNSEEN impossible")
                return 0

            for message_id in data[0].split():
                status, fetched = client.fetch(message_id, "(RFC822)")
                if status != "OK" or not fetched:
                    continue

                raw_message = fetched[0][1]
                parsed = email.message_from_bytes(raw_message)
                subject = self._decode_header(parsed.get("Subject", "Demande SAV email"))
                sender_name, sender_email = parseaddr(parsed.get("From", ""))
                sender_name = self._decode_header(sender_name)
                body = self._extract_body(parsed)
                if not body:
                    self.logger.warning(f"Email ignore sans contenu: {subject}")
                    continue

                self.ticket_service.create_support_request(
                    "email",
                    sender_email,
                    sender_name or sender_email,
                    body,
                    subject,
                )
                imported += 1

                if delete_after_import:
                    client.store(message_id, "+FLAGS", "\\Deleted")
                else:
                    client.store(message_id, "+FLAGS", "\\Seen")

            if delete_after_import:
                client.expunge()

        self.logger.info(f"Emails importes: {imported}")
        return imported

    def _decode_header(self, value):
        parts = decode_header(value or "")
        decoded = []
        for text, charset in parts:
            if isinstance(text, bytes):
                decoded.append(text.decode(charset or "utf-8", errors="replace"))
            else:
                decoded.append(text)
        return "".join(decoded).strip()

    def _extract_body(self, message):
        if message.is_multipart():
            for part in message.walk():
                content_type = part.get_content_type()
                disposition = part.get_content_disposition()
                if content_type == "text/plain" and disposition != "attachment":
                    payload = part.get_payload(decode=True)
                    if payload:
                        return payload.decode(part.get_content_charset() or "utf-8", errors="replace").strip()
        payload = message.get_payload(decode=True)
        if payload:
            return payload.decode(message.get_content_charset() or "utf-8", errors="replace").strip()
        return ""
