{
  "name": "Telegram AI Chatbot with History",
  "description": "Handles Telegram messages, adds history, calls an AI, and logs the conversation.",
  "nodes": [
    {
      "id": "trigger_telegram",
      "type": "WEBHOOK_TRIGGER",
      "parameters": { "path": "/telegram" },
      "connections": { "output": "get_history" }
    },
    {
      "id": "get_history",
      "type": "SQLITE_QUERY",
      "parameters": {
        "db_file": "conversation_history.db",
        "query": "SELECT role, content FROM conversations WHERE chat_id = ? ORDER BY timestamp ASC;"
      },
      "connections": { "output": "save_user_message" }
    },
    {
      "id": "save_user_message",
      "type": "SQLITE_EXEC",
      "parameters": {
        "db_file": "conversation_history.db",
        "query": "INSERT INTO conversations (chat_id, role, content, timestamp) VALUES (?, 'user', ?, ?);"
      },
      "connections": { "output": "call_ai" }
    },
    {
      "id": "call_ai",
      "type": "SET_DATA",
      "parameters": {
        "code": [
          "DIM chat_id",
          "DIM user_message$",
          "DIM history_array",
          "chat_id = INPUT_DATA{\"message\"}{\"chat\"}{\"id\"}",
          "user_message$ = INPUT_DATA{\"message\"}{\"text\"}",
          "history_array = INPUT_DATA{\"history\"}",
          "PRINT \"Calling AI for user: \" + user_message$",
          "ai_response$ = WFLIB.call_openai_with_history(user_message$, history_array)",
          "GLOBAL_RETURN = {\"ai_response\": ai_response$, \"chat_id\": chat_id, \"user_message\": user_message$}"
        ]
      },
      "connections": { "output": "save_ai_response" }
    },
    {
      "id": "save_ai_response",
      "type": "SQLITE_EXEC",
      "parameters": {
        "db_file": "conversation_history.db",
        "query": "INSERT INTO conversations (chat_id, role, content, timestamp) VALUES (?, 'assistant', ?, ?);"
      },
      "connections": { "output": "send_to_telegram" }
    },
    {
      "id": "send_to_telegram",
      "type": "SET_DATA",
      "parameters": {
        "code": [
          "PRINT \"Sending response to Telegram...\"",
          "WFLIB.send_telegram_message(INPUT_DATA{\"chat_id\"}, INPUT_DATA{\"ai_response\"})",
          "GLOBAL_RETURN = {\"status\": \"Message sent\"}"
        ]
      },
      "connections": {}
    }
  ]
}