import requests
import json
import os

TELNYX_API_KEY = "KEY019BE7A3A2D749FCA8681CFF8448A7F0_vTMM1n77CtQxLDT2ra3P1z"
ASSISTANT_ID = "assistant-9c42d3ce-e05a-4e34-8083-c91081917637"

def main():
    print(f"Updating Telnyx Assistant {ASSISTANT_ID} with Lead Capture Tool...")
    
    payload = {
        "tools": [
            {
                "type": "webhook",
                "webhook": {
                    "name": "lead_capture",
                    "description": "Captures lead information (name, phone, email, needs, preferred time) and sends it to the CRM.",
                    "url": "https://services.leadconnectorhq.com/hooks/73q7bKDm2d6hsCtHuz1m/webhook-trigger/lead-capture",
                    "method": "POST",
                    "async": True,
                    "body_parameters": {
                        "type": "object",
                        "properties": {
                            "name": {"type": "string", "description": "Full name of the lead"},
                            "phone": {"type": "string", "description": "Phone number of the lead"},
                            "email": {"type": "string", "description": "Email address of the lead"},
                            "needs": {"type": "string", "description": "Description of the services needed"},
                            "preferred_time": {"type": "string", "description": "Preferred time for a call or appointment"}
                        },
                        "required": ["name", "phone"]
                    }
                }
            }
        ]
    }

    try:
        resp = requests.patch(
            f"https://api.telnyx.com/v2/ai/assistants/{ASSISTANT_ID}",
            headers={
                "Authorization": f"Bearer {TELNYX_API_KEY}",
                "Content-Type": "application/json",
            },
            json=payload,
            timeout=30.0
        )
        print("Update Status:", resp.status_code)
        if resp.status_code != 200:
            print("Error Response:", resp.text)
        else:
            print("Successfully added webhook tool to assistant.")
            
    except Exception as e:
        print("Error during request:", str(e))

if __name__ == "__main__":
    main()
