import config
import re
import random
import boto3
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from elasticsearch import Elasticsearch
import json
import ast
import time
import sys
from summary import generate_response, translate_to_korean 
from download_file import list_shared_urls_in_bucket, generate_presigned_url

# elastic 연결
cloud_id = 'univ=============================='
username = 'e==========='
password = 'wNl==========='

app = App(token=config.bot_token)
slack_client = WebClient(token=config.bot_token)

###############################################################################################
### ---------- 1. IR자료 요약하기---------- ###
###############################################################################################
@app.message(re.compile("IR 요약하기"))
def summary(message, say):
    say("🤗 *찾고자 하시는 회사 이름을 입력해주시면, 해당 회사의 IR 핵심 내용을 요약해드립니다* 🤗 ")
    # say("🌟어떤 IR자료를 요약해 줄까?🌟")
    summary_action(message["channel"])
def summary_action(channel_id):
    try:
        blocks = [
            {
                "type": "input",
                "element": {
                    "type": "plain_text_input",
                    "action_id": "input_block"
                },
                "label": {
                    "type": "plain_text",
                    "text": "기업을 입력하세요"
                },
                "block_id": "input_block"
            },
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "IR 요약결과 확인하기"
                        },
                        "action_id": "test_summary"
                    }
                ]
            }
        ]
        response = slack_client.chat_postMessage(channel=channel_id, blocks=blocks)
        return response
    except SlackApiError as e:
        print(f"메시지 전송 오류: {e.response['error']}")
  
@app.action("test_summary")
def test_for_action_2(ack, body, say):
    ack()
    # print(body)
    name = body["state"]["values"]["input_block"]["input_block"]["value"]
    print(name)
    # say(f"IR자료 찾을 키워드는: {key}")
    es = Elasticsearch(
            cloud_id=cloud_id,
            basic_auth=(username, password),
        )
    
    body_keyword={
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "startup_name": name
              }
            }
          ]
        }
      }
    }
  
        
    response = es.search(index="luck4_ir_db_2", body=body_keyword)

    hits = response["hits"]["hits"]
    
    keywordlist=[]

    for hit in hits:
      keywordlist = hit['_source']['keyword_list']
     
    
    
    ### 요약하는 함수 호출 ### 
    
    direct_texts = ""
    
    for key in keywordlist:
        direct_texts += key
        direct_texts += " "
    
    
    english = generate_response(direct_texts)
    korean = translate_to_korean(english)

        
        
    message = {
      "blocks": [
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": f"*📂 영어로 요약한 IR 자료에요!* \\n {english} \\n\\n *📂 한국어로 요약한 IR 자료에요!* \\n {korean}"
            }
        }
      ]
    }
        
    say(message)
  

###############################################################################################
### ---------- 2. 해당 키워드 포함 되어 있는 IR 찾기 ---------- ###
###############################################################################################
@app.message(re.compile("키워드 검색"))
def regex(message, say):
    say("*안녕하세요🤓 IR 자료를 기반으로 하는키워드 검색엔진 입니다*")
    say("*🕵 검색하시고자하는 키워드를 입력해주시면 찾고자 하시는 기업을 빠르게 찾아드릴게요🚀*")
    handle_some_action(message["channel"])

def handle_some_action(channel_id):
    try:
        blocks = [
            {
                "type": "input",
                "element": {
                    "type": "plain_text_input",
                    "action_id": "input_block"
                },
                "label": {
                    "type": "plain_text",
                    "text": "키워드를 입력하세요"
                },
                "block_id": "input_block"
            },
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "키워드에 해당하는 기업 찾기"
                        },
                        "action_id": "test"
                    }
                ]
            }
        ]
        response = slack_client.chat_postMessage(channel=channel_id, blocks=blocks)
        return response
    except SlackApiError as e:
        print(f"메시지 전송 오류: {e.response['error']}")

@app.action("test")
def test_for_action(ack, body, say):
    name_list = []

    ack()
    # print(body)
    key = body["state"]["values"]["input_block"]["input_block"]["value"]
    print(key)
    # say(f"IR자료 찾을 키워드는: {key}")
    es = Elasticsearch(
            cloud_id=cloud_id,
            basic_auth=(username, password),
        )
    
    body_keyword={
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "keyword_list": key
              }
            }
          ]
        }
      }
    }
  
        
    response = es.search(index="luck4_ir_db_2", body=body_keyword)

    hits = response["hits"]["hits"]

    for hit in hits:
      name = hit['_source']['startup_name']
      print(name)
      name_list.append(name)
        
        
    formatted_list = ', '.join(name_list)
    message = {
      "blocks": [
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": f"*📁 IR에 해당 키워드가 태깅되어있는 기업 정보입니다* \\n {formatted_list}"
                    }
                }
            ]
        }
        
    say(message)

###############################################################################################
### ---------- 3. 해당 IR 자료의 주요 키워드 10개 ---------- ###
###############################################################################################
keyword_list = []
@app.message(re.compile("IR 태깅 검색"))
def regex_2(message, say):
    say("*안녕하세요🤓 IR 키워드를 기반으로 하는 기업검색엔진 입니다*")
    say("*🕵 검색하시고자하는 기업명 입력해주시면 IR에 태깅된 키워드들을 보여드려요!*")
    # say("🌟어떤 IR자료의 키워드들을 알려드릴까요?🌟")
    handle_some_action_2(message["channel"])

def handle_some_action_2(channel_id_2):
    try:
        blocks = [
            {
                "type": "input",
                "element": {
                    "type": "plain_text_input",
                    "action_id": "input_block"
                },
                "label": {
                    "type": "plain_text",
                    "text": "기업을 입력하세요"
                },
                "block_id": "input_block"
            },
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "IR 태깅 확인하기"
                        },
                        "action_id": "test2"
                    }
                ]
            }
        ]
        response = slack_client.chat_postMessage(channel=channel_id_2, blocks=blocks)
        return response
    except SlackApiError as e:
        print(f"메시지 전송 오류: {e.response['error']}")

@app.action("test2")
def test_for_action_3(ack, body, say):
    ack()
    # print(body)
    name = body["state"]["values"]["input_block"]["input_block"]["value"]
    # say(f"IR자료 찾을 키워드는: {key}")
    es = Elasticsearch(
            cloud_id=cloud_id,
            basic_auth=(username, password),
        )
    
    body={
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "startup_name": name
              }
            }
          ]
        }
      }
    }
        
    response = es.search(index="luck4_ir_db_2", body=body)

    hits = response["hits"]["hits"]
    # print(hits)
    
    for hit in hits:
      taggings = hit['_source']['taggings']
    
    for tag in taggings:
      keywords = tag['tag']
      print(keywords)
      keyword_list.append(keywords)
    
    
    message = {
        "blocks": [
            {
                "type": "section",
                "text": {
                    "type": "mrkdwn",
                    "text": f"*🔖 이 기업의 IR자료에 태깅되어있는 키워드들을 보여드립니다!* \\n #{keyword_list[0]}\\t #{keyword_list[1]}\\t #{keyword_list[2]}\\t #{keyword_list[3]}\\t #{keyword_list[4]}\\t\\n #{keyword_list[5]}\\t #{keyword_list[6]}\\t #{keyword_list[7]}\\t #{keyword_list[8]}\\t #{keyword_list[9]}"
                }
            }
        ]
    }
    
    say(message)
    

###############################################################################################
### --------- 4.  파일 다운 받기 --------- ###
###############################################################################################

@app.message(re.compile("IR자료 다운받기"))
def regex_download(message, say):
    say("🕵 IR을 다운받으실 기업 이름을 입력해주세요!🔍")
    handle_some_action_download(message["channel"])

def handle_some_action_download(channel_id_download):
    try:
        blocks = [
            {
                "type": "input",
                "element": {
                    "type": "plain_text_input",
                    "action_id": "input_block"
                },
                "label": {
                    "type": "plain_text",
                    "text": "기업을 입력하세요"
                },
                "block_id": "input_block"
            },
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "IR 다운받기"
                        },
                        "action_id": "test_download"
                    }
                ]
            }
        ]
        response = slack_client.chat_postMessage(channel=channel_id_download, blocks=blocks)
        return response
    except SlackApiError as e:
        print(f"메시지 전송 오류: {e.response['error']}")

@app.action("test_download")
def test_for_action_download(ack, body, say):
    ack()
    # print(body)
    name = body["state"]["values"]["input_block"]["input_block"]["value"]
    # say(f"{name} 의 IR자료 다운로드")
    
    
    shared_url = list_shared_urls_in_bucket('luck4-ir-bucket', name)
    # print("shared_url")
    print(shared_url)
    
    send_message_with_button(shared_url)

# 버튼을 생성하고 url 전송하는 함수
def send_message_with_button(url):
    try:
      blocks=[
          {
              "type": "section",
              "text": {
                  "type": "mrkdwn",
                  "text": "🔗 오른쪽 버튼을 통해 IR자료를 다운 받으실 수 있습니다!🤗 "
              },
              "accessory": {
                  "type": "button",
                  "text": {
                      "type": "plain_text",
                      "text": "IR 자료 다운로드"
                  },
                  "url": url  # 버튼을 눌렀을 때 이동할 URL 설정
              }
          }
      ]
      response = slack_client.chat_postMessage(channel = 'ir_slack_bot', blocks=blocks)

    except SlackApiError as e:
        print(url)
        print(f"Error sending message")
        print(e)

  # BASE         
if __name__ == '__main__':
    SocketModeHandler(app, config.app_token).start()