import os
import ssl
import smtplib
from email.message import EmailMessage
from datetime import datetime, timezone
from dotenv import load_dotenv

load_dotenv()

EMAIL_HOST = os.getenv("EMAIL_HOST")
EMAIL_PORT = int(os.getenv("EMAIL_PORT", 587))
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS")
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD")
EMAIL_USE_SSL = os.getenv("EMAIL_USE_SSL", "false").strip().lower() in {"1", "true", "yes"}
EMAIL_TIMEOUT = int(os.getenv("EMAIL_TIMEOUT", "30"))

# Config: TO = you, CC = Naveen (comma/semicolon supported)
EMAIL_TO = os.getenv("EMAIL_TO", "")       # e.g. "abhishek.mishra@ardem.com"
EMAIL_CC = os.getenv("EMAIL_CC", "")       # e.g. "naveen@ardem.com"


# ---------- Helpers ----------
def _parse_addr_list(raw: str):
    """Split comma/semicolon-separated addresses, strip spaces, drop empties."""
    if not raw:
        return []
    parts = [p.strip() for p in raw.replace(";", ",").split(",")]
    return [p for p in parts if p]

def extract_state_from_filename(filename: str) -> str:
    """Extract state from filename prefix (e.g., 'PA-12345.pdf' → 'PA')."""
    if not filename:
        return ""
    return filename.split("-")[0] if "-" in filename else ""

def extract_date_from_s3_path(s3_path: str) -> str:
    """
    Extract Document/Batch date from S3 path.
    Expected: VITU/YYYY/MONTH/MM.DD_Files/... → returns YYYY-MM-DD
    Example:  VITU/2025/AUGUST/08.20_Files/PA_08.20/PA-3587.pdf -> 2025-08-20
    """
    try:
        parts = s3_path.split("/")
        year = parts[1]
        folder = parts[3]            # "08.20_Files"
        mmdd = folder.split("_")[0]  # "08.20"
        mm, dd = mmdd.split(".")
        return f"{year}-{mm}-{dd}"
    except Exception:
        return ""

def _overall_state(records) -> str:
    """
    Determine a single 'State' line for the header:
    - If all records share the same non-empty state, return that.
    - If mixed or none, return 'Multiple' (if >1 distinct) or '' (if none).
    """
    states = set()
    for r in (records or []):
        st = r.get("state") or extract_state_from_filename(r.get("filename", ""))
        if st:
            states.add(st)
    if not states:
        return ""
    if len(states) == 1:
        return states.pop()
    return "Multiple"


# ---------- Email Body Builders ----------
def _build_html_body(records, note=None, totals=None) -> str:
    """
    Styled HTML matching the reference:
    - Title: ARDEM VITU - FILE DOWNLOAD SUMMARY
    - Provider + State (derived) + Completion Time
    - Summary (Total Files Received, Successful Downloads)
    - Table with bold filenames and smaller S3 location
    - Optional red alert box for notes (e.g., 'No PDFs found...')
    """
    totals = totals or {}
    success_count = totals.get("success", len(records or []))
    files_received = totals.get("received", len(records or []))
    completed_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    header_state = _overall_state(records)

    brand_dark = "#1e2636"
    border_gray = "#e5e7eb"
    section_bg = "#f8fafc"

    # Optional alert box
    alert_html = ""
    if note:
        alert_html = f"""
        <div style="padding:12px;border:1px solid #f5c2c7;background:#f8d7da;color:#842029;border-radius:6px;margin:12px 0;">
          <strong>Notice:</strong> {note}
        </div>
        """

    # Table rows
    rows = []
    for r in (records or []):
        filename = r.get("filename", "")
        state = r.get("state") or extract_state_from_filename(filename)
        doc_date = r.get("doc_date") or extract_date_from_s3_path(r.get("s3_location", ""))
        processed_time = r.get("processed_time", "")
        s3_location = r.get("s3_location", "")
        rows.append(f"""
          <tr>
            <td style="font-weight:700;">{filename}</td>
            <td>{state}</td>
            <td>{doc_date}</td>
            <td>{processed_time}</td>
            <td style="font-size:12px; white-space:nowrap;">{s3_location}</td>
          </tr>
        """)

    if not rows:
        rows_html = """
          <tr><td colspan="5" style="text-align:center; padding:14px;">No successful files today.</td></tr>
        """
    else:
        rows_html = "\n".join(rows)

    return f"""
<!DOCTYPE html>
<html>
  <body style="font-family:Segoe UI, Arial, sans-serif; color:#111827; margin:0; padding:0;">
    <div style="max-width:960px; margin:0 auto; padding:24px;">
      <!-- Title -->
      <h2 style="margin:0 0 8px 0; font-weight:700; color:{brand_dark};">
        📘 ARDEM VITU - FILE DOWNLOAD SUMMARY
      </h2>

      <!-- Provider + state + completion -->
      <div style="padding:12px 16px; background:{section_bg}; border:1px solid {border_gray}; border-radius:6px; margin-bottom:16px;">
        <div style="margin:2px 0;"><strong>🏷️ Provider:</strong> VITU</div>
        <div style="margin:2px 0;"><strong>🗺️ State:</strong> {header_state if header_state else '-'} </div>
        <div style="margin:2px 0;"><strong>⏱️ Completion Time:</strong> {completed_utc}</div>
      </div>

      <!-- Summary -->
      <h3 style="margin:16px 0 8px 0; color:{brand_dark};">📊 Summary</h3>
      <div style="padding:12px 16px; border:1px solid {border_gray}; border-radius:6px; margin-bottom:20px;">
        <ul style="margin:0; padding-left:18px;">
          <li><span style="color:#2563eb;">📥</span> <strong>Total Files Received:</strong> {files_received}</li>
          <li><span style="color:#16a34a;">✅</span> <strong>Successful Downloads:</strong> {success_count}</li>
        </ul>
      </div>

      {alert_html}

      <!-- Table -->
      <h3 style="margin:0 0 8px 0; color:{brand_dark};">🗂️ File Details</h3>
      <table role="table" cellspacing="0" cellpadding="10" style="width:100%; border-collapse:collapse; border:1px solid {border_gray};">
        <thead>
          <tr style="background:{brand_dark}; color:#ffffff;">
            <th align="left">Filename</th>
            <th align="left">State</th>
            <th align="left">Document/Batch Date</th>
            <th align="left">Processed Time</th>
            <th align="left">S3 Location</th>
          </tr>
        </thead>
        <tbody>
          {rows_html}
        </tbody>
      </table>

      <p style="color:#6b7280; font-size:12px; margin-top:16px;">
        This is an automated message from the ARDEM VITU system.
      </p>
    </div>
  </body>
</html>
    """


def _build_text_body(records, note=None, totals=None) -> str:
    """Plain-text fallback for clients that block HTML."""
    totals = totals or {}
    success_count = totals.get("success", len(records or []))
    files_received = totals.get("received", len(records or []))
    completed_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    header_state = _overall_state(records)

    lines = [
        "ARDEM VITU - FILE DOWNLOAD SUMMARY",
        f"Provider: VITU",
        f"State: {header_state if header_state else '-'}",
        f"Completion Time: {completed_utc}",
        "",
        "Summary:",
        f"  Total Files Received: {files_received}",
        f"  Successful Downloads: {success_count}",
        ""
    ]
    if note:
        lines += [f"Notice: {note}", ""]

    if records:
        header = ["Filename", "State", "Doc/Batch Date", "Processed Time", "S3 Location"]
        lines.append(" | ".join(header))
        lines.append("-" * 100)
        for r in records:
            filename = r.get("filename", "")
            state = r.get("state") or extract_state_from_filename(filename)
            doc_date = r.get("doc_date") or extract_date_from_s3_path(r.get("s3_location", ""))
            processed_time = r.get("processed_time", "")
            s3_location = r.get("s3_location", "")
            lines.append(" | ".join([filename, state, doc_date, processed_time, s3_location]))
    else:
        lines.append("No successful files today.")
    return "\n".join(lines)


# ---------- Main Send ----------
def send_notification(subject: str, records: list, note: str = None, totals=None):
    """
    Send formatted email.
    - Subject automatically prefixed with 'VITU Automation - '
    - `records`: list of dicts (filename, processed_time, s3_location [, state, doc_date])
    - `note`: optional line (e.g., 'No PDFs found at this S3 location: ...')
    - `totals`: optional dict like {'received': int, 'success': int}
    """
    try:
        if not all([EMAIL_HOST, EMAIL_PORT, EMAIL_ADDRESS, EMAIL_PASSWORD, EMAIL_TO]):
            print("❌ Missing email configuration.")
            return

        to_list = _parse_addr_list(EMAIL_TO)
        cc_list = _parse_addr_list(EMAIL_CC)

        # De-dup CC if an address also appears in TO
        to_lower = {a.lower() for a in to_list}
        cc_list = [a for a in cc_list if a.lower() not in to_lower]

        msg = EmailMessage()
        msg["Subject"] = f"VITU Automation - {subject}"
        msg["From"] = EMAIL_ADDRESS
        msg["To"] = ", ".join(to_list)
        if cc_list:
            msg["Cc"] = ", ".join(cc_list)

        # Plain text + HTML
        msg.set_content(_build_text_body(records or [], note=note, totals=totals))
        msg.add_alternative(_build_html_body(records or [], note=note, totals=totals), subtype="html")

        tls_context = ssl.create_default_context()
        if EMAIL_USE_SSL:
            # Implicit TLS: normally port 465. Do not call starttls() here.
            with smtplib.SMTP_SSL(
                EMAIL_HOST, EMAIL_PORT, timeout=EMAIL_TIMEOUT, context=tls_context
            ) as smtp:
                smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
                smtp.send_message(msg)
        else:
            # Explicit TLS / STARTTLS: normally port 587 for Microsoft 365.
            with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT, timeout=EMAIL_TIMEOUT) as smtp:
                smtp.ehlo()
                if not smtp.has_extn("starttls"):
                    raise RuntimeError(
                        f"SMTP server {EMAIL_HOST}:{EMAIL_PORT} does not advertise STARTTLS. "
                        "Use EMAIL_USE_SSL=true only for an implicit-TLS SMTP endpoint."
                    )
                smtp.starttls(context=tls_context)
                smtp.ehlo()
                smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
                smtp.send_message(msg)

        print("✅ Email notification sent.")
    except Exception as e:
        print(f"❌ Failed to send email: {e}")
