#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
NT-Notify Python 整合範例
這個腳本展示如何在 Python 中使用 NT-Notify API 發送訊息
"""

import requests
import json

# 設定 NT-Notify API 的 URL 和 API Token
API_URL = 'https://notify.example.com/api/notify'
API_TOKEN = 'YOUR_API_TOKEN_HERE'  # 請將此替換為您的實際 API Token


def send_notification(message, title=None, image_url=None):
    """
    發送簡單通知訊息
    
    Args:
        message (str): 要發送的訊息內容
        title (str, optional): 訊息標題
        image_url (str, optional): 圖片 URL
        
    Returns:
        dict: API 回應
    """
    # 準備請求資料
    data = {'message': message}
    
    # 如果有標題，加入 data
    if title:
        data['title'] = title
    
    # 如果有圖片 URL，加入 data
    if image_url:
        data['image_url'] = image_url
    
    # 設定請求標頭
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {API_TOKEN}'
    }
    
    # 發送 API 請求
    response = requests.post(API_URL, headers=headers, json=data)
    
    # 解析回應
    result = response.json()
    
    # 檢查是否成功
    if response.status_code >= 200 and response.status_code < 300:
        print("訊息發送成功！")
    else:
        print(f"訊息發送失敗: {result.get('message', '未知錯誤')}")
    
    return result


def send_to_user(message, recipient_id, title=None, image_url=None):
    """
    發送訊息給特定使用者
    
    Args:
        message (str): 要發送的訊息內容
        recipient_id (str): LINE 用戶 ID
        title (str, optional): 訊息標題
        image_url (str, optional): 圖片 URL
        
    Returns:
        dict: API 回應
    """
    # 準備請求資料
    data = {
        'message': message,
        'recipient_id': recipient_id
    }
    
    # 如果有標題，加入 data
    if title:
        data['title'] = title
    
    # 如果有圖片 URL，加入 data
    if image_url:
        data['image_url'] = image_url
    
    # 設定請求標頭
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {API_TOKEN}'
    }
    
    # 發送 API 請求
    response = requests.post(API_URL, headers=headers, json=data)
    
    # 解析回應
    result = response.json()
    
    # 檢查是否成功
    if response.status_code >= 200 and response.status_code < 300:
        print(f"訊息發送成功給用戶 {recipient_id}！")
    else:
        print(f"訊息發送失敗: {result.get('message', '未知錯誤')}")
    
    return result


def send_to_multiple_users(message, recipient_ids, title=None, image_url=None):
    """
    群發訊息給多個使用者
    
    Args:
        message (str): 要發送的訊息內容
        recipient_ids (list): LINE 用戶 ID 列表 (最多 500 位)
        title (str, optional): 訊息標題
        image_url (str, optional): 圖片 URL
        
    Returns:
        dict: API 回應
    """
    # 檢查接收者數量
    if len(recipient_ids) > 500:
        raise ValueError('一次最多只能發送給 500 位接收者')
    
    # 準備請求資料
    data = {
        'message': message,
        'recipient_ids': recipient_ids
    }
    
    # 如果有標題，加入 data
    if title:
        data['title'] = title
    
    # 如果有圖片 URL，加入 data
    if image_url:
        data['image_url'] = image_url
    
    # 設定請求標頭
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {API_TOKEN}'
    }
    
    # 發送 API 請求
    response = requests.post(API_URL, headers=headers, json=data)
    
    # 解析回應
    result = response.json()
    
    # 檢查是否成功
    if response.status_code >= 200 and response.status_code < 300:
        count = len(recipient_ids)
        print(f"訊息發送成功給 {count} 位用戶！")
    else:
        print(f"訊息發送失敗: {result.get('message', '未知錯誤')}")
    
    return result


def broadcast_to_all(message, title=None, image_url=None):
    """
    廣播訊息給所有會員 (需謹慎使用)
    注意：此功能僅適用於部分業務帳戶，且有嚴格限制
    
    Args:
        message (str): 要發送的訊息內容
        title (str, optional): 訊息標題
        image_url (str, optional): 圖片 URL
        
    Returns:
        dict: API 回應
    """
    # 準備請求資料
    data = {
        'message': message,
        'send_to_all': True
    }
    
    # 如果有標題，加入 data
    if title:
        data['title'] = title
    
    # 如果有圖片 URL，加入 data
    if image_url:
        data['image_url'] = image_url
    
    # 設定請求標頭
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {API_TOKEN}'
    }
    
    # 發送 API 請求
    response = requests.post(API_URL, headers=headers, json=data)
    
    # 解析回應
    result = response.json()
    
    # 檢查是否成功
    if response.status_code >= 200 and response.status_code < 300:
        recipients_count = result.get('data', {}).get('recipients_count', '未知')
        print(f"廣播訊息發送成功給大約 {recipients_count} 位用戶！")
    else:
        print(f"訊息發送失敗: {result.get('message', '未知錯誤')}")
    
    return result


if __name__ == "__main__":
    # 使用範例
    
    # 1. 發送簡單通知訊息
    # send_notification("這是一條測試訊息", "測試標題")
    
    # 2. 發送訊息給特定使用者
    # send_to_user("這是發送給特定用戶的訊息", "U4af4980629...", "個人通知")
    
    # 3. 群發訊息給多個使用者
    # user_ids = ["U4af4980629...", "U8c6d6tx42b...", "U7def892145..."]
    # send_to_multiple_users("這是群發訊息", user_ids, "群組通知")
    
    # 4. 廣播訊息給所有會員 (需謹慎使用)
    # broadcast_to_all("這是重要公告！", "系統公告", "https://example.com/announcement.jpg")
    
    print("NT-Notify Python 整合範例")
    print("請取消註解上方範例程式碼以測試不同的發送方式") 