import { apiRequest, pickSafeHeaderValue } from './api.js'

const AUTH_USER_STORAGE_KEY = 'x-financial-auth-user'

function readActorName() {
  if (typeof window === 'undefined') {
    return 'system'
  }

  const raw = window.sessionStorage.getItem(AUTH_USER_STORAGE_KEY)
  if (!raw) {
    return 'system'
  }

  try {
    const payload = JSON.parse(raw)
    return (
      pickSafeHeaderValue(payload?.name, payload?.username) ||
      pickSafeHeaderValue(payload?.username, 'system') ||
      'system'
    )
  } catch {
    return 'system'
  }
}

function buildWriteHeaders(options = {}) {
  const actor = String(options.actor || readActorName()).trim() || 'system'
  const headers = {
    'x-actor': actor
  }

  if (options.requestId) {
    headers['x-request-id'] = String(options.requestId).trim()
  }

  return headers
}

function buildQuery(params = {}) {
  const search = new URLSearchParams()

  if (params.assetType) {
    search.set('asset_type', params.assetType)
  }

  if (params.status) {
    search.set('status', params.status)
  }

  if (params.domain) {
    search.set('domain', params.domain)
  }

  if (params.keyword) {
    search.set('keyword', params.keyword)
  }

  if (params.limit) {
    search.set('limit', String(params.limit))
  }

  if (params.version) {
    search.set('version', String(params.version))
  }

  if (params.agent) {
    search.set('agent', params.agent)
  }

  if (params.source) {
    search.set('source', params.source)
  }

  const query = search.toString()
  return query ? `?${query}` : ''
}

export function fetchAgentAssets(params = {}) {
  return apiRequest(`/agent-assets${buildQuery(params)}`)
}

export function fetchAgentAssetDetail(assetId) {
  return apiRequest(`/agent-assets/${assetId}`)
}

export function fetchAgentAssetSpreadsheetOnlyOfficeConfig(assetId) {
  return apiRequest(`/agent-assets/${assetId}/spreadsheet/onlyoffice-config`)
}

export function fetchAgentAssetSpreadsheetBlob(assetId, disposition = 'inline') {
  const search = new URLSearchParams()
  if (disposition) {
    search.set('disposition', String(disposition).trim())
  }
  const query = search.toString()
  return apiRequest(`/agent-assets/${assetId}/spreadsheet/content${query ? `?${query}` : ''}`, {
    responseType: 'blob',
    contentType: null
  })
}

export function uploadAgentAssetSpreadsheet(assetId, file, options = {}) {
  return apiRequest(
    `/agent-assets/${assetId}/spreadsheet/upload?filename=${encodeURIComponent(file.name)}`,
    {
      method: 'POST',
      body: file,
      contentType: file.type || 'application/octet-stream',
      headers: buildWriteHeaders(options)
    }
  )
}

export function importAgentAssetSpreadsheetContent(assetId, file, options = {}) {
  return apiRequest(
    `/agent-assets/${assetId}/spreadsheet/import-content?filename=${encodeURIComponent(file.name)}`,
    {
      method: 'POST',
      body: file,
      contentType: file.type || 'application/octet-stream',
      headers: buildWriteHeaders(options)
    }
  )
}

export function fetchAgentAssetVersions(assetId, limit = 5) {
  return apiRequest(`/agent-assets/${assetId}/versions${buildQuery({ limit })}`)
}

export function fetchAgentAssetVersionTimeline(assetId) {
  return apiRequest(`/agent-assets/${assetId}/version-timeline`)
}

export function fetchAgentAssetRuleJson(assetId) {
  return apiRequest(`/agent-assets/${assetId}/rule-json`)
}

export function saveAgentAssetRuleJson(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/rule-json`, {
    method: 'PUT',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options)
  })
}

export function generateRiskRuleAsset(payload, options = {}) {
  return apiRequest('/agent-assets/risk-rules/generate', {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options),
    timeoutMs: options.timeoutMs || 60000,
    timeoutMessage: '风险规则生成时间较长，请稍后查看是否已生成草稿。'
  })
}

export function fetchRiskRuleLatestTest(assetId) {
  return apiRequest(`/agent-assets/${assetId}/risk-rule-tests/latest`)
}

export function runRiskRuleSampleTest(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/risk-rule-tests/sample`, {
    method: 'POST',
    body: JSON.stringify(payload || {}),
    headers: buildWriteHeaders(options)
  })
}

export function simulateRiskRuleTest(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/risk-rule-tests/simulate`, {
    method: 'POST',
    body: JSON.stringify(payload || {}),
    headers: buildWriteHeaders(options)
  })
}

export function runRiskRuleScenarioTest(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/risk-rule-tests/scenario`, {
    method: 'POST',
    body: JSON.stringify(payload || {}),
    headers: buildWriteHeaders(options)
  })
}

export function confirmRiskRuleTestReport(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/risk-rule-tests/report`, {
    method: 'POST',
    body: JSON.stringify(payload || {}),
    headers: buildWriteHeaders(options)
  })
}

export function deleteAgentAsset(assetId, options = {}) {
  return apiRequest(`/agent-assets/${assetId}`, {
    method: 'DELETE',
    headers: buildWriteHeaders(options)
  })
}

export function returnRiskRuleAsset(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/return`, {
    method: 'POST',
    body: JSON.stringify(payload || {}),
    headers: buildWriteHeaders(options)
  })
}

export function publishRiskRuleAsset(assetId, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/publish`, {
    method: 'POST',
    headers: buildWriteHeaders(options)
  })
}

export function setRiskRuleAssetEnabled(assetId, enabled, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/risk-rule-enabled`, {
    method: 'POST',
    body: JSON.stringify({ enabled: Boolean(enabled) }),
    headers: buildWriteHeaders(options)
  })
}

export function setRiskRuleAssetLevel(assetId, riskLevel, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/risk-rule-level`, {
    method: 'POST',
    body: JSON.stringify({ risk_level: riskLevel }),
    headers: buildWriteHeaders(options)
  })
}

export function fetchAgentAssetSpreadsheetChangeRecords(assetId, limit = 30) {
  return apiRequest(
    `/agent-assets/${assetId}/spreadsheet/change-records${buildQuery({ limit })}`
  )
}

export function updateAgentAsset(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}`, {
    method: 'PATCH',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options)
  })
}

export function createAgentAssetVersion(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/versions`, {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options)
  })
}

export function createAgentAssetReview(assetId, payload, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/reviews`, {
    method: 'POST',
    body: JSON.stringify(payload),
    headers: buildWriteHeaders(options)
  })
}

export function activateAgentAsset(assetId, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/activate`, {
    method: 'POST',
    headers: buildWriteHeaders(options)
  })
}

export function restoreAgentAssetVersion(assetId, version, options = {}) {
  return apiRequest(`/agent-assets/${assetId}/versions/${encodeURIComponent(version)}/restore`, {
    method: 'POST',
    headers: buildWriteHeaders(options)
  })
}

export function fetchAgentRuns(params = {}) {
  return apiRequest(`/agent-runs${buildQuery(params)}`)
}

export function fetchAgentRunDetail(runId) {
  return apiRequest(`/agent-runs/${encodeURIComponent(runId)}`)
}
