import type { FormRules } from 'naive-ui'

import { api } from '@/tools/web.ts'
import type { AiiProviderPublic } from '@/types/aii.ts'
import type { ReturnDto } from '@/types/response.ts'

export async function check_remote_model(provider_id: number, model_name: string) {
  try {
    return await api
      .get(`/aii/provider/${provider_id}/remote/model/${model_name}/`)
      .then((res) => res.data as ReturnDto)
      .then((data) => data.success)
  } catch (err) {
    console.error('检测远端模型可用性时出现问题：', provider_id, model_name, err)
    return false
  }
}

export async function check_remote_provider(provider: AiiProviderPublic) {
  try {
    return await api
      .post('/aii/remote/provider/check/', JSON.stringify(provider))
      .then((res) => res.data as ReturnDto)
      .then((data) => data.success)
  } catch (err) {
    console.error(`检查远端模型提供商可用性时出现问题：`, provider, err)
    return false
  }
}

export const aiiModelRules: FormRules = {
  aii_provider_id: {
    required: true,
    trigger: 'blur',
  },
  model_name: {
    required: true,
    trigger: 'blur',
  },
  max_context_length: {
    required: true,
    trigger: ['change', 'blur'],
    message: '最大上下文长度需要合理设置。大部分模型的上下文长度在数百到一千 k 左右',
    validator(_, value) {
      if (typeof value !== 'number') return new Error('非数字')
      if (value < 20) return new Error('上下文长度过小，不太合理？')
      return true
    },
  },
}
