package com.agentui.desktop

import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import androidx.work.*
import java.util.concurrent.TimeUnit

/**
 * Periodic background worker that triggers the widget ListView to refresh.
 * The actual data fetching happens in TerminalListFactory.onDataSetChanged().
 */
class TranscriptWidgetWorker(
    private val context: Context,
    params: WorkerParameters
) : CoroutineWorker(context, params) {

    companion object {
        const val WORK_NAME = "transcript_widget_refresh"

        fun enqueue(context: Context) {
            val request = OneTimeWorkRequestBuilder<TranscriptWidgetWorker>()
                .build()
            WorkManager.getInstance(context)
                .enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, request)
        }

        fun cancel(context: Context) {
            WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
        }
    }

    override suspend fun doWork(): Result {
        // Tell the widget's ListView adapter to re-fetch data
        val appWidgetManager = AppWidgetManager.getInstance(context)
        val widgetIds = appWidgetManager.getAppWidgetIds(
            ComponentName(context, TranscriptWidgetProvider::class.java)
        )
        appWidgetManager.notifyAppWidgetViewDataChanged(widgetIds, R.id.terminal_list)

        // Schedule next refresh
        val next = OneTimeWorkRequestBuilder<TranscriptWidgetWorker>()
            .setInitialDelay(30, TimeUnit.SECONDS)
            .build()
        WorkManager.getInstance(context)
            .enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, next)

        return Result.success()
    }
}
