package com.android.commands.monkey.ape.jev;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.Properties;
import org.json.*;

/** Region-only device admission through the unchanged production protocol and transport. */
public final class RegionPreflight {
    public static void main(String[] args)throws Exception {
        boolean validate="--validate".equals(args[0]);Properties config=new Properties();
        try(InputStream in=new FileInputStream(args[validate?1:0])){config.load(in);}
        int maxBytes=Integer.parseInt(config.getProperty("ape.jev.maxRequestBytes"));
        String model=config.getProperty("ape.jev.model");
        JSONObject fixture=new JSONObject(new String(Files.readAllBytes(Paths.get(args[2])),StandardCharsets.UTF_8));
        JevRegionProtocol.Request request=JevRegionProtocol.snapshot("preflight-region",fixture.getJSONObject("state"),maxBytes,model);
        if(validate){System.out.println("Region VALID "+request.requestBytes+" bytes");return;}
        Path output=Paths.get(args[1]);Files.createDirectories(output);
        Files.write(output.resolve("request.json"),request.bodyJson.getBytes(StandardCharsets.UTF_8));
        try(JevTransport transport=new JevTransport(config.getProperty("ape.jev.endpoint"),JevProvider.token(config.getProperty("ape.jev.provider", "startlux")),1,"region")) {
            JevTransport.Call call=transport.submit(request.requestId,request.bodyJson,Integer.parseInt(config.getProperty("ape.jev.timeoutMs")),Math.max(16384,maxBytes));
            if(call==null)throw new IllegalStateException("Region preflight queue full");
            JevTransport.Result response=call.await();
            JSONObject receipt=JevRegistry.fields("request_id",request.requestId,"request_bytes",request.requestBytes,"http_status",response.httpStatus,
                "error",response.error==null?JSONObject.NULL:response.error,"raw_response",response.raw==null?JSONObject.NULL:response.raw,"latency_ns",response.latencyNanos());
            Files.write(output.resolve("transport.json"),receipt.toString(2).getBytes(StandardCharsets.UTF_8));
            if(response.error!=null)throw new IllegalStateException(response.error);
            Files.write(output.resolve("validated-response.json"),JevRegionProtocol.fromProvider(response.raw,request).toJson().toString(2).getBytes(StandardCharsets.UTF_8));
            System.out.println("Region preflight PASS");
        }
    }
}
