from typing import List, Optional
import requests

from pqai_agent.toolkit.base import BaseToolkit
from pqai_agent.toolkit.function_tool import FunctionTool
from pqai_agent import configs

class LarkAlertForHumanIntervention(BaseToolkit):
    r"""A toolkit for Lark alert for human intervention."""

    def __init__(self):
        self.webhook_url = configs.get().get('system', {}).get('human_intervention_alert_url', '')
        super().__init__()

    def send_lark_alert_for_human_intervention(
        self, message: str, ack_url: Optional[str] = None
    ) -> str:
        r"""Sends a Lark alert for human intervention.

        Args:
            message (str): The message to send.
            ack_url (str): The URL to acknowledge the alert.
        Returns:
            str: A confirmation message.
        """
        if not self.webhook_url:
            return "Webhook URL not configured."

        contents = [{
            "tag": "text",
            "text": f"{message}\n"
        }]
        if ack_url:
            contents.append({
                "tag": "a",
                "text": "[处理完成点击此处]",
                "href": ack_url
            })

        req_body = {
            "msg_type": "post",
            "content": {
                "post": {
                    "zh_cn": {
                        "title": f'Agent告警',
                        "content": [contents]
                    }
                }
            }
        }
        try:
            response = requests.post(
                url=self.webhook_url,
                json=req_body
            )
            return f"Alert sent successfully: {response.status_code}"
        except Exception as e:
            return f"Failed to send alert: {e}"

    def get_tools(self) -> List[FunctionTool]:
        return [FunctionTool(self.send_lark_alert_for_human_intervention)]

if __name__ == '__main__':
    toolkit = LarkAlertForHumanIntervention()
    tools = toolkit.get_tools()
    for tool in tools:
        print(f"Tool schema: {tool.get_openai_tool_schema()}")
    ack_url = "http://ai-wechat-hook-internal.piaoquantv.com/manage/insertEvent?" \
                f"sender=1688855931724582&receiver=1688854492669990&type=103&content=OPERATION"
    resp = toolkit.send_lark_alert_for_human_intervention('测试', ack_url)
    print(resp)
