"""
EIGIS Email Alert Service
Sends SMTP email notifications for anomalous progress detection
"""
import aiosmtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import List, Optional
import os
import logging

logger = logging.getLogger("eigis.alerts")


class EmailAlertService:
    """Async email alert service for anomalous project progress detection."""

    def __init__(self):
        self.smtp_host = os.getenv("SMTP_HOST", "smtp.gmail.com")
        self.smtp_port = int(os.getenv("SMTP_PORT", 587))
        self.smtp_username = os.getenv("SMTP_USERNAME", "eigis-alerts@gie.gov")
        self.smtp_password = os.getenv("SMTP_PASSWORD", "")
        self.from_address = os.getenv("ALERT_FROM_EMAIL", "eigis-alerts@gie.gov")
        self.use_tls = os.getenv("SMTP_USE_TLS", "true").lower() == "true"

    async def send_alert(
        self,
        to_addresses: List[str],
        subject: str,
        body_html: str,
        cc_addresses: Optional[List[str]] = None,
        priority: str = "normal",
    ) -> bool:
        """
        Send an email alert asynchronously.
        Returns True if sent successfully, False otherwise.
        """
        if not to_addresses:
            logger.warning("No recipients provided for alert")
            return False

        try:
            msg = MIMEMultipart("alternative")
            msg["From"] = self.from_address
            msg["To"] = ", ".join(to_addresses)
            msg["Subject"] = f"[EIGIS Alert] {subject}"
            if cc_addresses:
                msg["Cc"] = ", ".join(cc_addresses)
            if priority == "critical":
                msg["X-Priority"] = "1"
                msg["Importance"] = "high"
            elif priority == "emergency":
                msg["X-Priority"] = "1"
                msg["Importance"] = "high"
                msg["Subject"] = f"[EIGIS EMERGENCY] {subject}"

            msg.attach(MIMEText(body_html, "html"))

            smtp = aiosmtplib.SMTP(
                hostname=self.smtp_host,
                port=self.smtp_port,
                use_tls=self.use_tls,
            )
            await smtp.connect()
            if self.smtp_username and self.smtp_password:
                await smtp.login(self.smtp_username, self.smtp_password)
            await smtp.send_message(msg)
            await smtp.quit()

            logger.info(f"Alert sent to {to_addresses}: {subject}")
            return True

        except Exception as e:
            logger.error(f"Failed to send alert: {e}")
            return False

    async def send_hazard_alert(
        self,
        client_email: str,
        receptionist_email: str,
        project_code: str,
        site_id: str,
        hazard_level: str,
        details: str,
    ):
        """Send critical hazard level alert to client and receptionist."""
        html = f"""
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: #DC2626; color: white; padding: 20px; border-radius: 8px 8px 0 0;">
                <h1 style="margin:0; font-size: 20px;">⚠ EIGIS Critical Hazard Alert</h1>
            </div>
            <div style="background: #FEF2F2; border: 1px solid #FECACA; padding: 20px; border-radius: 0 0 8px 8px;">
                <p><strong>Project:</strong> {project_code}</p>
                <p><strong>Site ID:</strong> {site_id}</p>
                <p><strong>Hazard Level:</strong> <span style="color: #DC2626; font-weight: bold;">{hazard_level.upper()}</span></p>
                <p><strong>Details:</strong> {details}</p>
                <hr style="border: none; border-top: 1px solid #FECACA; margin: 16px 0;">
                <p style="font-size: 12px; color: #666;">
                    This alert was automatically generated by the EIGIS Engineering Geology &amp;
                    Geohazard Information System. Immediate review and action is recommended.
                </p>
            </div>
        </div>
        """
        return await self.send_alert(
            to_addresses=[client_email],
            cc_addresses=[receptionist_email] if receptionist_email else None,
            subject=f"Critical Hazard: {hazard_level.upper()} at {site_id}",
            body_html=html,
            priority="critical" if hazard_level in ("high", "very_high") else "emergency",
        )

    async def send_geothermal_anomaly_alert(
        self,
        client_email: str,
        receptionist_email: str,
        project_code: str,
        site_id: str,
        anomaly_type: str,
        anomaly_details: str,
    ):
        """Send geothermal anomaly alert."""
        html = f"""
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: #EA580C; color: white; padding: 20px; border-radius: 8px 8px 0 0;">
                <h1 style="margin:0; font-size: 20px;">🌋 EIGIS Geothermal Anomaly Alert</h1>
            </div>
            <div style="background: #FFF7ED; border: 1px solid #FED7AA; padding: 20px; border-radius: 0 0 8px 8px;">
                <p><strong>Project:</strong> {project_code}</p>
                <p><strong>Site ID:</strong> {site_id}</p>
                <p><strong>Anomaly Type:</strong> {anomaly_type}</p>
                <p><strong>Details:</strong> {anomaly_details}</p>
                <hr style="border: none; border-top: 1px solid #FED7AA; margin: 16px 0;">
                <p style="font-size: 12px; color: #666;">
                    This alert was automatically generated by the EIGIS Geothermal Monitoring System.
                    Please review the data and take appropriate action.
                </p>
            </div>
        </div>
        """
        return await self.send_alert(
            to_addresses=[client_email],
            cc_addresses=[receptionist_email] if receptionist_email else None,
            subject=f"Geothermal Anomaly: {anomaly_type} at {site_id}",
            body_html=html,
            priority="critical",
        )

    async def send_progress_delay_alert(
        self,
        client_email: str,
        receptionist_email: str,
        project_code: str,
        project_name: str,
        days_without_data: int,
    ):
        """Send project progress delay alert."""
        html = f"""
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: #CA8A04; color: white; padding: 20px; border-radius: 8px 8px 0 0;">
                <h1 style="margin:0; font-size: 20px;">📊 EIGIS Progress Delay Alert</h1>
            </div>
            <div style="background: #FEFCE8; border: 1px solid #FEF08A; padding: 20px; border-radius: 0 0 8px 8px;">
                <p><strong>Project:</strong> {project_code} — {project_name}</p>
                <p><strong>Days Without New Data:</strong> <strong>{days_without_data}</strong></p>
                <p>No new observations have been recorded for this active project in the past {days_without_data} days.
                This may indicate a field data collection gap or scheduling issue.</p>
                <hr style="border: none; border-top: 1px solid #FEF08A; margin: 16px 0;">
                <p style="font-size: 12px; color: #666;">
                    This is an automated alert from EIGIS. Please verify field trip schedules and data collection status.
                </p>
            </div>
        </div>
        """
        return await self.send_alert(
            to_addresses=[client_email],
            cc_addresses=[receptionist_email] if receptionist_email else None,
            subject=f"Progress Delay: No data for {days_without_data} days on {project_code}",
            body_html=html,
            priority="warning",
        )


# Singleton instance
email_service = EmailAlertService()
