"""
Slack通知ユーティリティモジュール

このモジュールは、Slackへのメッセージ送信とファイル送信機能を提供します。

推奨使用方法:
- メッセージ送信: send_slack_message(message, webhook_url)
- ファイル送信: send_slack_file(file_path, message, channel_id, title)

既存の関数は互換性のために残されていますが、
新しいコードでは上記の汎用関数を使用することを推奨します。
"""

import json
import requests
import os
from datetime import datetime
from config.load_env import load_environment_variables
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
    
#環境変数の取得
load_environment_variables() 

def send_slack_message(message, webhook_url):
    """
    汎用Slackメッセージ送信関数
    
    Args:
        message: 送信するメッセージ
        webhook_url: WebhookのURL環境変数キー
    
    Returns:
        Slack APIからのレスポンス
    """
    headers = {'Content-Type': 'application/json'}
    data = {'text': message}
    response = requests.post(webhook_url, headers=headers, data=json.dumps(data))
    return response.text

def send_slack_file(file_path, message, channel_id="C052Z37SWAV", title="File Upload"):
    """
    汎用Slackファイル送信関数
    
    Args:
        file_path: 送信するファイルのパス
        message: ファイルと一緒に送信するメッセージ
        channel_id: 送信先チャンネルID（デフォルト: C052Z37SWAV）
        title: ファイルのタイトル
    
    Returns:
        Slack APIからのレスポンス
    """
    try:
        slack_token = os.getenv('PROD_SLACK_BOT_TOKEN')
        client = WebClient(token=slack_token)

        if not os.path.exists(file_path):
            raise FileNotFoundError(f"The file {file_path} does not exist.")
        
        response = client.files_upload_v2(
            file=file_path,
            title=title,
            channel=channel_id,
            initial_comment=message,
        )
        response.get("file")
        print("File uploaded successfully.")
        return response

    except SlackApiError as e:
        print(f"Slack API Error: {e.response['error']}")
        return None


    
def send_slack_api_file(message):    
    # 送信するファイルのパス
    current_directory = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    folder_name = f'{current_directory}/myapp/apis/file/status_history'
    timestamp = datetime.now().strftime('%Y-%m-%d')
    file_path = f'{folder_name}/history_{timestamp}.csv'
    
    return send_slack_file(file_path, message, "C052Z37SWAV", "Today's Status Management File")

def send_slack_api_file_individually(message):
    # 送信するファイルのパス
    current_directory = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    folder_name = f'{current_directory}/myapp/apis/file/status_history'
    timestamp = datetime.now().strftime('%Y-%m-%d')
    file_path = f'{folder_name}/history_{timestamp}.csv'
    
    return send_slack_file(file_path, message, "C052Z37SWAV", "Today's Status Management File")
        

