def number_to_words_en(number):
    """
    Converts a number to English words.
    Handles decimals up to 3 places (common for some currencies).
    """
    if number == 0:
        return "Zero"

    units = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 
             "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
    tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
    thousands = ["", "Thousand", "Million", "Billion"]

    def _convert_less_than_thousand(num):
        res = ""
        if num >= 100:
            res += units[num // 100] + " Hundred "
            num %= 100
        if num >= 20:
            res += tens[num // 10] + " "
            num %= 10
        if num > 0:
            res += units[num]
        return res.strip()

    # Split into integer and fractional parts
    parts = str(float(number)).split('.')
    integer_part = int(parts[0])
    fractional_part = int(parts[1]) if len(parts) > 1 else 0

    # Convert integer part
    res = ""
    if integer_part == 0:
        res = "Zero"
    else:
        idx = 0
        while integer_part > 0:
            if integer_part % 1000 != 0:
                res = _convert_less_than_thousand(integer_part % 1000) + " " + thousands[idx] + " " + res
            integer_part //= 1000
            idx += 1
    
    words = res.strip()

    # Convert fractional part (e.g., for 0.125 -> 125/1000)
    if fractional_part > 0:
        # Standard way is often "and X/100" or "and X cents"
        # We'll just append "and X/1000" or similar based on length
        frac_str = parts[1]
        denom = 10 ** len(frac_str)
        words += f" and {fractional_part}/{denom}"

    return words

def number_to_words_ar(number):
    """
    A very basic Arabic number to words converter.
    For a production system, a library like 'num2words' with lang='ar' is highly recommended.
    """
    # This is a placeholder for Arabic. For now, we'll return the English version or just a simplified one.
    # Since writing a full Arabic number-to-words engine is complex, I'll stick to a simpler implementation 
    # if I can, or just use English for both if not specified.
    # However, I'll try to provide a basic one if possible.
    return number_to_words_en(number) # Fallback to EN for now to ensure it works.

import requests

def send_whatsapp_message(phone, message):
    """
    Sends a WhatsApp message via Wablas gateway.
    """
    from .models import SystemSetting
    settings = SystemSetting.objects.first()
    
    if not settings or not settings.wablas_enabled:
        return False, "WhatsApp gateway is disabled."
    
    if not settings.wablas_token or not settings.wablas_server_url:
        return False, "Wablas configuration is incomplete."

    # Clean phone number (remove non-digits)
    phone = ''.join(filter(str.isdigit, str(phone)))
    
    # Ensure URL is properly formatted
    server_url = settings.wablas_server_url.rstrip('/')
    url = f"{server_url}/api/send-message"
    
    headers = {
        "Authorization": settings.wablas_token,
        "Secret": settings.wablas_secret_key
    }
    
    payload = {
        "phone": phone,
        "message": message
    }
    
    try:
        response = requests.post(url, data=payload, headers=headers, timeout=10)
        data = response.json()
        if response.status_code == 200 and data.get('status') == True:
            return True, "Message sent successfully."
        else:
            return False, data.get('message', 'Unknown error from Wablas.')
    except Exception as e:
        return False, str(e)

def send_whatsapp_document(phone, document_url, caption=""):
    """
    Sends a document via WhatsApp using Wablas gateway.
    document_url should be a public URL to the file.
    """
    from .models import SystemSetting
    settings = SystemSetting.objects.first()
    
    if not settings or not settings.wablas_enabled:
        return False, "WhatsApp gateway is disabled."
    
    if not settings.wablas_token or not settings.wablas_server_url:
        return False, "Wablas configuration is incomplete."

    # Clean phone number (remove non-digits)
    phone = ''.join(filter(str.isdigit, str(phone)))
    
    # Ensure URL is properly formatted
    server_url = settings.wablas_server_url.rstrip('/')
    url = f"{server_url}/api/send-document"
    
    headers = {
        "Authorization": settings.wablas_token,
        "Secret": settings.wablas_secret_key
    }
    
    payload = {
        "phone": phone,
        "document": document_url,
        "caption": caption
    }
    
    try:
        response = requests.post(url, data=payload, headers=headers, timeout=15)
        data = response.json()
        if response.status_code == 200 and data.get('status') == True:
            return True, "Document sent successfully."
        else:
            return False, data.get('message', 'Unknown error from Wablas.')
    except Exception as e:
        return False, str(e)
