package jp.ac.dendai.im.ai;

// JSON 用のライブラリ
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
// Google の生成AI用ライブラリ
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;

/**
 * Gemini の出力結果を JSON形式で取得
 * (Jackson の JsonNode を使用)
 */
public class GeminiJson {
    public static final String apiKey = "(your-api-key)";    // 自分のAPIキーを記入
    public static final String model = "gemini-2.0-flash";
    public static void main(String[] args) {
        // Gemini クライアントをインスタンス化
        Client client = Client.builder().apiKey(apiKey).build();

        // 生成のための設定 config を用意
        GenerateContentConfig config =
            GenerateContentConfig.builder()
                .responseMimeType("application/json")    // JSONで返答
                .candidateCount(1)
                .maxOutputTokens(1024)
                .build();

        // 生成
        String text =
                "次の文章に含まれる8つの基本感情を分析し、" +
                "各感情の強さを1-10の値で出力してください: " +
                "わーい。";
                // "がーん...";
                // "眠すぎる。";
        GenerateContentResponse response =
                client.models.generateContent(    model, text, config);

        // 返答のテキスト部分を text() で取得して表示(確認用)
        System.out.println("返答: " + response.text());
        System.out.println();

        // 返答のテキスト部分を text() で取得し、JSON として処理
        try {
            // データをツリーにマッピングし rootノードを JsonNode として取得
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootArray = mapper.readTree(response.text());

            // rootノードは感情オブジェクトの配列なので各要素を取得して表示
            for(JsonNode emotionObject: rootArray) {
                String emotion = emotionObject.get("emotion").asText();
                int strength = emotionObject.get("strength").asInt();
                System.out.println(emotion + " = " + strength);
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
