"""
Email Notification Service for scheduled jobs and auth failures
"""

import logging
from typing import Optional
import os

log = logging.getLogger(__name__)

PROACTIVE_OUTREACH_SUBJECT = "Quick check-in from FoundryOps"
PROACTIVE_OUTREACH_TEMPLATE = """{greeting}

I noticed the FoundryOps add-on may have run into an issue while
you were working earlier today.

If you're blocked or need help, just reply to this email or hit
the SOS button in the add-on — I'd be happy to take a look.

If everything's working fine, no action needed!

— Mike
"""


async def send_proactive_outreach_email(
    user_email: str, first_name: Optional[str] = None
) -> Optional[str]:
    """
    Send a non-intrusive proactive outreach email.

    Returns:
        Resend email ID when available, else None.
    """
    greeting = f"Hi {first_name}," if first_name else "Hi,"
    body = PROACTIVE_OUTREACH_TEMPLATE.format(greeting=greeting)

    email_provider = os.getenv("EMAIL_PROVIDER", "").lower()
    if email_provider == "resend":
        return await _send_via_resend_with_id(
            user_email,
            PROACTIVE_OUTREACH_SUBJECT,
            body,
            tags=[{"name": "message_type", "value": "support_proactive"}],
        )

    await _send_email(user_email, PROACTIVE_OUTREACH_SUBJECT, body)
    return None


async def send_auth_failure_notification(
    user_email: str,
    integration_provider: str,
    account_id: str,
    failure_reason: Optional[str] = None,
) -> bool:
    """
    Send email notification when integration credentials expire or fail.

    Args:
        user_email: User's email address
        integration_provider: Name of integration (e.g., "Salesforce")
        account_id: Account ID for logging
        failure_reason: Optional reason for failure

    Returns:
        True if email sent successfully, False otherwise
    """
    try:
        subject = f"{integration_provider} Connection Expired - Action Required"

        provider = (integration_provider or "").strip().lower()
        if provider.startswith("salesforce"):
            steps = [
                "1. Open your Google Sheet",
                "2. Go to Extensions -> FoundryMatch -> Salesforce -> Connection Status",
                '3. Click "Reconnect" to re-authorize',
            ]
        else:
            steps = [
                "1. Open your Google Sheet",
                "2. Go to Extensions -> FoundryMatch -> Schedule Manager",
                '3. Click "Connect Google" to re-authorize',
            ]

        body_lines = [
            "Hello,",
            "",
            f"Your {integration_provider} connection has expired and scheduled automations have been paused.",
            "",
            f"Reason: {failure_reason}" if failure_reason else "",
            "",
            "To resume your scheduled reports and data syncs:",
            "",
            *steps,
            "",
            "Your schedules will automatically resume once reconnected.",
            "",
            "---",
            "FoundryMatch Team",
            "https://foundrymatch.com",
            "",
            "(This is an automated notification)",
        ]
        body = "\n".join(line for line in body_lines if line)

        # Send email via configured provider
        await _send_email(user_email, subject, body)

        log.info(
            f"Sent auth failure notification to {user_email} for {integration_provider}"
        )
        return True

    except Exception as e:
        log.error(f"Failed to send auth failure notification: {e}")
        return False


async def send_schedule_paused_notification(
    user_email: str,
    schedule_name: str,
    job_id: str,
    error_message: str,
    account_id: str,
) -> bool:
    """
    Send email when a scheduled job is paused due to errors.
    """
    try:
        subject = f"Scheduled Job Paused: {schedule_name}"

        body_lines = [
            "Hello,",
            "",
            f'Your scheduled job "{schedule_name}" has been automatically paused after multiple failures.',
            "",
            f"Error: {error_message}",
            "",
            "To fix this:",
            "",
            "1. Open your Google Sheet",
            "2. Go to Extensions -> FoundryMatch -> Schedule Manager",
            "3. Review the job settings and error details",
            "4. Fix any issues (expired credentials, invalid queries, etc.)",
            '5. Click "Resume" to restart the schedule',
            "",
            f"Job ID: {job_id}",
            "",
            "---",
            "FoundryMatch Team",
            "https://foundrymatch.com",
        ]
        body = "\n".join(line for line in body_lines if line)

        await _send_email(user_email, subject, body)

        log.info(f"Sent schedule paused notification to {user_email} for job {job_id}")
        return True

    except Exception as e:
        log.error(f"Failed to send schedule paused notification: {e}")
        return False


async def send_sheet_webhook_failure_notification(
    user_email: str,
    webhook_name: str,
    sheet_name: str,
    error_message: str,
    account_id: str,
) -> bool:
    """
    Send email when a sheet webhook is failing after ingest accepted the request.
    """
    try:
        subject = f"Webhook Needs Attention: {webhook_name}"

        body_lines = [
            "Hello,",
            "",
            f'Your sheet webhook "{webhook_name}" is currently failing to write into "{sheet_name}".',
            "",
            f"Latest error: {error_message}",
            "",
            "To fix this:",
            "",
            "1. Open your Google Sheet",
            "2. Go to Extensions -> FoundryMatch -> Webhook Manager",
            "3. Review the failing webhook and reconnect Google or fix the target sheet",
            '4. Use the "History" panel to replay failed deliveries after the issue is fixed',
            "",
            f"Account ID: {account_id}",
            "",
            "---",
            "FoundryMatch Team",
            "https://foundryops.io",
        ]
        body = "\n".join(line for line in body_lines if line)

        await _send_email(user_email, subject, body)

        log.info(
            "Sent sheet webhook failure notification to %s for webhook %s",
            user_email,
            webhook_name,
        )
        return True

    except Exception as e:
        log.error(f"Failed to send sheet webhook failure notification: {e}")
        return False


async def send_enrichment_complete_notification(
    user_email: str,
    job_name: str,
    job_id: str,
    total_contacts: int,
    enriched_count: int,
    not_found_count: int,
    error_count: int,
    spreadsheet_url: Optional[str] = None,
    record_label: str = "contacts",
) -> bool:
    """
    Send branded HTML email notification when enrichment completes.
    """
    try:
        success_rate = (enriched_count / total_contacts * 100) if total_contacts > 0 else 0
        label = (record_label or "contacts").strip() or "contacts"
        label_title = label.capitalize()
        subject = f"✅ Enrichment Complete: {enriched_count}/{total_contacts} {label} enriched"
        error_color = "#ef4444" if error_count > 0 else "#6b7280"

        cta_html = ""
        if spreadsheet_url:
            cta_html = f"""
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center">
                    <a href="{spreadsheet_url}" style="display: inline-block; background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 15px;">
                      View Results in Google Sheets →
                    </a>
                  </td>
                </tr>
              </table>
            """

        text_body_lines = [
            "Hello,",
            "",
            f"Your {job_name} job has finished processing.",
            "",
            f"Total Rows: {total_contacts}",
            f"Enriched: {enriched_count}",
            f"Not Found: {not_found_count}",
            f"Errors: {error_count}",
            "",
            f"Job ID: {job_id}",
            "",
            "FoundryMatch Team",
        ]
        text_body = "\n".join(text_body_lines)

        html_body = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #f4f4f5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f5; padding: 40px 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
          
          <tr>
            <td style="background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%); padding: 32px 40px; text-align: center;">
              <div style="width: 48px; height: 48px; line-height: 48px; border-radius: 12px; background: #111827; color: #f97316; font-weight: 700; font-size: 18px; display: inline-block; text-align: center; margin-bottom: 12px;">FM</div>
              <h1 style="color: #f97316; font-size: 24px; font-weight: 700; margin: 0;">FoundryMatch</h1>
            </td>
          </tr>
          
          <tr>
            <td style="background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); padding: 24px 40px; text-align: center;">
              <span style="font-size: 32px;">✅</span>
              <h2 style="color: #ffffff; font-size: 20px; font-weight: 600; margin: 8px 0 0 0;">Enrichment Complete</h2>
            </td>
          </tr>
          
          <tr>
            <td style="padding: 40px;">
              <p style="color: #374151; font-size: 16px; line-height: 1.6; margin: 0 0 24px 0;">
                Your {job_name} job has finished processing. Here's a summary of the results:
              </p>
              
              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 24px;">
                <tr>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 8px 0 0 8px; text-align: center; border-right: 1px solid #e5e7eb;">
                    <div style="font-size: 28px; font-weight: 700; color: #22c55e;">{enriched_count:,}</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Enriched</div>
                  </td>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 0 8px 8px 0; text-align: center;">
                    <div style="font-size: 28px; font-weight: 700; color: #f97316;">{success_rate:.0f}%</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Success Rate</div>
                  </td>
                </tr>
              </table>
              
              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 32px;">
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Total {label_title}</span>
                    <span style="float: right; font-weight: 600; color: #111827;">{total_contacts:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Successfully Enriched</span>
                    <span style="float: right; font-weight: 600; color: #22c55e;">{enriched_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Not Found</span>
                    <span style="float: right; font-weight: 600; color: #6b7280;">{not_found_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0;">
                    <span style="color: #374151;">Errors</span>
                    <span style="float: right; font-weight: 600; color: {error_color};">{error_count:,}</span>
                  </td>
                </tr>
              </table>
              
              {cta_html}
              
            </td>
          </tr>
          
          <tr>
            <td style="background: #f9fafb; padding: 24px 40px; text-align: center; border-top: 1px solid #e5e7eb;">
              <p style="color: #6b7280; font-size: 13px; margin: 0 0 8px 0;">
                Job ID: {job_id}
              </p>
              <p style="color: #9ca3af; font-size: 12px; margin: 0;">
                <a href="https://foundryops.io" style="color: #f97316; text-decoration: none;">FoundryMatch</a> by FoundryOps
              </p>
            </td>
          </tr>
          
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
"""

        text_body = f"""
Your {job_name} job has completed.

Results Summary:
? Total {label}: {total_contacts:,}
? Enriched: {enriched_count:,} ({success_rate:.1f}%)
? Not found: {not_found_count:,}
? Errors: {error_count:,}

{f"View your results: {spreadsheet_url}" if spreadsheet_url else ""}

Job ID: {job_id}

---
FoundryMatch by FoundryOps
https://foundryops.io
"""

        await _send_email(user_email, subject, text_body, html_body=html_body)

        log.info(
            f"Sent enrichment complete notification to {user_email} for job {job_id}"
        )
        return True

    except Exception as e:
        log.error(f"Failed to send enrichment complete notification: {e}")
        return False


async def send_scraper_complete_notification(
    user_email: str,
    job_name: str,
    job_id: str,
    total_rows: int,
    scraped_count: int,
    skipped_count: int,
    error_count: int,
    spreadsheet_url: Optional[str] = None,
) -> bool:
    """
    Send branded HTML email notification when a scraper job completes.
    """
    try:
        success_rate = (scraped_count / total_rows * 100) if total_rows > 0 else 0
        subject = f"✅ Scraper Complete: {scraped_count}/{total_rows} rows scraped"
        error_color = "#ef4444" if error_count > 0 else "#6b7280"

        cta_html = ""
        if spreadsheet_url:
            cta_html = f"""
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center">
                    <a href="{spreadsheet_url}" style="display: inline-block; background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 15px;">
                      View Results in Google Sheets →
                    </a>
                  </td>
                </tr>
              </table>
            """

        html_body = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #f4f4f5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f5; padding: 40px 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
          
          <tr>
            <td style="background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%); padding: 32px 40px; text-align: center;">
              <div style="width: 48px; height: 48px; line-height: 48px; border-radius: 12px; background: #111827; color: #f97316; font-weight: 700; font-size: 18px; display: inline-block; text-align: center; margin-bottom: 12px;">FM</div>
              <h1 style="color: #f97316; font-size: 24px; font-weight: 700; margin: 0;">FoundryMatch</h1>
            </td>
          </tr>
          
          <tr>
            <td style="background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); padding: 24px 40px; text-align: center;">
              <span style="font-size: 32px;">✅</span>
              <h2 style="color: #ffffff; font-size: 20px; font-weight: 600; margin: 8px 0 0 0;">Scraper Complete</h2>
            </td>
          </tr>
          
          <tr>
            <td style="padding: 40px;">
              <p style="color: #374151; font-size: 16px; line-height: 1.6; margin: 0 0 24px 0;">
                Your {job_name} job has finished processing. Here's a summary of the results:
              </p>
              
              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 24px;">
                <tr>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 8px 0 0 8px; text-align: center; border-right: 1px solid #e5e7eb;">
                    <div style="font-size: 28px; font-weight: 700; color: #22c55e;">{scraped_count:,}</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Scraped</div>
                  </td>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 0 8px 8px 0; text-align: center;">
                    <div style="font-size: 28px; font-weight: 700; color: #f97316;">{success_rate:.0f}%</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Success Rate</div>
                  </td>
                </tr>
              </table>
              
              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 32px;">
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Total Rows</span>
                    <span style="float: right; font-weight: 600; color: #111827;">{total_rows:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Scraped</span>
                    <span style="float: right; font-weight: 600; color: #22c55e;">{scraped_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Skipped</span>
                    <span style="float: right; font-weight: 600; color: #6b7280;">{skipped_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0;">
                    <span style="color: #374151;">Errors</span>
                    <span style="float: right; font-weight: 600; color: {error_color};">{error_count:,}</span>
                  </td>
                </tr>
              </table>

              {cta_html}
              
              <p style="color: #9ca3af; font-size: 12px; margin: 32px 0 0 0; text-align: center;">
                Job ID: {job_id}
              </p>
            </td>
          </tr>
          
          <tr>
            <td style="background: #f9fafb; padding: 24px 40px; text-align: center; border-top: 1px solid #e5e7eb;">
              <p style="color: #6b7280; font-size: 12px; margin: 0;">
                FoundryMatch by FoundryOps • <a href="https://foundryops.io" style="color: #f97316; text-decoration: none;">foundryops.io</a>
              </p>
            </td>
          </tr>
          
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
"""

        text_body = f"""
Your {job_name} job has completed.

Results Summary:
- Total rows: {total_rows:,}
- Scraped: {scraped_count:,} ({success_rate:.1f}%)
- Skipped: {skipped_count:,}
- Errors: {error_count:,}

{f"View your results: {spreadsheet_url}" if spreadsheet_url else ""}

Job ID: {job_id}

---
FoundryMatch by FoundryOps
https://foundryops.io
"""

        await _send_email(user_email, subject, text_body, html_body=html_body)

        log.info(
            f"Sent scraper complete notification to {user_email} for job {job_id}"
        )
        return True

    except Exception as e:
        log.error(f"Failed to send scraper complete notification: {e}")
        return False


async def send_justcall_complete_notification(
    user_email: str,
    job_name: str,
    job_id: str,
    total_rows: int,
    enrolled_count: int,
    failed_count: int,
    skipped_count: int,
    spreadsheet_url: Optional[str] = None,
) -> bool:
    """
    Send branded HTML email notification when a JustCall autodialer push completes.
    """
    try:
        success_rate = (enrolled_count / total_rows * 100) if total_rows > 0 else 0
        subject = f"Autodialer Push Complete: {enrolled_count}/{total_rows} contacts enrolled"
        error_color = "#ef4444" if failed_count > 0 else "#6b7280"

        cta_html = ""
        if spreadsheet_url:
            cta_html = f"""
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center">
                    <a href="{spreadsheet_url}" style="display: inline-block; background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 15px;">
                      View Results in Google Sheets
                    </a>
                  </td>
                </tr>
              </table>
            """

        text_body = "\n".join(
            [
                "Hello,",
                "",
                f"Your {job_name} job has finished processing.",
                "",
                f"Total Rows: {total_rows}",
                f"Enrolled: {enrolled_count}",
                f"Skipped: {skipped_count}",
                f"Failed: {failed_count}",
                "",
                f"Job ID: {job_id}",
                "",
                "FoundryMatch Team",
            ]
        )

        html_body = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #f4f4f5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f5; padding: 40px 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">

          <tr>
            <td style="background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%); padding: 32px 40px; text-align: center;">
              <div style="width: 48px; height: 48px; line-height: 48px; border-radius: 12px; background: #111827; color: #f97316; font-weight: 700; font-size: 18px; display: inline-block; text-align: center; margin-bottom: 12px;">FM</div>
              <h1 style="color: #f97316; font-size: 24px; font-weight: 700; margin: 0;">FoundryMatch</h1>
            </td>
          </tr>

          <tr>
            <td style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); padding: 24px 40px; text-align: center;">
              <span style="font-size: 32px;">OK</span>
              <h2 style="color: #ffffff; font-size: 20px; font-weight: 600; margin: 8px 0 0 0;">Autodialer Push Complete</h2>
            </td>
          </tr>

          <tr>
            <td style="padding: 40px;">
              <p style="color: #374151; font-size: 16px; line-height: 1.6; margin: 0 0 24px 0;">
                Your {job_name} job has finished processing. Here's a summary of the results:
              </p>

              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 24px;">
                <tr>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 8px 0 0 8px; text-align: center; border-right: 1px solid #e5e7eb;">
                    <div style="font-size: 28px; font-weight: 700; color: #22c55e;">{enrolled_count:,}</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Enrolled</div>
                  </td>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 0 8px 8px 0; text-align: center;">
                    <div style="font-size: 28px; font-weight: 700; color: #f97316;">{success_rate:.0f}%</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Success Rate</div>
                  </td>
                </tr>
              </table>

              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 32px;">
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Total Rows</span>
                    <span style="float: right; font-weight: 600; color: #111827;">{total_rows:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Enrolled</span>
                    <span style="float: right; font-weight: 600; color: #22c55e;">{enrolled_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Skipped</span>
                    <span style="float: right; font-weight: 600; color: #6b7280;">{skipped_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0;">
                    <span style="color: #374151;">Failed</span>
                    <span style="float: right; font-weight: 600; color: {error_color};">{failed_count:,}</span>
                  </td>
                </tr>
              </table>

              {cta_html}
            </td>
          </tr>

          <tr>
            <td style="background: #f9fafb; padding: 20px 40px; text-align: center; color: #9ca3af; font-size: 12px;">
              Job ID: {job_id}
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
"""

        await _send_email(user_email, subject, text_body, html_body=html_body)

        log.info(
            f"Sent JustCall completion notification to {user_email} for job {job_id}"
        )
        return True

    except Exception as e:
        log.error(f"Failed to send JustCall completion notification: {e}")
        return False


async def send_heyreach_complete_notification(
    user_email: str,
    job_name: str,
    job_id: str,
    total_rows: int,
    enrolled_count: int,
    failed_count: int,
    skipped_count: int,
    duplicate_count: int = 0,
    invalid_count: int = 0,
    spreadsheet_url: Optional[str] = None,
) -> bool:
    """
    Send branded HTML email notification when a HeyReach LinkedIn push completes.
    """
    try:
        success_rate = (enrolled_count / total_rows * 100) if total_rows > 0 else 0
        subject = f"LinkedIn Push Complete: {enrolled_count}/{total_rows} contacts enrolled"
        error_color = "#ef4444" if failed_count > 0 else "#6b7280"

        cta_html = ""
        if spreadsheet_url:
            cta_html = f"""
              <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center">
                    <a href="{spreadsheet_url}" style="display: inline-block; background: linear-gradient(135deg, #f97316 0%, #ea580c 100%); color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 15px;">
                      View Results in Google Sheets
                    </a>
                  </td>
                </tr>
              </table>
            """

        html_body = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #f4f4f5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f5; padding: 40px 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="background-color: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">

          <tr>
            <td style="background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%); padding: 32px 40px; text-align: center;">
              <div style="width: 48px; height: 48px; line-height: 48px; border-radius: 12px; background: #111827; color: #f97316; font-weight: 700; font-size: 18px; display: inline-block; text-align: center; margin-bottom: 12px;">FM</div>
              <h1 style="color: #f97316; font-size: 24px; font-weight: 700; margin: 0;">FoundryMatch</h1>
            </td>
          </tr>

          <tr>
            <td style="background: linear-gradient(135deg, #0077b5 0%, #005582 100%); padding: 24px 40px; text-align: center;">
              <span style="font-size: 32px;">in</span>
              <h2 style="color: #ffffff; font-size: 20px; font-weight: 600; margin: 8px 0 0 0;">LinkedIn Push Complete</h2>
            </td>
          </tr>

          <tr>
            <td style="padding: 40px;">
              <p style="color: #374151; font-size: 16px; line-height: 1.6; margin: 0 0 24px 0;">
                Your {job_name} job has finished processing. Here's a summary of the results:
              </p>

              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 24px;">
                <tr>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 8px 0 0 8px; text-align: center; border-right: 1px solid #e5e7eb;">
                    <div style="font-size: 28px; font-weight: 700; color: #22c55e;">{enrolled_count:,}</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Enrolled</div>
                  </td>
                  <td width="50%" style="padding: 16px; background: #f9fafb; border-radius: 0 8px 8px 0; text-align: center;">
                    <div style="font-size: 28px; font-weight: 700; color: #f97316;">{success_rate:.0f}%</div>
                    <div style="font-size: 13px; color: #6b7280; margin-top: 4px;">Success Rate</div>
                  </td>
                </tr>
              </table>

              <table width="100%" cellpadding="0" cellspacing="0" style="margin-bottom: 32px;">
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Total Rows</span>
                    <span style="float: right; font-weight: 600; color: #111827;">{total_rows:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Enrolled</span>
                    <span style="float: right; font-weight: 600; color: #22c55e;">{enrolled_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Skipped</span>
                    <span style="float: right; font-weight: 600; color: #6b7280;">{skipped_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Duplicate</span>
                    <span style="float: right; font-weight: 600; color: #6b7280;">{duplicate_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e7eb;">
                    <span style="color: #374151;">Invalid</span>
                    <span style="float: right; font-weight: 600; color: #6b7280;">{invalid_count:,}</span>
                  </td>
                </tr>
                <tr>
                  <td style="padding: 12px 0;">
                    <span style="color: #374151;">Failed</span>
                    <span style="float: right; font-weight: 600; color: {error_color};">{failed_count:,}</span>
                  </td>
                </tr>
              </table>

              {cta_html}
            </td>
          </tr>

          <tr>
            <td style="background: #f9fafb; padding: 20px 40px; text-align: center; color: #9ca3af; font-size: 12px;">
              Job ID: {job_id}
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
"""

        text_body = f"""
Your {job_name} job has completed.

Results Summary:
- Total rows: {total_rows:,}
- Enrolled: {enrolled_count:,} ({success_rate:.1f}%)
- Skipped: {skipped_count:,}
- Duplicate: {duplicate_count:,}
- Invalid: {invalid_count:,}
- Failed: {failed_count:,}

{f"View your results: {spreadsheet_url}" if spreadsheet_url else ""}

Job ID: {job_id}

---
FoundryMatch by FoundryOps
https://foundryops.io
"""

        await _send_email(user_email, subject, text_body, html_body=html_body)

        log.info(
            f"Sent HeyReach completion notification to {user_email} for job {job_id}"
        )
        return True

    except Exception as e:
        log.error(f"Failed to send HeyReach completion notification: {e}")
        return False


async def _send_email(
    to: str,
    subject: str,
    body: str,
    html_body: Optional[str] = None,
) -> None:
    """
    Send email via configured provider (Resend, SendGrid, SES, SMTP)
    """
    # Check which email provider is configured
    email_provider = os.getenv("EMAIL_PROVIDER", "").lower()

    if email_provider == "resend":
        await _send_via_resend(to, subject, body, html_body=html_body)
    elif email_provider == "sendgrid":
        await _send_via_sendgrid(to, subject, body)
    elif email_provider == "ses":
        await _send_via_ses(to, subject, body)
    elif email_provider == "smtp":
        await _send_via_smtp(to, subject, body)
    else:
        # Log to console for now (dev mode)
        log.warning(
            f"Email provider not configured. Email content:\nTo: {to}\nSubject: {subject}\n{body}"
        )


async def _send_via_resend_with_id(
    to: str,
    subject: str,
    body: str,
    html_body: Optional[str] = None,
    tags: Optional[list[dict]] = None,
) -> Optional[str]:
    """Send email via Resend and return the email ID when available."""
    try:
        import httpx

        api_key = os.getenv("RESEND_API_KEY")
        from_email = os.getenv("RESEND_FROM_EMAIL", "notifications@foundryops.io")

        if not api_key:
            log.warning("Resend API key not configured (RESEND_API_KEY)")
            return None

        email_payload: dict[str, object] = {
            "from": f"FoundryOps <{from_email}>",
            "to": [to],
            "subject": subject,
            "text": body,
        }
        if html_body:
            email_payload["html"] = html_body
        if tags:
            email_payload["tags"] = tags

        async with httpx.AsyncClient() as client:
            response = await client.post(
                "https://api.resend.com/emails",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
                json=email_payload,
                timeout=20,
            )
            if response.status_code >= 300:
                log.warning(
                    "Resend send failed (%s): %s",
                    response.status_code,
                    response.text,
                )
                return None
            data = response.json()
            return data.get("id") if isinstance(data, dict) else None
    except Exception as exc:
        log.error("Resend send failed: %s", exc)
        return None


async def _send_via_resend(
    to: str,
    subject: str,
    body: str,
    html_body: Optional[str] = None,
) -> None:
    """Send email via Resend (https://resend.com)"""
    try:
        import httpx

        api_key = os.getenv("RESEND_API_KEY")
        from_email = os.getenv("RESEND_FROM_EMAIL", "notifications@foundryops.io")

        if not api_key:
            log.warning("Resend API key not configured (RESEND_API_KEY)")
            return

        email_payload = {
            "from": f"FoundryOps <{from_email}>",
            "to": [to],
            "subject": subject,
            "text": body,
        }
        if html_body:
            email_payload["html"] = html_body

        async with httpx.AsyncClient() as client:
            response = await client.post(
                "https://api.resend.com/emails",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
                json=email_payload,
                timeout=10.0,
            )

            if response.status_code not in (200, 201):
                log.error(f"Resend error: {response.status_code} - {response.text}")
                raise Exception(f"Resend failed: {response.status_code}")

            result = response.json()
            log.info(f"Resend email sent: {result.get('id')}")

    except Exception as e:
        log.error(f"Resend send failed: {e}")
        raise


async def _send_via_sendgrid(to: str, subject: str, body: str) -> None:
    """Send email via SendGrid"""
    try:
        import httpx
        from ... import settings

        api_key = os.getenv("SENDGRID_API_KEY") or settings.SENDGRID_API_KEY
        from_email = os.getenv("SENDGRID_FROM_EMAIL", "notifications@foundrymatch.com")

        if not api_key:
            log.warning("SendGrid API key not configured")
            return

        async with httpx.AsyncClient() as client:
            response = await client.post(
                "https://api.sendgrid.com/v3/mail/send",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "personalizations": [{"to": [{"email": to}]}],
                    "from": {"email": from_email, "name": "FoundryOps"},
                    "subject": subject,
                    "content": [{"type": "text/plain", "value": body}],
                },
                timeout=10.0,
            )

            if response.status_code not in (200, 202):
                log.error(f"SendGrid error: {response.status_code} - {response.text}")
                raise Exception(f"SendGrid failed: {response.status_code}")

    except Exception as e:
        log.error(f"SendGrid send failed: {e}")
        raise


async def _send_via_ses(to: str, subject: str, body: str) -> None:
    """Send email via AWS SES"""
    try:
        import boto3

        from_email = os.getenv("SES_FROM_EMAIL", "notifications@foundrymatch.com")
        region = os.getenv("AWS_REGION", "us-east-1")

        ses_client = boto3.client("ses", region_name=region)

        response = ses_client.send_email(
            Source=from_email,
            Destination={"ToAddresses": [to]},
            Message={"Subject": {"Data": subject}, "Body": {"Text": {"Data": body}}},
        )

        log.info(f"SES email sent: {response['MessageId']}")

    except Exception as e:
        log.error(f"SES send failed: {e}")
        raise


async def _send_via_smtp(to: str, subject: str, body: str) -> None:
    """Send email via SMTP"""
    try:
        import smtplib
        from email.mime.text import MIMEText
        from email.mime.multipart import MIMEMultipart

        smtp_host = os.getenv("SMTP_HOST", "smtp.gmail.com")
        smtp_port = int(os.getenv("SMTP_PORT", "587"))
        smtp_user = os.getenv("SMTP_USER")
        smtp_password = os.getenv("SMTP_PASSWORD")
        from_email = os.getenv("SMTP_FROM_EMAIL", smtp_user)

        if not smtp_user or not smtp_password:
            log.warning("SMTP credentials not configured")
            return

        msg = MIMEMultipart()
        msg["From"] = from_email
        msg["To"] = to
        msg["Subject"] = subject
        msg.attach(MIMEText(body, "plain"))

        with smtplib.SMTP(smtp_host, smtp_port) as server:
            server.starttls()
            server.login(smtp_user, smtp_password)
            server.send_message(msg)

        log.info(f"SMTP email sent to {to}")

    except Exception as e:
        log.error(f"SMTP send failed: {e}")
        raise
