import { ref } from 'vue'

import {
  createRiskRuleRevision,
  deleteAgentAsset,
  fetchAgentAssetDetail,
  publishRiskRuleAsset,
  regenerateRiskRuleAsset,
  returnRiskRuleAsset,
  setRiskRuleAssetEnabled,
  updateRiskRuleDraft
} from '../../services/agentAssets.js'
import { normalizeText } from './auditViewModel.js'

const DEFAULT_EXPENSE_CATEGORY = 'all'

export function useAuditRiskRuleActions({
  selectedSkill,
  detailBusy,
  actionState,
  canOpenRiskRuleTest,
  canDeleteRiskRule,
  canReturnRiskRule,
  canPublishRiskRule,
  canToggleRiskRuleEnabled,
  canEditRiskRuleDraft,
  canCreateRiskRuleRevision,
  riskRuleTestPassed,
  refreshCurrentAssets,
  loadSelectedAssetDetail,
  mergeSelectedRuleLifecycle,
  closeDetail,
  resolveActor,
  toast
}) {
  const riskRuleTestOpen = ref(false)
  const riskRuleDeleteOpen = ref(false)
  const riskRuleReturnOpen = ref(false)
  const riskRulePublishOpen = ref(false)
  const riskRuleReturnNote = ref('')
  const riskRuleEditOpen = ref(false)
  const riskRuleEditMode = ref('draft')
  const riskRuleEditForm = ref(createRiskRuleEditForm())

  function resetRiskRuleActionDialogs() {
    riskRuleTestOpen.value = false
    riskRuleDeleteOpen.value = false
    riskRuleReturnOpen.value = false
    riskRulePublishOpen.value = false
    riskRuleReturnNote.value = ''
    riskRuleEditOpen.value = false
    riskRuleEditMode.value = 'draft'
    riskRuleEditForm.value = createRiskRuleEditForm()
  }

  function openRiskRuleTestDialog() {
    if (detailBusy.value) {
      return
    }
    if (!canOpenRiskRuleTest.value) {
      if (!selectedSkill.value?.id) {
        toast('规则详情还没有加载完成，请稍后再测试。')
      }
      return
    }
    riskRuleTestOpen.value = true
  }

  function closeRiskRuleTestDialog() {
    riskRuleTestOpen.value = false
  }

  async function handleRiskRuleReportSaved(summary) {
    if (selectedSkill.value) {
      selectedSkill.value.latestTestSummary = summary
    }
    await refreshCurrentAssets()
    if (selectedSkill.value?.id) {
      const detail = await fetchAgentAssetDetail(selectedSkill.value.id)
      mergeSelectedRuleLifecycle(detail)
    }
  }

  function openRiskRuleEditDialog(mode = 'draft') {
    const normalizedMode = mode === 'revision' ? 'revision' : 'draft'
    if (normalizedMode === 'revision' && !canCreateRiskRuleRevision.value) {
      return
    }
    if (normalizedMode === 'draft' && !canEditRiskRuleDraft.value) {
      return
    }
    riskRuleEditMode.value = normalizedMode
    riskRuleEditForm.value = createRiskRuleEditForm(selectedSkill.value, normalizedMode)
    riskRuleEditOpen.value = true
  }

  function closeRiskRuleEditDialog() {
    if (actionState.value === 'save-risk-rule-edit') {
      return
    }
    riskRuleEditOpen.value = false
  }

  async function submitRiskRuleEdit() {
    const isRevision = riskRuleEditMode.value === 'revision'
    if (!selectedSkill.value || detailBusy.value) {
      return
    }
    if (isRevision && !canCreateRiskRuleRevision.value) {
      return
    }
    if (!isRevision && !canEditRiskRuleDraft.value) {
      return
    }

    const payload = normalizeRiskRuleEditPayload(riskRuleEditForm.value, isRevision)
    if (payload.rule_title.length < 2) {
      toast('请输入至少 2 个字的规则标题。')
      return
    }
    if (payload.natural_language.length < 8) {
      toast('请至少输入 8 个字的风险规则描述。')
      return
    }
    if (isRevision && !payload.change_reason) {
      toast('请填写修订原因。')
      return
    }

    actionState.value = 'save-risk-rule-edit'
    const assetId = selectedSkill.value.id
    try {
      const actor = resolveActor()
      if (isRevision) {
        await createRiskRuleRevision(assetId, payload, { actor })
      } else {
        await updateRiskRuleDraft(assetId, payload, { actor })
      }
      const regenerated = await regenerateRiskRuleAsset(assetId, buildRegeneratePayload(payload), { actor })
      riskRuleEditOpen.value = false
      await refreshCurrentAssets()
      mergeSelectedRuleLifecycle(regenerated)
      await loadSelectedAssetDetail(assetId, { silent: true })
      toast(isRevision ? '已创建修订草稿并重新生成规则。' : '风险规则草稿已保存并重新生成。')
    } catch (error) {
      toast(error?.message || (isRevision ? '创建并生成修订版本失败，请稍后重试。' : '保存并生成规则草稿失败，请稍后重试。'))
    } finally {
      actionState.value = ''
    }
  }

  function openDeleteRiskRuleDialog() {
    if (!canDeleteRiskRule.value) {
      return
    }
    riskRuleDeleteOpen.value = true
  }

  function closeDeleteRiskRuleDialog() {
    if (detailBusy.value) {
      return
    }
    riskRuleDeleteOpen.value = false
  }

  async function deleteSelectedRiskRule() {
    if (!selectedSkill.value || !canDeleteRiskRule.value || detailBusy.value) {
      return
    }

    actionState.value = 'delete-risk-rule'
    try {
      await deleteAgentAsset(selectedSkill.value.id, { actor: resolveActor() })
      riskRuleDeleteOpen.value = false
      const deletedName = selectedSkill.value.name
      closeDetail()
      await refreshCurrentAssets()
      toast(`风险规则“${deletedName}”已删除。`)
    } catch (error) {
      toast(error?.message || '风险规则删除失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  function openReturnRiskRuleDialog() {
    if (!canReturnRiskRule.value) {
      return
    }
    riskRuleReturnNote.value = ''
    riskRuleReturnOpen.value = true
  }

  function closeReturnRiskRuleDialog() {
    if (detailBusy.value) {
      return
    }
    riskRuleReturnOpen.value = false
  }

  async function returnSelectedRiskRule() {
    if (!selectedSkill.value || !canReturnRiskRule.value || detailBusy.value) {
      return
    }

    const note = normalizeText(riskRuleReturnNote.value)
    if (!note) {
      toast('请填写回退原因。')
      return
    }

    actionState.value = 'return-risk-rule'
    try {
      await returnRiskRuleAsset(selectedSkill.value.id, { note }, { actor: resolveActor() })
      riskRuleReturnOpen.value = false
      await refreshCurrentAssets()
      await loadSelectedAssetDetail(selectedSkill.value.id, { silent: true })
      toast('风险规则已回退到草稿。')
    } catch (error) {
      toast(error?.message || '风险规则回退失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  function openPublishRiskRuleDialog() {
    if (!canPublishRiskRule.value) {
      if (!riskRuleTestPassed.value) {
        toast('请先确认测试报告通过，再发布上线。')
      }
      return
    }
    riskRulePublishOpen.value = true
  }

  function closePublishRiskRuleDialog() {
    if (detailBusy.value) {
      return
    }
    riskRulePublishOpen.value = false
  }

  async function publishSelectedRiskRule() {
    if (!selectedSkill.value || !canPublishRiskRule.value || detailBusy.value) {
      return
    }

    actionState.value = 'publish-risk-rule'
    try {
      await publishRiskRuleAsset(selectedSkill.value.id, { actor: resolveActor() })
      riskRulePublishOpen.value = false
      await refreshCurrentAssets()
      await loadSelectedAssetDetail(selectedSkill.value.id, { silent: true })
      toast('风险规则已发布上线。')
    } catch (error) {
      toast(error?.message || '风险规则发布失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  async function toggleSelectedRiskRuleEnabled() {
    if (!selectedSkill.value || !canToggleRiskRuleEnabled.value || detailBusy.value) {
      return
    }

    const assetId = selectedSkill.value.id
    const nextEnabled = !selectedSkill.value.isOnlineValue
    actionState.value = 'toggle-risk-rule-enabled'
    try {
      const detail = await setRiskRuleAssetEnabled(assetId, nextEnabled, { actor: resolveActor() })
      mergeSelectedRuleLifecycle(detail)
      await refreshCurrentAssets()
      toast(
        nextEnabled
          ? '风险规则已上线。'
          : '风险规则已下线，不会进入业务扫描。'
      )
    } catch (error) {
      toast(error?.message || '风险规则上线状态更新失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  return {
    riskRuleTestOpen,
    riskRuleDeleteOpen,
    riskRuleReturnOpen,
    riskRulePublishOpen,
    riskRuleReturnNote,
    riskRuleEditOpen,
    riskRuleEditMode,
    riskRuleEditForm,
    resetRiskRuleActionDialogs,
    openRiskRuleTestDialog,
    closeRiskRuleTestDialog,
    handleRiskRuleReportSaved,
    openRiskRuleEditDialog,
    closeRiskRuleEditDialog,
    submitRiskRuleEdit,
    openDeleteRiskRuleDialog,
    closeDeleteRiskRuleDialog,
    deleteSelectedRiskRule,
    openReturnRiskRuleDialog,
    closeReturnRiskRuleDialog,
    returnSelectedRiskRule,
    openPublishRiskRuleDialog,
    closePublishRiskRuleDialog,
    publishSelectedRiskRule,
    toggleSelectedRiskRuleEnabled
  }
}

function createRiskRuleEditForm(rule = null, mode = 'draft') {
  const config = rule?.configJson || {}
  return {
    rule_title: normalizeText(rule?.name),
    expense_category: normalizeText(config.expense_category) || DEFAULT_EXPENSE_CATEGORY,
    requires_attachment: Boolean(rule?.riskRuleRequiresAttachment || config.requires_attachment),
    natural_language: normalizeText(rule?.summary || rule?.riskRuleSubtitle),
    change_reason: mode === 'revision' ? '' : undefined
  }
}

function normalizeRiskRuleEditPayload(form, includeReason) {
  const payload = {
    rule_title: normalizeText(form?.rule_title),
    expense_category: normalizeText(form?.expense_category) || DEFAULT_EXPENSE_CATEGORY,
    requires_attachment: Boolean(form?.requires_attachment),
    natural_language: normalizeText(form?.natural_language)
  }
  if (includeReason) {
    payload.change_reason = normalizeText(form?.change_reason)
  }
  return payload
}

function buildRegeneratePayload(payload) {
  return {
    rule_title: payload.rule_title,
    expense_category: payload.expense_category,
    requires_attachment: payload.requires_attachment,
    natural_language: payload.natural_language
  }
}
