TOOL_NAME = "slack_webhook_send"
TOOL_DESCRIPTION = """Send a message to Slack via an incoming webhook URL. Use this for one-off Slack posts when no Slack bot integration is connected. Requires the full webhook URL as argument."""
TOOL_ARGS = '{"webhook_url": {"type": "string", "description": "The Slack webhook URL"}, "message": {"type": "string", "description": "The text message to send"}, "username": {"type": "string", "default": "AI Assistant", "description": "Custom username to display"}, "icon_emoji": {"type": "string", "default": ":robot_face:", "description": "Custom emoji icon"}}'

import json
import urllib.request
import ssl
from tools._std import tool_ok, tool_error

def run(args: dict) -> str:
    webhook_url = args.get('webhook_url')
    message = args.get('message')
    username = args.get('username', 'AI Assistant')
    icon_emoji = args.get('icon_emoji', ':robot_face:')
    
    if not webhook_url:
        return tool_error("webhook_url is required")
    if not message:
        return tool_error("message is required")
    
    payload = {
        "text": message,
        "username": username,
        "icon_emoji": icon_emoji
    }
    
    data = json.dumps(payload).encode('utf-8')
    headers = {'Content-Type': 'application/json'}
    
    try:
        req = urllib.request.Request(webhook_url, data=data, headers=headers, method='POST')
        context = ssl.create_default_context()
        
        with urllib.request.urlopen(req, context=context, timeout=30) as response:
            result = response.read().decode('utf-8')
            if result == 'ok':
                return tool_ok(None, f"Message sent to Slack: '{message[:50]}...'")
            return tool_error(f"Slack response: {result}")
    except Exception as e:
        return tool_error(f"Error sending to Slack: {str(e)}")
