#!/usr/bin/env python3
"""
patch_telnyx_webhook_urls.py
----------------------------
Called by bridge_watchdog.sh when the cloudflared tunnel URL changes.
Updates all 3 AIVA Telnyx webhook tool URLs to the new tunnel base URL.

Usage:
    python3 patch_telnyx_webhook_urls.py https://new-tunnel.trycloudflare.com
"""

import sys
import os
import json
import requests

def main():
    if len(sys.argv) < 2:
        print("Usage: patch_telnyx_webhook_urls.py <new_tunnel_base_url>")
        sys.exit(1)

    new_base = sys.argv[1].rstrip('/')

    # Load env (called from watchdog which sources secrets.env)
    api_key = os.environ.get('TELNYX_API_KEY', '')
    assistant_uuid = os.environ.get('TELNYX_ASSISTANT_UUID', '')  # AIVA

    if not api_key or not assistant_uuid:
        print("ERROR: TELNYX_API_KEY or TELNYX_ASSISTANT_UUID not set")
        sys.exit(1)

    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json',
    }
    base_url = 'https://api.telnyx.com/v2'

    # GET current assistant to see existing tools
    r = requests.get(f'{base_url}/ai/assistants/{assistant_uuid}', headers=headers)
    if r.status_code != 200:
        print(f"ERROR: Could not fetch assistant: {r.status_code} {r.text[:200]}")
        sys.exit(1)

    assistant = r.json().get('data', r.json())
    tools = assistant.get('tools', [])

    print(f"Current assistant version: {assistant.get('version', '?')}")
    print(f"Tools: {len(tools)}")

    # Update all webhook tool URLs that contain the bridge endpoint paths
    bridge_paths = ['/bridge/telnyx-webhook', '/bridge/telnyx-transcript']
    updated = 0

    for tool in tools:
        if tool.get('type') == 'webhook':
            webhook = tool.get('webhook', {})
            old_url = webhook.get('url', '')

            for path in bridge_paths:
                if path in old_url:
                    new_url = f"{new_base}{path}"
                    webhook['url'] = new_url
                    print(f"  Updated: {old_url} → {new_url}")
                    updated += 1
                    break

    if updated == 0:
        print("No webhook URLs needed updating")
        return

    # PATCH assistant with updated tools
    payload = {
        'tools': tools,
        'instructions': assistant.get('instructions', ''),
        'voice': assistant.get('voice', ''),
        'model': assistant.get('model', ''),
    }
    # Keep other fields
    for field in ['speaking_plan', 'widget_settings', 'telephony_settings']:
        if assistant.get(field):
            payload[field] = assistant[field]

    r = requests.patch(
        f'{base_url}/ai/assistants/{assistant_uuid}',
        headers=headers,
        json=payload
    )

    if r.status_code == 200:
        print(f"✅ Patched AIVA assistant with {updated} new webhook URL(s)")
        new_version = r.json().get('data', r.json()).get('version', '?')
        print(f"  New version: {new_version}")
    else:
        print(f"❌ PATCH failed: {r.status_code} {r.text[:300]}")
        sys.exit(1)


if __name__ == '__main__':
    main()
