import {
  fetchAgentAssetRuleJson,
  saveAgentAssetRuleJson
} from '../../services/agentAssets.js'
import {
  applyRiskRuleJsonState,
  resolveRiskRuleDescription
} from './auditViewModel.js'

function readJsonPayload(payload) {
  return payload?.payload && typeof payload.payload === 'object' ? payload.payload : payload
}

function downloadTextFile({ content, fileName, type }) {
  const blob = new Blob([content], { type })
  const objectUrl = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = objectUrl
  link.download = fileName
  link.click()
  URL.revokeObjectURL(objectUrl)
}

export function useAuditRiskRuleJsonEditor({
  selectedSkill,
  canEditMarkdown,
  actionState,
  toast
}) {
  async function loadRiskRuleJson(assetId) {
    if (!assetId || !selectedSkill.value?.usesJsonRiskRule) {
      return
    }

    const payload = await fetchAgentAssetRuleJson(assetId)
    selectedSkill.value = applyRiskRuleJsonState(
      selectedSkill.value,
      readJsonPayload(payload),
      payload
    )
  }

  async function saveRiskRuleJson() {
    if (!selectedSkill.value?.id || !canEditMarkdown.value) {
      return
    }

    actionState.value = 'save-risk-json'
    try {
      const parsed = JSON.parse(String(selectedSkill.value.riskRuleJsonText || '{}'))
      const saved = await saveAgentAssetRuleJson(selectedSkill.value.id, { payload: parsed })
      selectedSkill.value = applyRiskRuleJsonState(
        selectedSkill.value,
        readJsonPayload(saved),
        saved
      )
      toast('风险规则 JSON 已保存。')
    } catch (error) {
      toast(error?.message || '风险规则 JSON 保存失败。')
    } finally {
      actionState.value = ''
    }
  }

  function formatRiskRuleJson() {
    if (!selectedSkill.value?.usesJsonRiskRule) {
      return
    }

    try {
      const parsed = JSON.parse(String(selectedSkill.value.riskRuleJsonText || '{}'))
      selectedSkill.value = applyRiskRuleJsonState(selectedSkill.value, parsed, {
        name: selectedSkill.value.name,
        description: resolveRiskRuleDescription(parsed)
      })
    } catch (error) {
      toast(error?.message || 'JSON 格式无效，无法格式化。')
    }
  }

  function downloadRiskRuleJson() {
    if (!selectedSkill.value?.usesJsonRiskRule) {
      return
    }

    downloadTextFile({
      content: String(selectedSkill.value.riskRuleJsonText || '{}'),
      fileName:
        selectedSkill.value.ruleDocument?.file_name ||
        `${selectedSkill.value.code || 'risk-rule'}.json`,
      type: 'application/json;charset=utf-8'
    })
  }

  return {
    loadRiskRuleJson,
    saveRiskRuleJson,
    formatRiskRuleJson,
    downloadRiskRuleJson
  }
}
