File size: 9,638 Bytes
c024705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923dca5
c024705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""
SMS Service for AIMHSA
Integrates with HDEV SMS Gateway for sending notifications
"""

import requests
import json
import time
from typing import Dict, Optional, Tuple
import logging

class HDevSMSService:
    def __init__(self, api_id: str, api_key: str):
        """
        Initialize HDEV SMS Service
        
        Args:
            api_id: HDEV API ID
            api_key: HDEV API Key
        """
        self.api_id = api_id
        self.api_key = api_key
        self.base_url = "https://sms-api.hdev.rw/v1/api"
        self.logger = logging.getLogger(__name__)
    
    def send_sms(self, sender_id: str, phone_number: str, message: str, link: str = '') -> Dict:
        """
        Send SMS message
        
        Args:
            sender_id: Sender identifier (max 11 characters)
            phone_number: Recipient phone number (Rwanda format: +250XXXXXXXXX)
            message: SMS message content
            link: Optional link to include
            
        Returns:
            Dict with response status and details
        """
        try:
            # Format phone number for Rwanda
            formatted_phone = self._format_phone_number(phone_number)
            
            # Prepare request data
            data = {
                'ref': 'sms',
                'sender_id': 'N-SMS',  # Use N-SMS as sender ID
                'tel': formatted_phone,
                'message': message,
                'link': link
            }
            
            # Make API request
            url = f"{self.base_url}/{self.api_id}/{self.api_key}"
            response = requests.post(url, data=data, timeout=30)
            
            if response.status_code == 200:
                result = response.json()
                self.logger.info(f"SMS sent successfully to {formatted_phone}: {result}")
                return {
                    'success': True,
                    'response': result,
                    'phone': formatted_phone
                }
            else:
                self.logger.error(f"SMS API error: {response.status_code} - {response.text}")
                return {
                    'success': False,
                    'error': f"API Error: {response.status_code}",
                    'phone': formatted_phone
                }
                
        except requests.exceptions.RequestException as e:
            self.logger.error(f"SMS request failed: {str(e)}")
            return {
                'success': False,
                'error': f"Request failed: {str(e)}",
                'phone': phone_number
            }
        except Exception as e:
            self.logger.error(f"SMS service error: {str(e)}")
            return {
                'success': False,
                'error': f"Service error: {str(e)}",
                'phone': phone_number
            }
    
    def send_booking_notification(self, user_data: Dict, professional_data: Dict, booking_data: Dict) -> Dict:
        """
        Send booking notification SMS to user
        
        Args:
            user_data: User information (name, phone, etc.)
            professional_data: Professional information
            booking_data: Booking details
            
        Returns:
            Dict with SMS sending result
        """
        try:
            # Format user name
            user_name = user_data.get('fullname', user_data.get('username', 'User'))
            
            # Format professional name
            prof_name = f"{professional_data.get('first_name', '')} {professional_data.get('last_name', '')}".strip()
            prof_specialization = professional_data.get('specialization', 'Mental Health Professional')
            
            # Format scheduled time
            scheduled_time = self._format_datetime(booking_data.get('scheduled_time', 0))
            
            # Create message based on risk level
            risk_level = booking_data.get('risk_level', 'medium')
            session_type = booking_data.get('session_type', 'consultation')
            
            if risk_level == 'critical':
                urgency_text = "URGENT: Emergency mental health support has been arranged"
            elif risk_level == 'high':
                urgency_text = "URGENT: Professional mental health support has been scheduled"
            else:
                urgency_text = "Professional mental health support has been scheduled"
            
            # Build SMS message
            message = f"""AIMHSA Mental Health Support

{urgency_text}

Professional: {prof_name}
Specialization: {prof_specialization}
Scheduled: {scheduled_time}
Session Type: {session_type.title()}

You will be contacted shortly. If this is an emergency, call 112 or the Mental Health Hotline at 105.

Stay safe and take care.
AIMHSA Team"""
            
            # Send SMS
            return self.send_sms(
                sender_id="N-SMS",
                phone_number=user_data.get('telephone', ''),
                message=message
            )
            
        except Exception as e:
            self.logger.error(f"Failed to send booking notification: {str(e)}")
            return {
                'success': False,
                'error': f"Notification failed: {str(e)}"
            }
    
    def send_professional_notification(self, professional_data: Dict, user_data: Dict, booking_data: Dict) -> Dict:
        """
        Send notification SMS to professional about new booking
        
        Args:
            professional_data: Professional information
            user_data: User information
            booking_data: Booking details
            
        Returns:
            Dict with SMS sending result
        """
        try:
            # Format names
            prof_name = f"{professional_data.get('first_name', '')} {professional_data.get('last_name', '')}".strip()
            user_name = user_data.get('fullname', user_data.get('username', 'User'))
            
            # Format scheduled time
            scheduled_time = self._format_datetime(booking_data.get('scheduled_time', 0))
            
            # Build message with comprehensive user information
            risk_level = booking_data.get('risk_level', 'medium')
            booking_id = booking_data.get('booking_id', 'N/A')
            
            # Get user contact information
            user_phone = user_data.get('telephone', 'Not provided')
            user_email = user_data.get('email', 'Not provided')
            user_location = f"{user_data.get('district', 'Unknown')}, {user_data.get('province', 'Unknown')}"
            
            message = f"""AIMHSA Professional Alert

New {risk_level.upper()} risk booking assigned to you.

Booking ID: {booking_id}
User: {user_name}
Risk Level: {risk_level.upper()}
Scheduled: {scheduled_time}

USER CONTACT INFORMATION:
Phone: {user_phone}
Email: {user_email}
Location: {user_location}

Please login to your dashboard to view details and accept/decline the booking:
https://prodevroger-ishingiro.hf.space/login

AIMHSA System"""
            
            # Send SMS to professional
            return self.send_sms(
                sender_id="N-SMS",
                phone_number=professional_data.get('phone', ''),
                message=message
            )
            
        except Exception as e:
            self.logger.error(f"Failed to send professional notification: {str(e)}")
            return {
                'success': False,
                'error': f"Professional notification failed: {str(e)}"
            }
    
    def _format_phone_number(self, phone: str) -> str:
        """
        Format phone number for Rwanda SMS
        
        Args:
            phone: Phone number in various formats
            
        Returns:
            Formatted phone number (+250XXXXXXXXX)
        """
        if not phone:
            return ""
        
        # Remove all non-digit characters
        digits = ''.join(filter(str.isdigit, phone))
        
        # Handle different formats
        if digits.startswith('250'):
            return f"+{digits}"
        elif digits.startswith('0'):
            return f"+250{digits[1:]}"
        elif len(digits) == 9:
            return f"+250{digits}"
        else:
            return f"+{digits}"
    
    def _format_datetime(self, timestamp: float) -> str:
        """
        Format timestamp to readable datetime
        
        Args:
            timestamp: Unix timestamp
            
        Returns:
            Formatted datetime string
        """
        try:
            import datetime
            dt = datetime.datetime.fromtimestamp(timestamp)
            return dt.strftime("%Y-%m-%d %H:%M")
        except:
            return "TBD"
    
    def test_connection(self) -> bool:
        """
        Test SMS service connection
        
        Returns:
            True if connection successful, False otherwise
        """
        try:
            # Send a test SMS to a dummy number
            result = self.send_sms(
                sender_id="N-SMS",
                phone_number="+250000000000",  # Dummy number
                message="Test message"
            )
            return result.get('success', False)
        except:
            return False

# Global SMS service instance
sms_service = None

def initialize_sms_service(api_id: str, api_key: str):
    """Initialize the global SMS service"""
    global sms_service
    sms_service = HDevSMSService(api_id, api_key)
    return sms_service

def get_sms_service() -> Optional[HDevSMSService]:
    """Get the global SMS service instance"""
    return sms_service