import type { Task } from '@/api'
import { TASK_TYPE } from '@/constants'

/** 从仓库任务生成可复制的同步指令 */
export function generateTaskPoolCommand(task: Partial<Task> | null | undefined): string {
  if (!task || task.type !== TASK_TYPE.REPO) return ''
  let repo: Record<string, any> = {}
  try {
    const cfg = JSON.parse(task.config || '{}')
    repo = cfg.repo || cfg || {}
  } catch {
    repo = {}
  }
  const url = String(repo.source_url || '').trim()
  if (!url) return ''

  const branch = String(repo.branch || 'main').trim() || 'main'
  const target = String(repo.target_path || '').trim()
  const sparse = String(repo.sparse_path || '').trim()
  const proxy = String(repo.proxy_url || repo.proxy || '').trim()
  const token = String(repo.auth_token || '').trim()
  const single = !!repo.single_file

  const parts = ['taskpool repo-sync', `--url "${url}"`, `--branch "${branch}"`]
  if (target) parts.push(`--target "${target}"`)
  if (sparse) parts.push(`--sparse "${sparse}"`)
  if (proxy) parts.push(`--proxy "${proxy}"`)
  if (token) parts.push(`--token "***"`)
  if (single) parts.push('--single-file')
  if (task.schedule) parts.push(`--cron "${task.schedule}"`)
  if (task.name) parts.push(`--name "${task.name}"`)
  return parts.join(' ')
}

/** 构建脚本执行命令（对齐原版 buildExecutionCommand） */
export function buildExecutionCommand(
  filePath: string,
  envs: { plugin: string; version: string }[],
  scriptsDir = 'scripts',
) {
  const rel = filePath.replace(/^\/+/, '')
  const full = scriptsDir ? `${scriptsDir.replace(/\/$/, '')}/${rel}` : rel
  const ext = rel.split('.').pop()?.toLowerCase() || ''
  const misePrefix =
    envs.length > 0
      ? `mise exec ${envs.map((e) => `${e.plugin}@${e.version}`).join(' ')} -- `
      : ''

  if (ext === 'py') return `${misePrefix}python "${full}"`
  if (ext === 'js' || ext === 'mjs' || ext === 'cjs') return `${misePrefix}node "${full}"`
  if (ext === 'ts') return `${misePrefix}npx tsx "${full}"`
  if (ext === 'go') return `${misePrefix}go run "${full}"`
  if (ext === 'rb') return `${misePrefix}ruby "${full}"`
  if (ext === 'php') return `${misePrefix}php "${full}"`
  if (ext === 'rs') return `${misePrefix}cargo run --manifest-path "${full}"`
  if (ext === 'ps1') return `powershell -ExecutionPolicy Bypass -File "${full}"`
  if (ext === 'bat' || ext === 'cmd') return `"${full}"`
  return `${misePrefix}bash "${full}"`
}
