#wp_invoices_mail_app/email_client.py
import imaplib
import email
from email.message import Message, EmailMessage
from email.utils import parseaddr
from pathlib import Path
from typing import List, Tuple, Optional
import smtplib

from .config import MailConfig


def _connect_imap():
    if MailConfig.IMAP_USE_SSL:
        imap = imaplib.IMAP4_SSL(MailConfig.IMAP_HOST, MailConfig.IMAP_PORT)
    else:
        imap = imaplib.IMAP4(MailConfig.IMAP_HOST, MailConfig.IMAP_PORT)

    imap.login(MailConfig.IMAP_USERNAME, MailConfig.IMAP_PASSWORD)
    return imap


def fetch_unseen_messages(folder: str = "INBOX"):
    imap = _connect_imap()
    imap.select(folder)
    status, data = imap.search(None, "UNSEEN")
    if status != "OK":
        imap.logout()
        return None, []

    ids = data[0].split()
    messages = []
    for msg_id in ids:
        status, msg_data = imap.fetch(msg_id, "(RFC822)")
        if status != "OK":
            continue
        raw_email = msg_data[0][1]
        msg = email.message_from_bytes(raw_email)
        messages.append((msg_id, msg))

    return imap, messages


def extract_invoice_attachments(msg: Message) -> List[Tuple[str, bytes, str]]:
    attachments = []
    for part in msg.walk():
        if part.get("Content-Disposition") and "attachment" in part.get("Content-Disposition").lower():
            filename = part.get_filename()
            if not filename:
                continue    
            content_type = part.get_content_type()
            print("CONTENT TYPE")
            print(content_type)
            if not (
                content_type == "application/pdf" or
                content_type.startswith("image/")
            ):
                continue

            data = part.get_payload(decode=True)
            attachments.append((filename, data, content_type))

    return attachments


def save_attachments(attachments, base_dir: Path) -> List[Path]:
    saved_paths = []
    base_dir.mkdir(parents=True, exist_ok=True)

    for filename, data, _ in attachments:
        safe_name = filename.replace("/", "_").replace("\\", "_")
        out_path = base_dir / safe_name

        i = 1
        while out_path.exists():
            out_path = base_dir / f"{out_path.stem}_{i}{out_path.suffix}"
            i += 1

        out_path.write_bytes(data)
        saved_paths.append(out_path)

    return saved_paths

def has_inline_images(msg):
    """
    Devuelve True si el correo tiene imágenes inline (no adjuntas),
    por ejemplo fotos insertadas en el cuerpo del mensaje.
    """
    for part in msg.walk():
        if part.get_content_maintype() == "multipart":
            continue

        content_disposition = (part.get("Content-Disposition") or "").lower()
        content_type = part.get_content_type().lower()

        # Si es imagen y NO viene marcada como attachment, la consideramos inline
        if content_type.startswith("image/") and "attachment" not in content_disposition:
            return True

    return False

""" def send_ack_email(to_address: str, original_subject: str, saved_files: List[Path]):
    msg = EmailMessage()
    msg["From"] = MailConfig.FROM_ADDRESS
    msg["To"] = to_address
    msg["Subject"] = f"[Invoice Bot] Hemos recibido tus facturas – {original_subject}"

    lines = []
    lines.append("Hola 👋")
    lines.append("")
    lines.append("Hemos recibido tu correo y los archivos adjuntos fueron guardados.")
    lines.append("")
    if saved_files:
        lines.append("Archivos recibidos:")
        for p in saved_files:
            lines.append(f"- {p.name}")
    else:
        lines.append("⚠️ No se encontraron adjuntos de factura válidos.")
    lines.append("")
    lines.append("En las próximas versiones recibirás la factura digitalizada.")
    lines.append("")
    lines.append("Saludos,")
    lines.append("Invoice Bot – Absolutems")

    msg.set_content("\n".join(lines))

    server = smtplib.SMTP(MailConfig.SMTP_HOST, MailConfig.SMTP_PORT)
    if MailConfig.SMTP_USE_TLS:
        server.starttls()

    if MailConfig.SMTP_USERNAME:
        server.login(MailConfig.SMTP_USERNAME, MailConfig.SMTP_PASSWORD)

    server.send_message(msg)
    server.quit() """

def send_processed_invoices_email(
    to_address: str,
    original_subject: str,
    body_text: str,
    pdf_paths: List[str],
    body_html: Optional[str] = None,
):
    msg = EmailMessage()
    msg["From"] = MailConfig.FROM_ADDRESS
    msg["To"] = to_address
    msg["Subject"] = f"[Invoice Bot] Processing result – {original_subject}"

    if body_html:
        # multipart/alternative: texto plano + HTML
        msg.set_content(body_text)
        msg.set_content(body_text, subtype="html")
        #msg.add_alternative(body_html, subtype="html")
    else:
        msg.set_content(body_text)

    for idx, pdf_path in enumerate(pdf_paths, start=1):
        if not pdf_path:
            continue
        p = Path(pdf_path)
        if not p.exists():
            continue
        with p.open("rb") as f:
            pdf_data = f.read()
        filename = (
            f"invoice_revision_{idx}.pdf" if len(pdf_paths) > 1
            else "invoice_revision.pdf"
        )
        msg.add_attachment(
            pdf_data,
            maintype="application",
            subtype="pdf",
            filename=filename,
        )

    server = smtplib.SMTP(MailConfig.SMTP_HOST, MailConfig.SMTP_PORT)
    if MailConfig.SMTP_USE_TLS:
        server.starttls()

    if MailConfig.SMTP_USERNAME:
        server.login(MailConfig.SMTP_USERNAME, MailConfig.SMTP_PASSWORD)

    server.send_message(msg)
    server.quit()

