import logging

import httpx

from app.core.config import settings

logger = logging.getLogger("yeneb.sms")

_API_URL = "https://smsethiopia.et/api/sms/send"


def send_sms(phone: str, message: str) -> None:
    """Send an SMS message via the mySMSEthiopia API.

    Every OTP send in this codebase goes through this one function.
    Only makes a real API call when sms_ethiopia_api_key is configured
    — otherwise (local dev, tests) this just logs, so the test suite
    (which triggers an OTP send on nearly every auth/admin/branch
    request) never touches the network.

    The full message (which usually contains the OTP code itself) is
    only ever logged in development — logging it in a real deployment
    would defeat the point of the code being one-time-use-and-secret.
    Outside development, only the fact that a send happened is logged.
    See app.api.v1.endpoints.auth's debug_otp field for the equivalent
    development-only exposure on the API response side.

    `phone` is expected in E.164 (+2519...); msisdn per the API docs
    is digits only, no leading +.
    """
    if settings.environment == "development":
        logger.info("SMS to %s: %s", phone, message)
    else:
        logger.info("SMS to %s", phone)
    if not settings.sms_ethiopia_api_key:
        return

    response = httpx.post(
        _API_URL,
        headers={
            "KEY": settings.sms_ethiopia_api_key,
            "Content-Type": "application/json",
        },
        json={"msisdn": phone.lstrip("+"), "text": message},
        timeout=10.0,
    )
    response.raise_for_status()
