function getBridge() {
  const bridge = globalThis.__NAPCAT_BRIDGE__;
  if (!bridge) throw new Error('[QCE Overlay] Bridge未初始化');
  return bridge;
}

function normalizeFriend(friend, categoryId = 1) {
  const uin = String(
    friend?.uin ??
    friend?.user_id ??
    friend?.qq ??
    friend?.coreInfo?.uin ??
    ''
  );
  const uid = String(
    friend?.uid ??
    friend?.coreInfo?.uid ??
    friend?.user_uid ??
    uin
  );
  const nick =
    friend?.coreInfo?.nick ??
    friend?.nickname ??
    friend?.nick ??
    uin;
  const remark =
    friend?.coreInfo?.remark ??
    friend?.remark ??
    null;

  return {
    ...friend,
    uid,
    uin,
    coreInfo: {
      ...(friend?.coreInfo || {}),
      uid,
      uin,
      nick,
      remark
    },
    baseInfo: {
      ...(friend?.baseInfo || {}),
      categoryId: friend?.baseInfo?.categoryId ?? friend?.categoryId ?? categoryId
    },
    status: friend?.status || { status: 0 }
  };
}

function normalizeCategory(category, index = 0) {
  const categoryId = category?.categoryId ?? category?.id ?? category?.category_id ?? (index + 1);
  const buddyList = Array.isArray(category?.buddyList)
    ? category.buddyList
    : Array.isArray(category?.friends)
      ? category.friends
      : [];

  return {
    ...category,
    categoryId,
    buddyList: buddyList.map(friend => normalizeFriend(friend, categoryId))
  };
}

function flattenToCategory(friends) {
  return [normalizeCategory({ categoryId: 1, buddyList: friends || [] }, 0)];
}

async function callAction(actionName, payload) {
  const { actions, instance } = getBridge();
  const handler = actions?.get?.(actionName);
  if (!handler) return null;
  const result = await handler.handle(payload, 'plugin', instance?.config);
  return result?.data ?? result ?? null;
}

export const FriendApi = {
  async getBuddyV2ExWithCate(forceRefresh = false) {
    const { core } = getBridge();
    const contexts = [core?.apis?.FriendApi, core?.apis?.friend].filter(Boolean);
    const methodNames = ['getBuddyV2ExWithCate', 'getBuddyV2ExWithCategory'];

    for (const ctx of contexts) {
      for (const methodName of methodNames) {
        const impl = ctx?.[methodName];
        if (typeof impl !== 'function') continue;
        const result = await impl.call(ctx, forceRefresh);
        if (Array.isArray(result)) return result.map(normalizeCategory);
        if (Array.isArray(result?.data)) return result.data.map(normalizeCategory);
      }
    }

    for (const ctx of contexts) {
      const impl = ctx?.getBuddy || ctx?.getFriends;
      if (typeof impl !== 'function') continue;
      const result = await impl.call(ctx, forceRefresh);
      if (Array.isArray(result)) return flattenToCategory(result.map(friend => normalizeFriend(friend)));
      if (Array.isArray(result?.data)) return flattenToCategory(result.data.map(friend => normalizeFriend(friend)));
    }

    const actionResult = await callAction('get_friend_list', {});
    if (Array.isArray(actionResult)) return flattenToCategory(actionResult.map(friend => normalizeFriend(friend)));

    throw new Error('[QCE Overlay] FriendApi.getBuddyV2ExWithCate 不可用');
  },

  async getBuddy(forceRefresh = false) {
    const categories = await this.getBuddyV2ExWithCate(forceRefresh);
    return categories.flatMap(cat => cat?.buddyList || []);
  },

  async getFriends(forceRefresh = false) {
    return this.getBuddy(forceRefresh);
  }
};

export const NTQQFriendApi = FriendApi;
export default FriendApi;
