import os
import re
import smtplib
import ssl
from email.message import EmailMessage
from typing import Dict, Iterable, List, Optional, Sequence, Union
 
import pandas as pd
import requests
from dotenv import load_dotenv
 
load_dotenv()
 
SMTP_HOST = os.getenv("SMTP_HOST", "smtp-mail.outlook.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", "587"))
SMTP_USERNAME = os.getenv("SMTP_USERNAME", os.getenv("GRAPH_USER", ""))
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD", "")
SMTP_FROM_ADDRESS = os.getenv("SMTP_FROM_ADDRESS", SMTP_USERNAME)
 
 
def clean_test_case_title(title: str) -> str:
    """Mirror email_utils.clean_test_case_title for consistent formatting."""
    try:
        text = str(title)
    except Exception:
        return ""
    match = re.match(r"^\s*\[[^\]]*\]\s*", text)
    if match:
        text = text[match.end() :]
    return text
 
 
def _normalize_recipients(raw: Optional[Union[str, Iterable[str]]]) -> List[str]:
    if not raw:
        return []
    if isinstance(raw, str):
        source = raw.split(",")
    else:
        source = raw
    normalized: List[str] = []
    for item in source:
        if not item:
            continue
        addr = str(item).strip()
        if addr:
            normalized.append(addr)
    return normalized
 
 
def _build_html_body(
    report_url: str,
    summary_data: Dict,
    detailed_report: Dict[str, Iterable[Dict]],
) -> str:
    passed_count = int(summary_data.get("Total Steps Passed", 0) or 0)
    failed_count = int(summary_data.get("Total Steps Failed", 0) or 0)
    total_count = passed_count + failed_count
    pass_percent_str = f"{int((passed_count / total_count) * 100)}%" if total_count else "0%"
 
    run_start = summary_data.get("Run Start Time", "")
    run_end = summary_data.get("Run End Time", "")
    duration = ""
    if run_start and run_end:
        try:
            duration = (
                str(pd.to_datetime(run_end) - pd.to_datetime(run_start)).replace("0 days ", "")
            )
        except Exception:
            duration = ""
 
    html_rows = []
    for row in detailed_report.get("rows", []):
        cells = []
        for col in detailed_report.get("columns", []):
            value = row.get(col, "")
            if col.strip().lower() == "test case title":
                value = clean_test_case_title(value)
            if col.strip().lower() == "status":
                cells.append(f"<td class='status-{str(value).lower()}'>{value}</td>")
            else:
                cells.append(f"<td>{value}</td>")
        html_rows.append("<tr>" + "".join(cells) + "</tr>")
 
    columns_html = "".join(f"<th>{col}</th>" for col in detailed_report.get("columns", []))
    rows_html = "".join(html_rows)
 
    html_content = f"""
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>HCLTech - Execution Report</title>
  <style>
    body {{
      background: #f8f9ff;
      margin: 0;
      padding: 20px;
      color: #1C1C1C;
      font-family: Arial, sans-serif;
    }}
    .container {{
      max-width: 1000px;
      margin: 0 auto;
      background: white;
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 6px 20px rgba(18,32,64,0.06);
    }}
    h2 {{ color: #000; }}
    table {{
      width: 100%;
      border-collapse: collapse;
      margin-top: 18px;
      font-size: 14px;
    }}
    th {{
      background-color: #0949F6 !important;
      color: #ffffff !important;
      padding: 10px;
      text-align: left;
    }}
    td {{
      background-color: #ffffff !important;
      padding: 10px;
      border-bottom: 1px solid #f1f3ff;
      color: #000000;
    }}
    .status-passed {{ color: #00994C; font-weight: bold; }}
    .status-failed {{ color: #FF4D4F; font-weight: bold; }}
    .btn {{
      display:inline-block;
      background-color: #0949F6 !important;
      color: #ffffff !important;
      padding: 10px 16px;
      text-decoration: none;
      border-radius: 8px;
      font-weight: bold;
      margin-top: 16px;
    }}
    .logo {{ font-size: 20px; font-weight: bold; color: #000; }}
    .accent-bar {{
      height: 6px;
      border-radius: 6px;
      background: linear-gradient(90deg,#6F31FF,#0949F6);
      margin-top: 12px;
    }}
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <div class="logo">IDC_Family_Safety Windows Regression AI Agent Report</div>
    </div>
 
   <h2>Test Summary</h2>
   <table>
     <thead>
       <tr>
         <th>Total</th>
         <th>Passed</th>
         <th>Failed</th>
         <th>Pass %</th>
       </tr>
     </thead>
     <tbody>
       <tr>
         <td>{total_count}</td>
         <td>{passed_count}</td>
         <td>{failed_count}</td>
         <td>{pass_percent_str}</td>
       </tr>
     </tbody>
   </table>
 
   <h2>Execution Summary</h2>
   <table>
     <thead>
       <tr>
         <th>Run Start Time</th>
         <th>Run End Time</th>
         <th>Total Duration</th>
       </tr>
     </thead>
     <tbody>
       <tr>
         <td>{run_start}</td>
         <td>{run_end}</td>
         <td>{duration}</td>
       </tr>
     </tbody>
   </table>
 
   <h2>Detailed Execution Report</h2>
   <table>
     <thead>
       <tr>{columns_html}</tr>
     </thead>
     <tbody>
       {rows_html}
     </tbody>
   </table>
 
    <a href="{report_url}" class="btn">Download Full Report</a>
    <div class="accent-bar"></div>
    <p style="color:#7D7D7D;font-size:12px;margin-top:24px;">
      Note: This is an automated email generated by the HCLTech Exploratory Agent. Do not reply to this email.
    </p>
  </div>
</body>
</html>
"""
    return html_content
 
 
def sendEmail(
    recipients,
    report_url,
    login_url,
    summary_data,
    test_cases,
    test_summary,
    execution_summary,
    detailed_report,
):
    """Drop-in replacement for send_email that sends via SMTP instead of Graph API."""
 
    html_content = _build_html_body(report_url, summary_data, detailed_report)
 
    if not recipients:
        recipients = os.getenv("MAIL_RECIPIENTS", "")
 
    cc_addresses = _normalize_recipients(recipients)
 
    primary_recipients_env = os.getenv("PRIMARY_RECIPIENT", "")
    to_addresses = _normalize_recipients(primary_recipients_env)
 
    bcc_recipients_env = os.getenv("BCC_RECIPIENTS", "")
    bcc_addresses = _normalize_recipients(bcc_recipients_env)
 
    print("Email Recipients:")
    print(f"   TO: {', '.join(to_addresses) if to_addresses else 'None'}")
    print(f"   CC: {', '.join(cc_addresses) if cc_addresses else 'None'}")
    print(f"   BCC: {', '.join(bcc_addresses) if bcc_addresses else 'None'}")
 
    if not to_addresses:
        raise ValueError("SMTP email requires at least one primary recipient (PRIMARY_RECIPIENT).")
 
    message = EmailMessage()
    message["Subject"] = "IDC_Family_Safety Windows Regression AI Agent Report"
    message["From"] = SMTP_FROM_ADDRESS
    message["To"] = ", ".join(to_addresses)
    if cc_addresses:
        message["Cc"] = ", ".join(cc_addresses)
    message.set_content("Please view this email in HTML-capable client.")
    message.add_alternative(html_content, subtype="html")
 
    all_recipients = to_addresses + cc_addresses + bcc_addresses
 
    context = ssl.create_default_context()
    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
        server.starttls(context=context)
        server.login(SMTP_USERNAME, SMTP_PASSWORD)
        server.send_message(message, to_addrs=all_recipients or None)
 
    print("Email sent successfully via SMTP!")
 
 
 
 