import { isAgentRunIntegrationUrl, parseAgentRunIntegrationUrl } from './agentrun-openai.js'

export const AGENTRUN_CODE = 'agentrun'
export const AGENTRUN_PROTOCOL = 'agentrun'

export function secretPreview(value) {
  const s = String(value || '').trim()
  if (!s) return null
  if (s.length < 4) return '已保存'
  if (s.length === 4) return `...${s}`
  return `...${s.slice(-4)}`
}

export function missingAgentRunConfig(row = {}) {
  if (isAgentRunIntegrationUrl(row.endpoint_public_url)) {
    return String(row.api_key || '').trim() ? [] : ['api_key']
  }

  const missing = []
  if (!String(row.access_key_id || '').trim()) missing.push('access_key_id')
  if (!String(row.access_key_secret || '').trim()) missing.push('access_key_secret')
  if (!String(row.account_id || '').trim()) missing.push('account_id')
  if (!String(row.runtime_name || '').trim()) missing.push('runtime_name')
  return missing
}

export function isAgentRunReady(row = {}) {
  return !!row.enabled && missingAgentRunConfig(row).length === 0
}

export function rowToAgentRunProvider(row = {}) {
  const accessKeyId = String(row.access_key_id || '').trim()
  const accessKeySecret = String(row.access_key_secret || '').trim()
  const securityToken = String(row.security_token || '').trim()
  const invocationKey = String(row.api_key || '').trim()
  const runtimeName = String(row.runtime_name || '').trim()
  const endpointName = String(row.endpoint_name || 'default').trim() || 'default'

  return {
    code: row.code || AGENTRUN_CODE,
    name: row.name || '阿里云 AgentRun',
    icon: row.icon || '☁️',
    protocol: AGENTRUN_PROTOCOL,
    baseUrl: row.endpoint_public_url || '',
    defaultModel: endpointName,
    models: [{ value: endpointName, label: endpointName }],
    enabled: !!row.enabled,
    isActive: !!row.is_active,
    hasKey: !!(invocationKey || accessKeySecret),
    keyPreview: secretPreview(invocationKey || accessKeySecret),
    hasInvocationKey: !!invocationKey,
    invocationKeyPreview: secretPreview(invocationKey),
    hasAccessKeyId: !!accessKeyId,
    accessKeyIdPreview: secretPreview(accessKeyId),
    hasAccessKeySecret: !!accessKeySecret,
    hasSecurityToken: !!securityToken,
    accountId: row.account_id || '',
    regionId: row.region_id || 'cn-hangzhou',
    runtimeName,
    endpointName,
    runtimeId: row.runtime_id || '',
    endpointId: row.endpoint_id || '',
    endpointPublicUrl: row.endpoint_public_url || '',
    runtimeStatus: row.runtime_status || '',
    endpointStatus: row.endpoint_status || '',
    missing: missingAgentRunConfig(row),
  }
}

export function sanitizeAgentRunPatch(body = {}, existing = {}) {
  const patch = {}
  const copyString = (from, to = from) => {
    if (typeof body[from] === 'string') patch[to] = body[from].trim()
  }
  const copySecret = (from, to = from) => {
    if (typeof body[from] === 'string' && body[from].trim()) patch[to] = body[from].trim()
  }

  copySecret('accessKeyId', 'access_key_id')
  copySecret('accessKeySecret', 'access_key_secret')
  copySecret('securityToken', 'security_token')
  copySecret('invocationKey', 'api_key')
  copyString('accountId', 'account_id')
  copyString('regionId', 'region_id')
  copyString('runtimeName', 'runtime_name')
  copyString('endpointName', 'endpoint_name')
  copyString('runtimeId', 'runtime_id')
  copyString('endpointId', 'endpoint_id')
  copyString('endpointPublicUrl', 'endpoint_public_url')

  const parsedUrl = parseAgentRunIntegrationUrl(patch.endpoint_public_url || existing.endpoint_public_url)
  if (parsedUrl) {
    if (!patch.account_id) patch.account_id = parsedUrl.accountId
    if (!patch.region_id) patch.region_id = parsedUrl.regionId
    if (!patch.runtime_name) patch.runtime_name = parsedUrl.runtimeName
    if (!patch.endpoint_name) patch.endpoint_name = parsedUrl.endpointName
  }

  if (typeof body.enabled === 'boolean') patch.enabled = body.enabled ? 1 : 0
  if (typeof body.isActive === 'boolean') patch.is_active = body.isActive ? 1 : 0

  const merged = { ...existing, ...patch }
  if (!merged.region_id) merged.region_id = 'cn-hangzhou'
  if (!merged.endpoint_name) merged.endpoint_name = 'default'
  return { patch, merged }
}
