const AGENTRUN_HOST_RE = /^([^.]+)\.agentrun-data\.([a-z0-9-]+)\.aliyuncs\.com$/i
const AGENTRUN_PATH_RE = /^\/agent-runtimes\/([^/]+)\/endpoints\/([^/]+)\/invocations\/openai\/v1\/chat\/completions\/?$/i

export function parseAgentRunIntegrationUrl(value) {
  const raw = String(value || '').trim()
  if (!raw) return null

  let url
  try {
    url = new URL(raw)
  } catch {
    return null
  }

  const hostMatch = url.hostname.match(AGENTRUN_HOST_RE)
  const pathMatch = url.pathname.match(AGENTRUN_PATH_RE)
  if (!hostMatch || !pathMatch || url.protocol !== 'https:') return null

  return {
    endpointPublicUrl: url.toString(),
    accountId: hostMatch[1],
    regionId: hostMatch[2],
    runtimeName: decodeURIComponent(pathMatch[1]),
    endpointName: decodeURIComponent(pathMatch[2]),
  }
}

export function isAgentRunIntegrationUrl(value) {
  return !!parseAgentRunIntegrationUrl(value)
}

export function buildAgentRunChatCompletionsRequest({
  endpointPublicUrl,
  invocationKey,
  sessionId,
  messages,
  stream = false,
  tools,
  toolChoice,
  maxTokens,
}) {
  const parsed = parseAgentRunIntegrationUrl(endpointPublicUrl)
  if (!parsed) {
    throw new Error('AgentRun 集成 URL 格式不正确')
  }

  const sid = String(sessionId || '').trim()
  if (!sid) throw new Error('AgentRun sessionId 不能为空')

  const headers = {
    'Content-Type': 'application/json',
    'x-agentrun-session-id': sid,
  }
  const key = String(invocationKey || '').trim()
  if (key) headers.Authorization = `Bearer ${key}`

  const body = {
    messages: Array.isArray(messages) ? messages : [],
    stream: !!stream,
  }
  if (Array.isArray(tools) && tools.length) body.tools = tools
  if (toolChoice !== undefined && toolChoice !== null) body.tool_choice = toolChoice
  if (Number.isFinite(maxTokens) && maxTokens > 0) body.max_tokens = Math.floor(maxTokens)

  return {
    url: parsed.endpointPublicUrl,
    options: {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
    },
  }
}

export function extractOpenAIChunkText(chunk) {
  const choice = chunk?.choices?.[0]
  const deltaText = choice?.delta?.content
  if (typeof deltaText === 'string') return deltaText
  const messageText = choice?.message?.content
  if (typeof messageText === 'string') return messageText
  return ''
}
