package net.micode.notes.ui;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class AIActivity extends AppCompatActivity {
    private static final String API_KEY = "sk-wB84RdCHqMQBg1qB7aF65f9718054aE6A90b8085D8A92271";
    private static final String API_URL = "https://api.vveai.com/v1/chat/completions";
    private static final String MODEL = "gpt-4o";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 创建一个TextView
        TextView textView = new TextView(this);
        textView.setTextSize(24);
        textView.setPadding(16, 16, 16, 16);
        setContentView(textView);

        // 获取传递的内容
        String noteContent = getIntent().getStringExtra("new_content");

        // 执行异步任务
        new HttpRequestTask(textView).execute(noteContent);
    }

    private static class HttpRequestTask extends AsyncTask<String, Void, String> {
        private TextView textView;

        public HttpRequestTask(TextView textView) {
            this.textView = textView;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                return makeHttpRequest(params[0]);
            } catch (Exception e) {
                e.printStackTrace();
                return "Oops, something went wrong!";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
        }

        private String makeHttpRequest(String prompt) throws Exception {
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setDoOutput(true);
            String promptEscaped = prompt.replace("\n", "\\n");
            promptEscaped = promptEscaped.replace("\"","\\\"");
            String jsonInputString = String.format(
                    "{\"model\": \"%s\", \"messages\": [{\"role\": \"user\", \"content\": \"summarize the content followed in Chinese as short as possible: %s\"}], \"max_tokens\": 1000,\"stream\": false}",
                    MODEL, promptEscaped);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int code = connection.getResponseCode();
            BufferedReader br;
            if (100 <= code && code <= 399) {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            } else {
                br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"));
            }

            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            String jsonResponse = response.toString();
            JsonObject rootObject = JsonParser.parseString(jsonResponse).getAsJsonObject();

            // 获取 choices 数组中的第一个对象
            JsonArray choicesArray = rootObject.getAsJsonArray("choices");
            JsonObject firstChoice = choicesArray.get(0).getAsJsonObject();

            // 获取 message 对象中的 content 字段
            String contents = firstChoice.getAsJsonObject("message").get("content").getAsString();
            return "\n"+contents;//jsonInputString;
        }
    }
}