File size: 5,333 Bytes
408b7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import os
import smtplib
import socket
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from core.logger import logger

# 🎯 THE RAILWAY PRODUCTION FIX: Force IPv4 
# Prevents "Network is unreachable" errors by stopping the container 
# from attempting to route through IPv6 addresses in the cluster.
old_getaddrinfo = socket.getaddrinfo
def new_getaddrinfo(*args, **kwargs):
    res = old_getaddrinfo(*args, **kwargs)
    return [r for r in res if r[0] == socket.AF_INET]
socket.getaddrinfo = new_getaddrinfo

class EmailService:
    def __init__(self):
        self.sender = os.getenv("SENDER_EMAIL")
        self.password = os.getenv("SENDER_PASSWORD")
        self.smtp_server = os.getenv("SMTP_SERVER", "smtp.gmail.com")
        
        try:
            # Standardizing on 465 for SSL stability in Railway containers 
            self.smtp_port = int(os.getenv("SMTP_PORT", 465))
        except (TypeError, ValueError):
            self.smtp_port = 465

    def generate_risk_narrative(self, metrics: dict, locale: str):
        """Generates localized clinical insights for the regional pilot."""
        risk = metrics.get('risk_score', 0)
        
        if locale == "IN_NEP":
            if risk > 70:
                return "Significant gaps in Foundational Literacy. Remedial coaching recommended."
            elif risk > 35:
                return "Moderate decoding fatigue observed. Supplemental support advised."
            return "Foundational literacy markers within expected ranges."
        else:
            if risk > 70:
                return "Biometric markers suggest high probability of phonological processing challenges."
            elif risk > 35:
                return "Moderate ocular backtracking and decoding fatigue detected."
            return "Phonological and ocular metrics within typical development benchmarks."

    async def send_report(self, recipient_email: str, pdf_path: str, session_id: str = "N/A", metrics: dict = None, locale: str = "AU_VIC"):
        """
        🎯 CORE FIX: Primary entry point used by DyslexiaScanner.
        Maps to the internal secure dispatch logic.
        """
        # Ensure metrics is a dictionary to prevent attribute errors in narrative generation
        metrics = metrics or {}
        return await self.send_secure_report(recipient_email, [pdf_path], session_id, metrics, locale)

    async def send_secure_report(self, recipient_email, attachments, session_id, metrics, locale="AU_VIC"):
        """Dispatches encrypted reports with localized context and access keys."""
        if not recipient_email or recipient_email in ["null", "undefined", ""]:
            logger.error(f"⚠️ Aborting Email: No valid recipient for session {session_id}")
            return False

        if not self.sender or not self.password:
            logger.error("❌ CRITICAL: SMTP credentials missing from environment.")
            return False

        narrative = self.generate_risk_narrative(metrics, locale)
        is_nep = locale == "IN_NEP"
        subject_tag = "NEP 2020 Progress" if is_nep else "Clinical Screening Artifact"

        msg = MIMEMultipart()
        msg['From'] = f"LearningView Pro <{self.sender}>"
        msg['To'] = recipient_email
        msg['Subject'] = f"SECURE: {subject_tag} (Session {session_id})"

        body = f"""Hello,\n\nThe biometric synthesis for Session {session_id} is complete.\n\n--- SUMMARY ---\n{narrative}\n\nOPEN PASSWORD: {session_id}\n\nRegards,\nClinical Team"""
        msg.attach(MIMEText(body, 'plain'))

        for file_path in attachments:
            if file_path and os.path.exists(file_path):
                try:
                    with open(file_path, "rb") as f:
                        part = MIMEApplication(f.read(), Name=os.path.basename(file_path))
                    part['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"'
                    msg.attach(part)
                except Exception as e:
                    logger.error(f"⚠️ Attachment Error: {e}")

        context = ssl.create_default_context()
        try:
            # Strategy A: SSL (Port 465)
            with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, context=context, timeout=15) as server:
                server.login(self.sender, self.password)
                server.send_message(msg)
            logger.info(f"✅ SMTP Success (465): Delivered session {session_id}")
            return True
        except Exception as e:
            logger.error(f"⚠️ SMTP SSL Failed: {e}. Attempting 587 STARTTLS...")
            try:
                # Strategy B: STARTTLS Fallback (Port 587)
                with smtplib.SMTP(self.smtp_server, 587, timeout=15) as server:
                    server.starttls(context=context)
                    server.login(self.sender, self.password)
                    server.send_message(msg)
                logger.info(f"✅ SMTP Success (587): Fallback delivered for session {session_id}")
                return True
            except Exception as e2:
                logger.error(f"❌ CRITICAL SMTP FAILURE: Both protocols unreachable: {e2}")
                return False

# Singleton instance
email_service = EmailService()