import path from 'node:path'

import { PROJECT_ROOT } from '../../../config/runtime.js'
import { readJsonFile, writeJsonFile } from '../../../utils/json-file-store.js'

const KUAISHOU_ETICKET_SOURCE_FILE_PATH = path.join(PROJECT_ROOT, 'data', 'kuaishou-eticket-source.json')
const DEFAULT_BASE_URL = 'https://s.kwaixiaodian.com'

type JsonObject = Record<string, any>

export type KuaishouEticketShopConfig = {
  shopId: string
  kshopName: string
  cookie: string
  userAvatar: string
  enabled: boolean
}

export type KuaishouEticketSourceConfig = {
  enabled: boolean
  baseUrl: string
  shops: KuaishouEticketShopConfig[]
}

export function getKuaishouEticketSourceFilePath(): string {
  return KUAISHOU_ETICKET_SOURCE_FILE_PATH
}

export function getKuaishouEticketSourceConfig(): KuaishouEticketSourceConfig {
  return loadKuaishouEticketSourceConfigFromFile()
}

export function saveKuaishouEticketSourceConfig(rawValue: unknown): KuaishouEticketSourceConfig {
  return writeJsonFile(
    KUAISHOU_ETICKET_SOURCE_FILE_PATH,
    rawValue,
    normalizeKuaishouEticketSourceConfig,
  )
}

export function listKuaishouEticketShopConfigs(source: KuaishouEticketSourceConfig = getKuaishouEticketSourceConfig()): KuaishouEticketShopConfig[] {
  return Array.isArray(source?.shops) ? source.shops : []
}

export function findKuaishouEticketShopConfig(shopId: unknown, source: KuaishouEticketSourceConfig = getKuaishouEticketSourceConfig()): KuaishouEticketShopConfig | null {
  const normalizedShopId = String(shopId || '').trim()
  if (!normalizedShopId) {
    return null
  }

  return listKuaishouEticketShopConfigs(source).find((item) => String(item.shopId || '').trim() === normalizedShopId) || null
}

export function findKuaishouEticketShopConfigByName(kshopName: unknown, source: KuaishouEticketSourceConfig = getKuaishouEticketSourceConfig()): KuaishouEticketShopConfig | null {
  const normalizedName = String(kshopName || '').trim()
  if (!normalizedName) {
    return null
  }

  return listKuaishouEticketShopConfigs(source).find((item) => String(item.kshopName || '').trim() === normalizedName) || null
}

export function resolveKuaishouEticketShopConfig(
  { shopId = '', kshopName = '', shopName = '' }: { shopId?: unknown, kshopName?: unknown, shopName?: unknown } = {},
  source: KuaishouEticketSourceConfig = getKuaishouEticketSourceConfig(),
): KuaishouEticketShopConfig | null {
  const byId = findKuaishouEticketShopConfig(shopId, source)
  if (byId) {
    return byId
  }

  const normalizedName = String(kshopName || shopName || '').trim()
  if (!normalizedName) {
    return null
  }

  return findKuaishouEticketShopConfigByName(normalizedName, source)
}

export function getFirstAvailableKuaishouEticketShop(source: KuaishouEticketSourceConfig = getKuaishouEticketSourceConfig()): KuaishouEticketShopConfig | null {
  return listKuaishouEticketShopConfigs(source).find((item) => item.enabled !== false && String(item.cookie || '').trim()) || null
}

function loadKuaishouEticketSourceConfigFromFile(): KuaishouEticketSourceConfig {
  return readJsonFile(
    KUAISHOU_ETICKET_SOURCE_FILE_PATH,
    createDefaultKuaishouEticketSourceConfig,
    normalizeKuaishouEticketSourceConfig,
  )
}

function normalizeKuaishouEticketSourceConfig(rawValue: unknown): KuaishouEticketSourceConfig {
  const source = isPlainObject(rawValue) ? rawValue : {}
  const shops = Array.isArray(source.shops)
    ? source.shops
    : buildLegacySingleShopList(source)

  return {
    enabled: typeof source.enabled === 'boolean' ? source.enabled : true,
    baseUrl: String(source.baseUrl || DEFAULT_BASE_URL).trim() || DEFAULT_BASE_URL,
    shops: shops
      .map((item) => normalizeKuaishouEticketShopConfig(item))
      .filter(Boolean),
  }
}

function normalizeKuaishouEticketShopConfig(rawValue: unknown): KuaishouEticketShopConfig | null {
  if (!isPlainObject(rawValue)) {
    return null
  }

  const shopId = String(rawValue.shopId || rawValue.userId || '').trim()
  const kshopName = String(rawValue.kshopName || rawValue.shopName || rawValue.userName || '').trim()
  const cookie = String(rawValue.cookie || '').trim()
  const userAvatar = String(rawValue.userAvatar || '').trim()
  const enabled = typeof rawValue.enabled === 'boolean' ? rawValue.enabled : true

  if (!shopId && !kshopName && !cookie) {
    return null
  }

  return {
    shopId,
    kshopName,
    cookie,
    userAvatar,
    enabled,
  }
}

function buildLegacySingleShopList(source: JsonObject): JsonObject[] {
  const cookie = String(source.cookie || '').trim()
  if (!cookie) {
    return []
  }

  return [
    {
      shopId: '',
      kshopName: '',
      cookie,
      userAvatar: '',
      enabled: source.enabled !== false,
    },
  ]
}

function createDefaultKuaishouEticketSourceConfig(): KuaishouEticketSourceConfig {
  return {
    enabled: true,
    baseUrl: DEFAULT_BASE_URL,
    shops: [],
  }
}

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