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

function normalizeGroup(group) {
  const code = group?.groupCode ?? group?.group_code ?? group?.group_id ?? group?.groupId ?? group?.groupUin ?? '';
  const name = group?.groupName ?? group?.group_name ?? group?.groupRemark ?? group?.name ?? String(code || 'unknown');
  const memberCount = group?.memberCount ?? group?.member_count ?? group?.memberNum ?? 0;
  const maxMember = group?.maxMember ?? group?.max_member ?? group?.maxMemberCount ?? 0;

  return {
    ...group,
    groupCode: String(code),
    groupName: String(name),
    memberCount: Number(memberCount) || 0,
    maxMember: Number(maxMember) || 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 GroupApi = {
  async getGroups(forceRefresh = false) {
    const { core } = getBridge();
    const contexts = [core?.apis?.GroupApi, core?.apis?.group].filter(Boolean);
    const methodNames = ['getGroups', 'getGroupList', 'getGroupLists'];

    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(normalizeGroup);
        if (Array.isArray(result?.data)) return result.data.map(normalizeGroup);
        if (Array.isArray(result?.result?.groupList)) return result.result.groupList.map(normalizeGroup);
      }
    }

    const actionResult = await callAction('get_group_list', {});
    if (Array.isArray(actionResult)) return actionResult.map(normalizeGroup);

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

  async fetchGroupDetail(groupId) {
    const { core } = getBridge();
    const impl = core?.apis?.GroupApi?.fetchGroupDetail || core?.apis?.group?.fetchGroupDetail;
    if (impl) {
      const detail = await impl.call(core.apis.GroupApi || core.apis.group, String(groupId));
      return detail ? normalizeGroup(detail) : detail;
    }

    const actionResult = await callAction('get_group_info', { group_id: Number(groupId) });
    return actionResult ? normalizeGroup(actionResult) : actionResult;
  },

  async getGroupMemberAll(groupId, forceRefresh = false) {
    const { core } = getBridge();
    const impl = core?.apis?.GroupApi?.getGroupMemberAll || core?.apis?.group?.getGroupMemberAll;
    if (impl) return impl.call(core.apis.GroupApi || core.apis.group, String(groupId), forceRefresh);

    const { actions, instance } = getBridge();
    const handler = actions?.get?.('get_group_member_list');
    if (!handler) throw new Error('[QCE Overlay] get_group_member_list 不可用');

    const result = await handler.handle({ group_id: Number(groupId) }, 'plugin', instance?.config);
    const members = result?.data ?? result ?? null;
    if (!Array.isArray(members)) {
      throw new Error('[QCE Overlay] get_group_member_list 返回异常');
    }

    return { result: { infos: new Map(members.map(m => [m.user_id, m])) } };
  },

  // 入群申请 / 邀请通知（issue #317）。优先走 NapCat 上层 OneBot 的
  // get_group_system_msg，因为它已经把 uid 解析成了 uin、把 group/user1/user2
  // 等字段拍平成 invited_requests / join_requests，调用方零额外解析。
  // 直接 NT 内部 API 没有 uin 解析，调用方还得自己再 await UserApi.getUinByUidV2，
  // 用这个 fallback 不划算。
  async getGroupSystemMsg(count = 50) {
    const { actions, instance } = getBridge();
    const handler = actions?.get?.('get_group_system_msg');
    if (!handler) throw new Error('[QCE Overlay] get_group_system_msg 不可用');
    const result = await handler.handle({ count: Number(count) || 50 }, 'plugin', instance?.config);
    return result?.data ?? result ?? null;
  }
};

export const NTQQGroupApi = GroupApi;
export default GroupApi;
