// Natural Voice API: đọc văn bản thành giọng nói, rồi chép file đó lại thành chữ và phụ đề.
// Java 11 trở lên, không cần thêm thư viện:  NATVOICE_API_KEY=nvk_... java NatVoice.java
// Windows với Java 11 đến 17: java -Dfile.encoding=UTF-8 NatVoice.java (nếu không, chữ tiếng Việt trong file bị đọc sai).
// Để khỏi cần thư viện, ví dụ đọc JSON bằng biểu thức chính quy; trong dự án thật hãy dùng Jackson hoặc Gson.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NatVoice {
    static final String API = System.getenv().getOrDefault("NATVOICE_API", "https://api.natvoice.com");
    static final String KEY = System.getenv("NATVOICE_API_KEY");
    static final HttpClient HTTP = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();

    public static void main(String[] args) throws Exception {
        System.setOut(new PrintStream(System.out, true, "UTF-8"));
        System.setErr(new PrintStream(System.err, true, "UTF-8"));
        List<String> speech = download(run("tts", "{\"text\":\"Xin chào, đây là giọng đọc tạo qua API.\",\"voice\":\"truc_ly\"}", null, null));
        System.out.println("Giọng đọc: " + speech);
        List<String> transcript = download(run("speech_to_text", "{\"language\":\"vi\"}", Path.of(speech.get(0)), "audio/mpeg"));
        System.out.println("Bản chép lời: " + transcript);
    }

    static HttpRequest.Builder request(String path) {
        return HttpRequest.newBuilder(URI.create(API + path)).header("Authorization", "Bearer " + KEY).timeout(Duration.ofMinutes(2));
    }

    /** Gửi yêu cầu; khi hỏi (GET) quá nhanh bị 429 thì chờ rồi thử lại. */
    static byte[] send(HttpRequest request) throws IOException, InterruptedException {
        for (int attempt = 0; ; attempt++) {
            HttpResponse<byte[]> response = HTTP.send(request, HttpResponse.BodyHandlers.ofByteArray());
            if (response.statusCode() == 429 && request.method().equals("GET") && attempt < 4) {
                Thread.sleep(15_000);
                continue;
            }
            if (response.statusCode() >= 300) {
                throw new IOException(response.statusCode() + ": " + new String(response.body(), StandardCharsets.UTF_8));
            }
            return response.body();
        }
    }

    /** Gửi một job (multipart/form-data), chờ xong, trả về JSON của job. */
    static String run(String tool, String params, Path file, String contentType) throws IOException, InterruptedException {
        String boundary = "natvoice-" + UUID.randomUUID();
        ByteArrayOutputStream body = new ByteArrayOutputStream();
        write(body, "--" + boundary + "\r\nContent-Disposition: form-data; name=\"tool\"\r\n\r\n" + tool + "\r\n");
        write(body, "--" + boundary + "\r\nContent-Disposition: form-data; name=\"params\"\r\n\r\n" + params + "\r\n");
        if (file != null) {
            write(body, "--" + boundary + "\r\nContent-Disposition: form-data; name=\"files\"; filename=\"" + file.getFileName() + "\"\r\n");
            write(body, "Content-Type: " + contentType + "\r\n\r\n");
            body.write(Files.readAllBytes(file));
            write(body, "\r\n");
        }
        write(body, "--" + boundary + "--\r\n");

        String job = text(send(request("/v1/jobs")
                .header("Content-Type", "multipart/form-data; boundary=" + boundary)
                .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray()))
                .build()));
        String id = field(job, "id");
        while (field(job, "status").equals("queued") || field(job, "status").equals("running")) {
            Thread.sleep(4_000); // mỗi lần hỏi cũng tính vào giới hạn 30 yêu cầu/phút của khóa
            job = text(send(request("/v1/jobs/" + id).build()));
        }
        if (!field(job, "status").equals("succeeded")) {
            throw new IOException(field(job, "error"));
        }
        return job;
    }

    /** Tải mọi file kết quả về thư mục hiện tại, trả về tên file. */
    static List<String> download(String job) throws IOException, InterruptedException {
        List<String> names = new ArrayList<>();
        Matcher outputs = Pattern.compile("\"(/v1/jobs/[^\"]+/files/([^\"/]+))\"").matcher(job);
        while (outputs.find()) {
            Files.write(Path.of(outputs.group(2)), send(request(outputs.group(1)).build()));
            names.add(outputs.group(2));
        }
        return names;
    }

    static String field(String json, String name) {
        Matcher m = Pattern.compile("\"" + name + "\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").matcher(json);
        return m.find() ? m.group(1) : "";
    }

    static String text(byte[] bytes) {
        return new String(bytes, StandardCharsets.UTF_8);
    }

    static void write(ByteArrayOutputStream out, String s) throws IOException {
        out.write(s.getBytes(StandardCharsets.UTF_8));
    }
}
