import AppIntents
import UIKit

// 「上传剪贴板」动作：读本机剪贴板文本，经控件专用会话推到云剪贴板。控制中心控件与主屏小组件按钮
// 共用此 intent。App 外触发时经 WidgetFeedback 弹本地通知反馈成功 / 失败（#6）。
struct UploadClipboardIntent: AppIntent
{
    static var title: LocalizedStringResource = "上传剪贴板"
    static var description = IntentDescription("把本机剪贴板内容上传到 Commilitia Drop 云剪贴板")

    func perform() async throws -> some IntentResult
    {
        let text = await MainActor.run { UIPasteboard.general.string ?? "" }
        guard !text.isEmpty else
        {
            await WidgetFeedback.post(t("ios.clipboard.empty"))
            return .result()
        }
        do
        {
            try await ClipboardClient.upload(text)
            await WidgetFeedback.post(t("ios.clipboard.uploaded"))
        }
        catch ClipboardClient.ClientError.noSession
        {
            await WidgetFeedback.post(t("ios.widget.needApp"))
        }
        catch
        {
            await WidgetFeedback.post(t("ios.clipboard.failed"))
        }
        return .result()
    }
}

// 「拉取剪贴板」动作：拉云剪贴板内容写入本机剪贴板。同上，App 外触发弹本地通知反馈。
struct PullClipboardIntent: AppIntent
{
    static var title: LocalizedStringResource = "拉取剪贴板"
    static var description = IntentDescription("把 Commilitia Drop 云剪贴板内容写入本机剪贴板")

    func perform() async throws -> some IntentResult
    {
        do
        {
            let text = try await ClipboardClient.pull()
            if text.isEmpty
            {
                await WidgetFeedback.post(t("ios.clipboard.empty"))
            }
            else
            {
                await MainActor.run { UIPasteboard.general.string = text }
                await WidgetFeedback.post(t("ios.clipboard.pulled"))
            }
        }
        catch ClipboardClient.ClientError.noSession
        {
            await WidgetFeedback.post(t("ios.widget.needApp"))
        }
        catch
        {
            await WidgetFeedback.post(t("ios.clipboard.failed"))
        }
        return .result()
    }
}
