# -*- coding: utf-8 -*-
# Solo Outlook (pip install pywin32)

import argparse, os, sys, logging, traceback, time

def _split_list(s):
    if not s:
        return []
    return [x.strip() for x in s.replace(";", ",").split(",") if x.strip()]

def _check_files(paths):
    miss = [p for p in paths if p and not os.path.isfile(p)]
    if miss:
        raise FileNotFoundError("No se encontraron estos adjuntos: " + "; ".join(miss))

def _obtener_outlook():
    try:
        import win32com.client as win32
    except ImportError:
        raise RuntimeError(
            "Outlook no disponible: falta pywin32.\n"
            "Instalá:  python -m pip install pywin32\n"
            "y luego:  python -m pywin32_postinstall -install"
        )
    try:
        return win32.Dispatch("Outlook.Application")
    except Exception as e:
        raise RuntimeError(
            "No se pudo automatizar Outlook. ¿Está instalado/configurado?\n"
            f"Detalle: {e}"
        )

def enviar_por_outlook(destinatarios, asunto, cuerpo, adjuntos, cc=None, bcc=None, mostrar=False, es_html=False):
    adjuntos = adjuntos or []
    if adjuntos:
        _check_files(adjuntos)

    outlook = _obtener_outlook()
    mail = outlook.CreateItem(0)  # olMailItem

    mail.To = ";".join(destinatarios)
    if cc:  mail.CC  = ";".join(cc)
    if bcc: mail.BCC = ";".join(bcc)

    mail.Subject = asunto or ""

    if es_html:
        try:
            mail.BodyFormat = 2  # olFormatHTML
        except Exception:
            pass
        mail.HTMLBody = cuerpo or ""
    else:
        mail.Body = cuerpo or ""

    for p in adjuntos:
        mail.Attachments.Add(os.path.abspath(p))

    if mostrar:
        mail.Display(True)
    else:
        mail.Send()

def main():
    ap = argparse.ArgumentParser(description="Enviar correo por Outlook (COM).")
    ap.add_argument("--to", required=True, help="Destinatarios (separar por ; o ,).")
    ap.add_argument("--cc", help="CC (opcional, ; o ,).")
    ap.add_argument("--bcc", help="BCC (opcional, ; o ,).")
    ap.add_argument("--subject", default="", help="Asunto.")

    ap.add_argument("--body", default="", help="Texto/HTML del cuerpo (si --html, lo trata como HTML).")
    ap.add_argument("--body-file", help="Archivo de texto o HTML para usar como cuerpo.")
    ap.add_argument("--html", action="store_true", help="Interpretar el cuerpo como HTML.")

    ap.add_argument("--attach", action="append",
                    help="Ruta(s) de adjunto. Podés repetir --attach y/o separar por ; o ,")
    ap.add_argument("--display", action="store_true", help="Mostrar el mail antes de enviar.")
    ap.add_argument("--log-file", default="", help="Ruta de log (opcional).")
    ap.add_argument("--sleep-ms", type=int, default=0, help="Pausa antes de salir (ms).")

    args = ap.parse_args()

    # logging
    if args.log_file:
        logging.basicConfig(
            filename=args.log_file,
            level=logging.INFO,
            format="%(asctime)s [%(levelname)s] %(message)s",
        )
    else:
        logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")

    destinatarios = _split_list(args.to)
    if not destinatarios:
        print("Error: --to requiere al menos un destinatario.", file=sys.stderr)
        sys.exit(2)

    cc  = _split_list(args.cc)  if args.cc  else []
    bcc = _split_list(args.bcc) if args.bcc else []

    cuerpo = args.body
    if args.body_file:
        try:
            with open(args.body_file, "r", encoding="utf-8-sig") as f:
                cuerpo = f.read()
        except Exception as e:
            print(f"Error leyendo --body-file: {e}", file=sys.stderr)
            sys.exit(2)

    # adjuntos opcionales
    adjuntos = []
    if args.attach:
        for item in args.attach:
            adjuntos.extend(_split_list(item))

    try:
        logging.info("ENVIO: to=%s subject=%s html=%s adjuntos=%s", destinatarios, args.subject, args.html, adjuntos)
        enviar_por_outlook(
            destinatarios=destinatarios,
            asunto=args.subject,
            cuerpo=cuerpo,
            adjuntos=adjuntos,
            cc=cc, bcc=bcc,
            mostrar=args.display,
            es_html=args.html
        )
        logging.info("OK: enviado por Outlook.")
        print("Correo enviado por Outlook.")
        if args.sleep_ms > 0:
            time.sleep(args.sleep_ms / 1000.0)
        sys.exit(0)
    except FileNotFoundError as e:
        logging.error("ERROR adjuntos: %s", e)
        print(str(e), file=sys.stderr); sys.exit(3)
    except Exception as e:
        logging.error("ERROR: %s\n%s", e, traceback.format_exc())
        print(str(e), file=sys.stderr); sys.exit(1)

if __name__ == "__main__":
    main()
