import axios from 'axios'
import { normalizeSkillTimestamps } from './skillTimestamp.js'

// 后端地址：默认走同源 /api；开发期由 Vite 转发到本地后端，避免浏览器代理拦截 localhost。
export const API_BASE = import.meta.env.VITE_API_BASE || '/api'

const http = axios.create({
  baseURL: API_BASE,
  timeout: 30000,
})

// 请求拦截器：自动注入当前用户的邮箱+手机号作为身份头
// 后端可以在中间件读取 X-User-Email / X-User-Phone 识别用户
http.interceptors.request.use(config => {
  if (typeof window !== 'undefined' && window.__AIPRO_USER__) {
    const u = window.__AIPRO_USER__
    if (u.email) config.headers['X-User-Email'] = u.email
    if (u.phone) config.headers['X-User-Phone'] = u.phone
  }
  return config
})

// 响应拦截器：统一处理网络异常、超时、服务端错误
http.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
      error.friendlyMessage = '请求超时，请检查网络后重试'
    } else if (!error.response) {
      // 无 response 表示网络完全不通（断网、DNS 失败等）
      error.friendlyMessage = '网络连接失败，请检查网络设置'
    } else if (error.response.status >= 500) {
      error.friendlyMessage = '服务器异常，请稍后重试'
    } else if (error.response.status === 401) {
      error.friendlyMessage = '身份已过期，请重新登录'
      // 清除本地用户信息，触发多标签页同步
      try { localStorage.removeItem('aipro_auth_user_v1') } catch {}
    } else if (error.response.status === 403) {
      error.friendlyMessage = error.response.data?.error || error.response.data?.message || '无权限执行此操作'
    } else if (error.response.status === 400 || error.response.status === 422) {
      error.friendlyMessage = error.response.data?.error || error.response.data?.message || '请求参数有误'
    } else if (error.response.status === 404) {
      error.friendlyMessage = error.response.data?.error || error.response.data?.message || '请求的资源不存在'
    } else if (error.response.status === 429) {
      error.friendlyMessage = '请求过于频繁，请稍后重试'
    }
    return Promise.reject(error)
  }
)

/* ============ 身份认证 ============ */
// 登录即创建：邮箱 + 手机号同时同步给后端。后端未实现时会抛错，前端在调用处 catch 住不阻塞主流程
export async function registerOrLogin({ email, phone }) {
  const r = await http.post('/users/sync', {}, {
    headers: {
      'X-User-Email': email,
      'X-User-Phone': phone,
    },
  })
  return r.data
}

/* ============ 大模型服务商配置 ============ */
export async function listProviders() {
  const r = await http.get('/providers')
  return r.data
}

export async function updateProvider(code, patch) {
  const r = await http.patch(`/providers/${code}`, patch)
  return r.data
}

export async function setActiveProvider(code) {
  const r = await http.post(`/providers/${code}/active`)
  return r.data
}

export async function testProvider(code) {
  const r = await http.post(`/providers/${code}/test`)
  return r.data
}

export async function fetchProviderModels(code) {
  const r = await http.get(`/providers/${code}/models`)
  return r.data
}

/* ============ 运行时与智能体配置 ============ */
export async function listRuntimes() {
  const r = await http.get('/runtimes')
  return r.data
}

export async function updateRuntime(code, patch) {
  const r = await http.patch(`/runtimes/${code}`, patch)
  return r.data
}

export async function setActiveRuntime(code) {
  const r = await http.post(`/runtimes/${code}/active`)
  return r.data
}

export async function testRuntime(code) {
  const r = await http.post(`/runtimes/${code}/test`)
  return r.data
}

export async function saveRuntimeAgent(id, data) {
  const r = await http.put(`/runtimes/agents/${encodeURIComponent(id)}`, data)
  return r.data
}

/* ============ 平台系统 Skill：创建器 / 评测器 ============ */
export async function listSystemSkills() {
  const r = await http.get('/system-skills')
  return r.data
}

export async function saveSystemSkill(kind, data) {
  const r = await http.put(`/system-skills/${encodeURIComponent(kind)}`, data)
  return r.data
}

export async function deleteSystemSkill(kind) {
  const r = await http.delete(`/system-skills/${encodeURIComponent(kind)}`)
  return r.data
}

export async function importDefaultSystemSkill(kind) {
  const r = await http.post(`/system-skills/${encodeURIComponent(kind)}/import-default`)
  return r.data
}

export async function getMe() {
  return (await http.post('/users/sync')).data
}

/**
 * cf-worker 风格：扁平 categories
 * 返回 { data: [{id, parent_id, code, name, level, path, status, sort}] }
 */
export async function listCategoriesFlat() {
  return (await http.get('/categories')).data
}

/**
 * cf-worker 风格：嵌套 tree
 * 返回 { data: [{...node, children: [...]}] }
 */
export async function listCategoriesTree() {
  return (await http.get('/categories/tree')).data
}

/** 创建分类节点 */
export async function createCategory(data) {
  const r = await http.post('/categories', data)
  return r.data
}

/** 更新分类节点名称 */
export async function updateCategory(id, data) {
  const r = await http.put(`/categories/${id}`, data)
  return r.data
}

/** 删除分类节点 */
export async function deleteCategory(id) {
  const r = await http.delete(`/categories/${id}`)
  return r.data
}

/** 兼容旧调用：返回 { tree, total } */
export async function getCategoryNodes() {
  const r = await http.get('/categories/tree')
  const tree = (r.data?.data) || []
  // 估算总数：递归数
  const count = (arr) => arr.reduce((s, n) => s + 1 + count(n.children || []), 0)
  return { tree, total: count(tree) }
}

/**
 * 上传原始包到 R2（multipart/form-data）
 * 返回 { data: { file_id, r2_key, filename, size, mime } }
 */
export async function uploadPackage(file, onProgress) {
  const fd = new FormData()
  fd.append('file', file)
  const r = await http.post('/uploads', fd, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 0,
    onUploadProgress: (e) => {
      if (onProgress && e.total) onProgress(Math.round(e.loaded * 100 / e.total))
    }
  })
  return r.data
}

/**
 * 操作日志查询（运营消费）
 */
export async function listAuditLogs({ action = '', actor_phone = '', page = 1, size = 50 } = {}) {
  const r = await http.get('/audit', { params: { action, actor_phone, page, size } })
  return r.data
}

export async function getSkills({ status = 'all', page = 1, pageSize = 20, keyword = '', nodeId = null } = {}) {
  // 对接粗工 /api/skills，把返回的字段映射成 AllSkills/SkillCard 期望的形状
  const params = { page, size: pageSize }
  if (status && status !== 'all') params.status = status
  if (keyword) params.q = keyword
  if (nodeId) params.node_id = nodeId
  const r = await http.get('/skills', { params })
  const raw = r.data
  const items = (raw.data || []).map(s => {
    const normalized = normalizeSkillTimestamps(s)
    const pathParts = (s.node_path || '').split(' / ').filter(Boolean)
    const lastLabel = pathParts.at(-1) || ''
    const parentLabel = pathParts.slice(0, -1).join(' / ')
    return {
      ...normalized,
      title: s.name,
      author: s.creator_name || '',
      version: s.version || 'v0.0.0',
      tags: '',
      content: '',
      category_nodes: lastLabel
        ? [{ id: s.node_id, label: lastLabel, parent_label: parentLabel }]
        : [],
    }
  })
  return { items, total: raw.total || 0, page: raw.page || 1, page_size: pageSize }
}

export async function getStats() {
  return (await http.get('/stats')).data
}

export async function getAoneStatus() {
  return (await http.get('/aone-oauth/status')).data
}

// ===== Skill 运行后台 =====
// 分析指标类接口（trend/logs/comments/callers）后端暂未实现，返回空数据。

export async function getSkillsByNode(nodeId) {
  // 复用真实的 /api/skills 接口，居点过滤由它处理
  const result = await getSkills({ nodeId: nodeId || null, pageSize: 100 })
  return result.items || []
}

export async function getSkillOverview(skillId) {
  // 拉真实 skill 信息，指标全部返回 null （表示暂无数据）
  const s = await getSkillApi(skillId)
  if (!s) return null
  const pathParts = (s.node_path || '').split(' / ').filter(Boolean)
  const lastLabel = pathParts.at(-1) || ''
  const parentLabel = pathParts.slice(0, -1).join(' / ')
  const skill = {
    ...s,
    title: s.name,
    author: s.creator_name || '',
    version: s.version || 'v0.0.0',
    category_nodes: lastLabel
      ? [{ id: s.node_id, label: lastLabel, parent_label: parentLabel }]
      : [],
  }
  const overview = {
    callTotal: null, callToday: null, downloadTotal: null,
    commentTotal: null, avgRating: null, avgLatencyMs: null,
    errorRate: null, callerCount: null, qps: null,
    endpoint: '—', method: 'POST', apiKey: '—'
  }
  return { skill, overview }
}

export async function getSkillTrend(_skillId, _days) {
  return []
}

export async function getSkillCallLogs(_skillId, _limit) {
  return []
}

export async function getSkillComments(_skillId, _limit) {
  return { list: [], total: 0, dist: { 5:0, 4:0, 3:0, 2:0, 1:0 } }
}

export async function getSkillCallerDist(_skillId) {
  return []
}

export async function getSkillComparison(nodeId) {
  const result = await getSkills({ nodeId: nodeId || null, pageSize: 100 })
  return (result.items || []).map(s => ({
    id: s.id, title: s.title || s.name, author: s.author,
    version: s.version || 'v0.0.0', status: s.status,
    callTotal: null, callToday: null, downloadTotal: null,
    commentTotal: null, avgRating: null, avgLatencyMs: null,
    errorRate: null, qps: null
  }))
}

// ===== Skill 基础 CRUD（SkillsContext 用，对接 cf-worker） =====

// 前端 → cf-worker payload
function toCfPayload(p) {
  if (!p || typeof p !== 'object') return p
  const out = {}
  if (p.name !== undefined)         out.name = p.name
  if (p.desc !== undefined)         out.description = p.desc
  if (p.description !== undefined)  out.description = p.description
  if (p.node_id !== undefined)      out.node_id = p.node_id
  if (p.source !== undefined)       out.source = p.source
  if (p.status !== undefined)       out.status = p.status
  if (p.creator_name !== undefined) out.creator_name = p.creator_name
  if (p.package_key !== undefined)  out.package_key = p.package_key
  if (p.package_size !== undefined) out.package_size = p.package_size
  if (p.package_name !== undefined) out.package_name = p.package_name
  if (p.visibility !== undefined)   out.visibility = p.visibility
  return out
}

// cf-worker → 前端 shape
function fromCfSkill(s) {
  if (!s || typeof s !== 'object') return s
  const normalized = normalizeSkillTimestamps(s)
  return {
    ...normalized,
    desc:           s.description ?? '',
    node_id:        s.node_id ?? null,
    node_path:      s.node_path ?? '',
    source:         s.source ?? '',
    creator_name:   s.creator_name ?? '',
    creator_phone:  s.creator_phone ?? '',
    creator_email:  s.creator_email ?? '',
    visibility:     s.visibility || 'public',
    package_key:    s.package_key ?? null,
    package_size:   s.package_size ?? null,
    package_name:   s.package_name ?? null,
    version:        s.version || 'v0.0.0',
    file_ids:       [],
    file_names:     s.package_name ? [s.package_name] : [],
    messages:       [],
    eval_records:   [],
    system_prompt:  '',
    published_at:   null
  }
}

export async function getSkillApi(id) {
  const r = await http.get(`/skills/${id}`)
  return fromCfSkill(r.data?.data || r.data)
}

export async function listSkills() {
  const r = await http.get('/skills', { params: { size: 200 } })
  const list = Array.isArray(r.data?.data) ? r.data.data : []
  return { list: list.map(fromCfSkill) }
}

export async function createSkillApi(data) {
  const payload = toCfPayload(data)
  // 默认 source='create'（CreateSkill 用），UploadSkill 显式传 'upload'
  if (!payload.source) payload.source = 'create'
  const r = await http.post('/skills', payload)
  return fromCfSkill(r.data?.data || r.data)
}

export async function updateSkillApi(id, patch) {
  const r = await http.put(`/skills/${id}`, toCfPayload(patch))
  return fromCfSkill(r.data?.data || r.data)
}

export async function deleteSkillApi(id) {
  const r = await http.delete(`/skills/${id}`)
  return r.data
}

/** 用 PUT status=published 实现「发布」 */
export async function publishSkillApi(id) {
  const r = await http.put(`/skills/${id}`, { status: 'published' })
  return fromCfSkill(r.data?.data || r.data)
}

/** 用 PUT status=archived 实现「下线」 */
export async function offlineSkillApi(id) {
  const r = await http.put(`/skills/${id}`, { status: 'archived' })
  return fromCfSkill(r.data?.data || r.data)
}

/**
 * 下载计数上报（复制 curl 命令 / 点击下载按钮时调用，fire-and-forget）
 */
export async function trackSkillDownload(id) {
  if (!id) return
  try {
    await http.post(`/skills/${id}/download`)
  } catch {}
}

/**
 * 点赞 / 点踩（同 vote 再点则取消）
 * @param {string} id - skill id
 * @param {'like'|'dislike'} vote
 * @returns {{ vote: 'like'|'dislike'|null, like_count: number, dislike_count: number }}
 */
export async function voteSkill(id, vote) {
  const r = await http.post(`/skills/${id}/vote`, { vote })
  return r.data
}

/**
 * 查当前用户对该 skill 的投票状态
 * @returns {{ vote: 'like'|'dislike'|null }}
 */
export async function getMyVote(id) {
  try {
    const r = await http.get(`/skills/${id}/my-vote`)
    return r.data
  } catch {
    return { vote: null }
  }
}

/* ============ 用户管理 ============ */

/** 获取用户列表（可按邮箱/手机号/名称搜索） */
export async function fetchUsers(q = '') {
  const params = q ? { q } : {}
  const r = await http.get('/users', { params })
  return r.data
}

/** 修改用户角色 */
export async function updateUserRole(id, role) {
  const r = await http.put(`/users/${id}/role`, { role })
  return r.data
}

/** 删除用户 */
export async function deleteUser(id) {
  const r = await http.delete(`/users/${id}`)
  return r.data
}

/** 登录同步用户到后端 */
export async function syncUser() {
  const r = await http.post('/users/sync')
  return r.data
}

/* ============ API Key 管理 ============ */

/** 创建 API Key（成功返回完整 key，仅一次） */
export async function createApiKey(skillId, name) {
  const r = await http.post('/apikeys', { skill_id: skillId, name })
  return r.data?.data || r.data
}

/** 列出当前用户的所有 API Key */
export async function listApiKeys() {
  const r = await http.get('/apikeys')
  return r.data
}

/** 吊销 API Key */
export async function revokeApiKey(keyId) {
  const r = await http.delete(`/apikeys/${keyId}`)
  return r.data
}

/** 获取 API Key 调用统计 */
export async function getApiKeyStats(keyId) {
  const r = await http.get(`/apikeys/${keyId}/stats`)
  return r.data?.data || r.data
}

export async function getOpsRankings({ limit = 20 } = {}) {
  const r = await http.get('/ops/rankings', { params: { limit } })
  return r.data
}

/**
 * 管理员下载项目源码 zip
 */
export async function downloadSourceCode() {
  const r = await http.get('/download/source', { responseType: 'blob' })
  const url = URL.createObjectURL(r.data)
  const a = document.createElement('a')
  a.href = url
  a.download = 'aipros-source.zip'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

/**
 * 下载 Skill ZIP 包（用于 EvaluationPanel 解压读取内容）
 */
export async function downloadSkillPackage(packageKey) {
  const r = await http.get(`/uploads/download?key=${encodeURIComponent(packageKey)}`, {
    responseType: 'blob',
  })
  return r.data
}

/**
 * 获取平台当前激活的 AI 服务商信息（不含 key）
 * 用于 EvaluationPanel/SkillSandboxPage 判断平台是否已配置 AI
 */
export async function getEvalConfig() {
  const r = await http.get('/eval')
  return r.data
}

/**
 * 获取当前用户的鉴权请求头（用于 fetch 流式请求）
 */
export function getAuthHeaders() {
  const h = {}
  if (typeof window !== 'undefined' && window.__AIPRO_USER__) {
    const u = window.__AIPRO_USER__
    if (u.email) h['X-User-Email'] = u.email
    if (u.phone) h['X-User-Phone'] = u.phone
  }
  return h
}

/**
 * 获取 Skill 执行引擎配置状态（AgentRun）
 * @returns {{ hasEngine: boolean, engineKind: 'agentrun'|null, agentRun?: object }}
 */
export async function getSkillRunConfig() {
  const r = await http.get('/skill-run')
  return r.data
}

/**
 * AI 绘图：自然语言/流程文件 → AgentRun 执行内核 → 流程图 JSON
 */
export async function generateAiFlowchart({ prompt, file, mode = 'react-flow' }) {
  const fd = new FormData()
  fd.append('prompt', prompt || '')
  fd.append('mode', mode || 'react-flow')
  if (file) fd.append('file', file)

  const res = await fetch(`${API_BASE}/skill-run/flowchart`, {
    method: 'POST',
    headers: getAuthHeaders(),
    body: fd,
  })

  if (!res.ok) {
    const text = await res.text().catch(() => '')
    let message = text || `HTTP ${res.status}`
    try {
      const json = JSON.parse(text)
      message = json.error || json.message || message
    } catch {}
    throw new Error(message)
  }

  return res.json()
}
