import urllib.request
import urllib.error
import json

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

# AIVA's original connection - Genesis-Claude-Voice call_control_connection
# This was the original connection before we incorrectly changed it
AIVA_CONNECTION_ID = "2895419033639715995"  # Genesis-Claude-Voice
NUMBER_E164 = "%2B61731304377"

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()}"

# Revert to AIVA's original connection
print("Reverting 4377 back to AIVA's connection (Genesis-Claude-Voice)...")
result, err = req("PATCH", f"/phone_numbers/{NUMBER_E164}", {
    "connection_id": AIVA_CONNECTION_ID
})

if err:
    print(f"ERROR: {err}")
else:
    d = result.get("data", {})
    print(f"REVERTED:")
    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')}")

# Also check what assistants George's TeXML app now has (should be clean)
print("\nGeorge's assistant phone numbers (should be empty now):")
r2, e2 = req("GET", "/ai/assistants/assistant-6f6f4ca2-3155-4930-95cb-27f59514af3e")
if not e2:
    phones = r2.get("data", {}).get("phone_numbers", [])
    print(f"  {phones if phones else '(none — correct)'}")
