import path from 'node:path'
import type { JsonObject } from '../../../types/json.js'

import { APP_CONFIG_KEYS } from '../../../config/app-config-keys.js'
import { PROJECT_ROOT } from '../../../config/runtime.js'
import { createHttpError } from '../../../utils/http.js'
import { readAppConfigEntry, saveAppConfigEntry } from '../../config/app-config-store.js'
import { normalizeCloudtentaclesDeviceId, normalizeCloudtentaclesDeviceType } from './defaults.js'

const CLOUDTENTACLES_SOURCES_FILE_PATH = path.join(
  PROJECT_ROOT,
  'data',
  'cloudtentacles-sources.json',
)

export function getCloudtentaclesSourcesFilePath() {
  return CLOUDTENTACLES_SOURCES_FILE_PATH
}

// 兼容旧调用：返回 key='default' 的单账号配置。
export function getCloudtentaclesSourceConfig() {
  const config = loadCloudtentaclesSourcesConfig()
  const defaultSource = config.sources.find((s) => s.key === 'default')
  return defaultSource || normalizeCloudtentaclesSourceItem({ key: 'default' })
}

// 按 sourceKey 获取账号配置，未命中时返回 null。
export function getCloudtentaclesSourceByKey(sourceKey: unknown) {
  const config = loadCloudtentaclesSourcesConfig()
  const key = String(sourceKey || '').trim()
  if (!key) return null
  return config.sources.find((s) => s.key === key) || null
}

// 返回完整的多账号配置。
export function listCloudtentaclesSources() {
  return loadCloudtentaclesSourcesConfig()
}

// 兼容旧保存格式：支持单账号对象和 { enabled, sources } 多账号格式。
export function saveCloudtentaclesSourceConfig(rawValue: unknown) {
  const normalized = normalizeCloudtentaclesSourcesConfig(rawValue)
  return saveAppConfigEntry({
    configKey: APP_CONFIG_KEYS.cloudtentaclesSources,
    legacyFilePath: CLOUDTENTACLES_SOURCES_FILE_PATH,
    value: normalized,
    normalize: normalizeCloudtentaclesSourcesConfig,
  })
}

// 保存完整多账号配置。
export function saveCloudtentaclesSourcesList(rawValue: unknown) {
  return saveCloudtentaclesSourceConfig(rawValue)
}

// 按 sourceKey 新增或替换单个账号配置。
export async function saveCloudtentaclesSourceByKey(sourceKey: unknown, data: JsonObject = {}) {
  const key = String(sourceKey || '').trim()
  if (!key) {
    throw createHttpError('cloudtentacles sourceKey 不能为空', {
      statusCode: 400,
      errorCode: 'cloudtentacles_source_key_required',
    })
  }

  const config = loadCloudtentaclesSourcesConfig()
  const normalizedItem = normalizeCloudtentaclesSourceItem({ ...data, key })
  const existingIndex = config.sources.findIndex((s) => s.key === key)

  if (existingIndex >= 0) {
    config.sources[existingIndex] = normalizedItem
  } else {
    config.sources.push(normalizedItem)
  }

  await saveCloudtentaclesSourceConfig(config)
  return normalizedItem
}

// 删除单个账号配置。
export async function deleteCloudtentaclesSourceByKey(sourceKey: unknown) {
  const key = String(sourceKey || '').trim()
  if (!key) {
    throw createHttpError('cloudtentacles sourceKey 不能为空', {
      statusCode: 400,
      errorCode: 'cloudtentacles_source_key_required',
    })
  }

  const config = loadCloudtentaclesSourcesConfig()
  const existingIndex = config.sources.findIndex((s) => s.key === key)

  if (existingIndex < 0) {
    return config
  }

  config.sources.splice(existingIndex, 1)

  await saveCloudtentaclesSourceConfig(config)
  return config
}

function loadCloudtentaclesSourcesConfig() {
  return readAppConfigEntry({
    configKey: APP_CONFIG_KEYS.cloudtentaclesSources,
    legacyFilePath: CLOUDTENTACLES_SOURCES_FILE_PATH,
    fallback: createDefaultCloudtentaclesSourcesConfig,
    normalize: normalizeCloudtentaclesSourcesConfig,
  })
}

// 标准化单个账号配置，补齐 key 和 label。
function normalizeCloudtentaclesSourceItem(rawValue: unknown) {
  const source = isPlainObject(rawValue) ? rawValue : {}

  return {
    key: String(source.key || 'default').trim() || 'default',
    label: String(source.label || '').trim(),
    enabled: source.enabled !== false,
    baseUrl:
      String(source.baseUrl || 'https://123.207.217.176').trim() || 'https://123.207.217.176',
    username: String(source.username || '').trim(),
    password: String(source.password || '').trim(),
    phone: String(source.phone || '').trim(),
    deviceId: normalizeCloudtentaclesDeviceId(source.deviceId),
    deviceType: normalizeCloudtentaclesDeviceType(source.deviceType),
  }
}

// 标准化整体配置，同时兼容旧版单账号对象。
export function normalizeCloudtentaclesSourcesConfig(rawValue: unknown) {
  if (isPlainObject(rawValue) && !Array.isArray(rawValue.sources)) {
    return {
      enabled: rawValue.enabled !== false,
      sources: [
        normalizeCloudtentaclesSourceItem({
          key: 'default',
          label: '默认账号',
          ...rawValue, // 旧字段自动映射为 default 账号。
        }),
      ].filter(Boolean),
    }
  }

  return {
    enabled: isPlainObject(rawValue) ? rawValue.enabled !== false : true,
    sources:
      isPlainObject(rawValue) && Array.isArray(rawValue.sources)
        ? rawValue.sources.map((s) => normalizeCloudtentaclesSourceItem(s)).filter(Boolean)
        : [],
  }
}

function createDefaultCloudtentaclesSourcesConfig() {
  return {
    enabled: true,
    sources: [normalizeCloudtentaclesSourceItem({ key: 'default', label: '默认账号' })],
  }
}

function isPlainObject(value: unknown): value is JsonObject {
  return Object.prototype.toString.call(value) === '[object Object]'
}
