import { computed, reactive } from 'vue'
import { api } from './api'

export interface Task {
  id: string
  app: string
  app_name: string
  version: string
  action: string
  status: 'running' | 'ok' | 'failed'
  log: string[]
  error?: string
  started_at: number
  ended_at?: number
}

export const taskStore = reactive<{
  items: Task[]
  updatedAt: number
}>({ items: [], updatedAt: 0 })

let timer: number | undefined
let finishHandler: ((task: Task) => void) | null = null

export function setTaskFinishHandler(fn: (task: Task) => void) {
  finishHandler = fn
}

export function taskLabel(task: Task): string {
  const verb = task.action === 'install' ? '安装' : '卸载'
  return `${verb} ${task.app_name} ${task.version}`
}

export async function refreshTasks() {
  try {
    // logs=0 keeps the 4s background poll small; the detail request pulls logs.
    const items = await api.get<Task[]>('api/v1/apps/tasks?limit=20&logs=0')
    const previous = new Map(taskStore.items.map((t) => [t.id, t.status]))
    taskStore.items = items
    taskStore.updatedAt = Date.now()
    if (finishHandler) {
      for (const t of items) {
        if (previous.get(t.id) === 'running' && t.status !== 'running') finishHandler(t)
      }
    }
  } catch {
    /* polling is best effort */
  }
}

/** Poll the shared task list while the panel is open. */
export function startTaskWatch() {
  if (timer !== undefined) return
  void refreshTasks()
  timer = window.setInterval(() => {
    if (!document.hidden) void refreshTasks()
  }, 4000)
}

export function stopTaskWatch() {
  if (timer !== undefined) {
    window.clearInterval(timer)
    timer = undefined
  }
}

export const runningTasks = computed(() => taskStore.items.filter((t) => t.status === 'running'))
export const recentTasks = computed(() => taskStore.items.slice(0, 8))
