import time, jwt, requests,httpx
from mama_care_api.settings import *

def generate_jwt():
    with open(APNS_AUTH_KEY_PATH, "r") as f:
        secret = f.read()

    token = jwt.encode(
        {"iss": APNS_TEAM_ID, "iat": int(time.time())},
        secret,
        algorithm="ES256", 
        headers={"alg": "ES256", "kid": APNS_KEY_ID},
    )
    return token

def send_push_notification_ios(device_token, title, body):
    token = generate_jwt()

    url = f"https://api.sandbox.push.apple.com/3/device/{device_token}"
    if not APNS_USE_SANDBOX:
        url = f"https://api.push.apple.com/3/device/{device_token}"

    headers = {
        "authorization": f"bearer {token}",
        "apns-topic": APNS_BUNDLE_ID,
        "apns-push-type": "alert",
    }

    payload = {
        "aps": {
            "alert": {"title": title, "body": body},
            "sound": "default"
        }
    }

    status = None
    text = None
    with httpx.Client(http2=True) as client:
        r = client.post(url, headers=headers, json=payload)
        status = r.status_code
        text = r.text
    
    #return status,text
