import {
  activateAgentAsset,
  createAgentAssetVersion,
  restoreAgentAssetVersion,
  updateAgentAsset
} from '../../services/agentAssets.js'
import {
  buildRuleConfigPayload,
  incrementVersion
} from './auditViewRuntimeModel.js'
import {
  buildMarkdownVersionContent,
  normalizeText,
  parseRuntimeRuleText
} from './auditViewModel.js'

export function useAuditRuleVersionActions({
  selectedSkill,
  selectedSkillIsRule,
  canEditMarkdown,
  canManageSelected,
  actionState,
  detailBusy,
  refreshCurrentAssets,
  loadSelectedAssetDetail,
  resolveActor,
  toast
}) {
  async function persistRuleRuntimeConfig(asset, runtimeRule) {
    await updateAgentAsset(
      asset.id,
      {
        config_json: buildRuleConfigPayload(asset, runtimeRule)
      },
      { actor: resolveActor() }
    )
  }

  async function saveRuleVersion({ action, changeNote, successLabel }) {
    if (
      !selectedSkill.value ||
      !selectedSkillIsRule.value ||
      selectedSkill.value.usesSpreadsheetRule ||
      !canEditMarkdown.value ||
      detailBusy.value
    ) {
      return
    }

    if (!normalizeText(selectedSkill.value.markdownContent)) {
      toast('规则 Markdown 内容不能为空。')
      return
    }

    const runtimeRule = parseRuntimeRuleText(selectedSkill.value.runtimeRuleText)
    if (!runtimeRule) {
      toast('运行时 JSON 必须是合法的对象。')
      return
    }

    const nextVersion = incrementVersion(selectedSkill.value.currentVersion)
    actionState.value = action

    try {
      await createAgentAssetVersion(
        selectedSkill.value.id,
        {
          version: nextVersion,
          content: buildMarkdownVersionContent(selectedSkill.value.markdownContent, runtimeRule),
          content_type: 'markdown',
          change_note: changeNote,
          created_by: resolveActor()
        },
        { actor: resolveActor() }
      )
      await persistRuleRuntimeConfig(selectedSkill.value, runtimeRule)
      await refreshCurrentAssets()
      await loadSelectedAssetDetail(selectedSkill.value.id, { silent: true })
      toast(`${successLabel} ${nextVersion}。`)
    } catch (error) {
      toast(error?.message || `${successLabel}失败，请稍后重试。`)
    } finally {
      actionState.value = ''
    }
  }

  async function saveRuleMarkdown() {
    await saveRuleVersion({
      action: 'save-markdown',
      changeNote: '通过规则中心保存 Markdown 规则内容，并同步运行时 JSON。',
      successLabel: '规则 Markdown 已保存为'
    })
  }

  async function saveRuleRuntimeJson() {
    await saveRuleVersion({
      action: 'save-runtime-json',
      changeNote: '通过规则中心保存运行时 JSON 配置。',
      successLabel: '规则 JSON 已保存为'
    })
  }

  async function activateSelectedRule() {
    if (!selectedSkill.value || !selectedSkillIsRule.value || !canManageSelected.value || detailBusy.value) {
      return
    }

    actionState.value = 'activate'
    try {
      await activateAgentAsset(selectedSkill.value.id, { actor: resolveActor() })
      await refreshCurrentAssets()
      await loadSelectedAssetDetail(selectedSkill.value.id, { silent: true })
      toast('规则已正式上线。')
    } catch (error) {
      toast(error?.message || '规则上线失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  async function restoreSelectedVersion(version) {
    if (
      !selectedSkill.value ||
      !selectedSkillIsRule.value ||
      !canManageSelected.value ||
      detailBusy.value ||
      !version
    ) {
      return
    }

    actionState.value = `restore-${version}`
    try {
      await restoreAgentAssetVersion(selectedSkill.value.id, version, { actor: resolveActor() })
      await refreshCurrentAssets()
      await loadSelectedAssetDetail(selectedSkill.value.id, { silent: true })
      toast(`已基于 ${version} 生成新的工作版本。`)
    } catch (error) {
      toast(error?.message || '历史版本恢复失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  return {
    saveRuleMarkdown,
    saveRuleRuntimeJson,
    activateSelectedRule,
    restoreSelectedVersion
  }
}
