package tools

import (
	"context"
	"fmt"
	"strings"
)

// --- ReminderCreateTool ---

type ReminderCreateTool struct {
	gw      *GatewayClient
	adminID string
}

func NewReminderCreateTool(gw *GatewayClient, adminID string) *ReminderCreateTool {
	return &ReminderCreateTool{gw: gw, adminID: adminID}
}

func (t *ReminderCreateTool) Definition() ToolDefinition {
	return ToolDefinition{
		Name:        "reminder_create",
		Description: "创建一个定时提醒。时间格式为 ISO8601（如 2026-06-23T08:00:00+08:00）。如果在群聊中创建提醒，请传入 platform/channel_id/channel_type/adapter_name 以便提醒时发回原群聊。",
		Parameters: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"title":       map[string]string{"type": "string", "description": "提醒标题"},
				"description": map[string]string{"type": "string", "description": "提醒详细描述（可选）"},
				"remind_at":   map[string]string{"type": "string", "description": "提醒时间，ISO8601 格式，如 2026-06-23T08:00:00+08:00"},
				"repeat_type": map[string]string{"type": "string", "description": "重复类型：none（不重复）, daily（每天）, weekly（每周）, monthly（每月），默认 none"},
				"platform":     map[string]string{"type": "string", "description": "（群聊提醒时必填）平台类型，如 obv11"},
				"channel_type": map[string]string{"type": "string", "description": "（群聊提醒时必填）频道类型：group"},
				"channel_id":   map[string]string{"type": "string", "description": "（群聊提醒时必填）群号"},
				"adapter_name": map[string]string{"type": "string", "description": "（群聊提醒时必填）适配器名，如 obv11-main"},
			},
			"required": []string{"title", "remind_at"},
		},
	}
}

func (t *ReminderCreateTool) Execute(ctx context.Context, args map[string]interface{}) (*ToolResult, error) {
	title, _ := args["title"].(string)
	description, _ := args["description"].(string)
	remindAt, _ := args["remind_at"].(string)
	repeatType, _ := args["repeat_type"].(string)
	if repeatType == "" {
		repeatType = "none"
	}

	if title == "" || remindAt == "" {
		return &ToolResult{Success: false, Error: "title 和 remind_at 为必填项"}, nil
	}

	platform, _ := args["platform"].(string)
	channelType, _ := args["channel_type"].(string)
	channelID, _ := args["channel_id"].(string)
	adapterName, _ := args["adapter_name"].(string)
	reminder, err := t.gw.CreateReminder(ctx, t.adminID, title, description, remindAt, repeatType, "", platform, channelType, channelID, adapterName)
	if err != nil {
		return &ToolResult{Success: false, Error: err.Error()}, nil
	}

	return &ToolResult{
		Success: true,
		Data:  fmt.Sprintf("✅ 提醒已创建\nID: %s\n标题: %s\n时间: %s\n重复: %s", reminder.ID, reminder.Title, reminder.RemindAt, reminder.RepeatType),
	}, nil
}

// --- ReminderListTool ---

type ReminderListTool struct {
	gw      *GatewayClient
	adminID string
}

func NewReminderListTool(gw *GatewayClient, adminID string) *ReminderListTool {
	return &ReminderListTool{gw: gw, adminID: adminID}
}

func (t *ReminderListTool) Definition() ToolDefinition {
	return ToolDefinition{
		Name:        "reminder_list",
		Description: "列出当前用户的提醒列表，可按状态过滤（pending/completed/cancelled）。",
		Parameters: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"status": map[string]string{"type": "string", "description": "过滤状态：pending（待执行）, completed（已完成）, cancelled（已取消），默认为空（全部）"},
				"limit":  map[string]interface{}{"type": "integer", "description": "返回条数上限，默认 20"},
			},
		},
	}
}

func (t *ReminderListTool) Execute(ctx context.Context, args map[string]interface{}) (*ToolResult, error) {
	status, _ := args["status"].(string)
	limit := 20
	if l, ok := args["limit"].(float64); ok && l > 0 {
		limit = int(l)
	}

	reminders, err := t.gw.ListReminders(ctx, t.adminID, status, limit)
	if err != nil {
		return &ToolResult{Success: false, Error: err.Error()}, nil
	}

	if len(reminders) == 0 {
		return &ToolResult{Success: true, Data: "📋 暂无提醒"}, nil
	}

	var sb strings.Builder
	sb.WriteString(fmt.Sprintf("📋 提醒列表（共 %d 条）:\n", len(reminders)))
	for _, r := range reminders {
		icon := "⏳"
		if r.Status == "completed" {
			icon = "✅"
		} else if r.Status == "cancelled" {
			icon = "❌"
		}
		sb.WriteString(fmt.Sprintf("%s [%s] %s — %s (ID: %s)\n", icon, r.Status, r.Title, r.RemindAt, r.ID))
	}
	return &ToolResult{Success: true, Data: sb.String()}, nil
}

// --- ReminderDeleteTool ---

type ReminderDeleteTool struct {
	gw      *GatewayClient
	adminID string
}

func NewReminderDeleteTool(gw *GatewayClient, adminID string) *ReminderDeleteTool {
	return &ReminderDeleteTool{gw: gw, adminID: adminID}
}

func (t *ReminderDeleteTool) Definition() ToolDefinition {
	return ToolDefinition{
		Name:        "reminder_delete",
		Description: "删除一个提醒。只能删除自己创建的提醒。",
		Parameters: map[string]interface{}{
			"type": "object",
			"properties": map[string]interface{}{
				"reminder_id": map[string]string{"type": "string", "description": "要删除的提醒 ID"},
			},
			"required": []string{"reminder_id"},
		},
	}
}

func (t *ReminderDeleteTool) Execute(ctx context.Context, args map[string]interface{}) (*ToolResult, error) {
	reminderID, _ := args["reminder_id"].(string)
	if reminderID == "" {
		return &ToolResult{Success: false, Error: "reminder_id 为必填项"}, nil
	}

	if err := t.gw.DeleteReminder(ctx, reminderID); err != nil {
		return &ToolResult{Success: false, Error: err.Error()}, nil
	}

	return &ToolResult{Success: true, Data: fmt.Sprintf("✅ 提醒 %s 已删除", reminderID)}, nil
}
