// FaceRecognition.js
import { NativeModules, Platform } from 'react-native';
import RNFS from 'react-native-fs';
import { launchImageLibrary } from 'react-native-image-picker';

const { BaiduFaceModule } = NativeModules;

// 初始化SDK
export const initFaceSDK = () => {
  const licenseId = "YOUR_LICENSE_ID"; // 从百度控制台获取
  if (Platform.OS === 'android') {
    BaiduFaceModule.initSDK(licenseId);
  } else {
    // iOS初始化代码（需单独实现）
  }
};

// 人脸检测方法
export const detectFace = async () => {
  try {
    // 1. 选择图片
    const result = await launchImageLibrary({ mediaType: 'photo' });
    if (result.didCancel) return;

    const uri = result.assets[0].uri;
    // 2. 将图片转为Base64（百度要求）
    const base64Data = await RNFS.readFile(uri, 'base64');

    // 3. 调用百度API（需自行实现网络请求）
    const apiKey = "YOUR_API_KEY";
    const secretKey = "YOUR_SECRET_KEY";
    const response = await fetch(
      `https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=${await getAccessToken(apiKey, secretKey)}`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          image: base64Data,
          image_type: 'BASE64',
          face_field: 'age,beauty,expression'
        })
      }
    );

    const data = await response.json();
    return data.result;
  } catch (error) {
    console.error("人脸检测失败:", error);
  }
};

// 获取百度API的Access Token
const getAccessToken = async (apiKey, secretKey) => {
  const response = await fetch(
    `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${secretKey}`,
    { method: 'POST' }
  );
  const data = await response.json();
  return data.access_token;
};