# -*- coding: utf-8 -*-
"""Shared IMAP / MIME helpers for helpdesk mail ingestion."""
import re
from email.header import decode_header
from email.utils import getaddresses, parseaddr


def decode_mime_header(value):
    if not value:
        return ''
    parts = []
    for fragment, charset in decode_header(value):
        if isinstance(fragment, bytes):
            parts.append(fragment.decode(charset or 'utf-8', errors='replace'))
        else:
            parts.append(fragment)
    return ''.join(parts)


def extract_addresses(header_value):
    if not header_value:
        return ''
    formatted = []
    for name, addr in getaddresses([header_value]):
        if not addr:
            continue
        formatted.append(f'{name} <{addr}>' if name else addr)
    return ', '.join(formatted)


def extract_email_list(header_value):
    if not header_value:
        return []
    return [addr.lower() for _name, addr in getaddresses([header_value]) if addr]


def parse_email_body(msg):
    body_text = ''
    body_html = ''
    if msg.is_multipart():
        for part in msg.walk():
            if 'attachment' in str(part.get('Content-Disposition', '')):
                continue
            payload = part.get_payload(decode=True)
            if not payload:
                continue
            charset = part.get_content_charset() or 'utf-8'
            try:
                decoded = payload.decode(charset, errors='replace')
            except (LookupError, UnicodeDecodeError):
                decoded = payload.decode('utf-8', errors='replace')
            ctype = part.get_content_type()
            if ctype == 'text/plain' and not body_text:
                body_text = decoded
            elif ctype == 'text/html' and not body_html:
                body_html = decoded
    else:
        payload = msg.get_payload(decode=True)
        if payload:
            charset = msg.get_content_charset() or 'utf-8'
            try:
                decoded = payload.decode(charset, errors='replace')
            except (LookupError, UnicodeDecodeError):
                decoded = payload.decode('utf-8', errors='replace')
            if msg.get_content_type() == 'text/html':
                body_html = decoded
            else:
                body_text = decoded
    if not body_text and body_html:
        body_text = re.sub(r'<[^>]+>', ' ', body_html)
    return body_text, body_html


TICKET_REF_RE = re.compile(r'SO-HD/\d{4}/\d+', re.IGNORECASE)


def extract_ticket_ref(subject):
    if not subject:
        return False
    match = TICKET_REF_RE.search(subject)
    return match.group(0).upper() if match else False
