import urllib.request
import urllib.error
import json

API_KEY = "KEY019BE7A3A2D749FCA8681CFF8448A7F0_vTMM1n77CtQxLDT2ra3P1z"
BASE = "https://api.telnyx.com/v2"

# George's assistant TeXML app ID (from assistant config)
GEORGE_TEXML_APP_ID = "2900777358543816088"
NUMBER_E164 = "%2B61731304377"  # URL-encoded +61731304377

def req(method, path, body=None):
    data = json.dumps(body).encode() if body else None
    r = urllib.request.Request(
        f"{BASE}{path}",
        data=data,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        method=method
    )
    try:
        resp = urllib.request.urlopen(r, timeout=10)
        return json.loads(resp.read()), None
    except urllib.error.HTTPError as e:
        return None, f"HTTP {e.code}: {e.read().decode()}"

# Assign the number to George's TeXML app (which IS his AI assistant)
print("Assigning 4377 to George's AI assistant via TeXML app ID...")
result, err = req("PATCH", f"/phone_numbers/{NUMBER_E164}", {
    "connection_id": GEORGE_TEXML_APP_ID
})

if err:
    print(f"ERROR: {err}")
else:
    d = result.get("data", {})
    print(f"SUCCESS!")
    print(f"  Number: {d.get('phone_number')}")
    print(f"  Status: {d.get('status')}")
    print(f"  Connection ID: {d.get('connection_id')}")
    print(f"  Connection Name: {d.get('connection_name', 'N/A')}")
