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

import java.net.*;
import java.io.*;
import org.json.*;

/** Device-side HTTPS content probe, separate from the APK METHOD stream and model service. */
public final class AppNetworkProbe {
    public static void main(String[] args)throws Exception {
        URL url=new URL(args[0]);int timeout=Integer.parseInt(args[1]);String proxy=args[2];
        if(!"https".equals(url.getProtocol()) || url.getUserInfo()!=null || !url.getHost().endsWith(".wikipedia.org"))
            throw new IllegalArgumentException("Expected credential-free Wikipedia HTTPS URL");
        Proxy route=Proxy.NO_PROXY;
        if(!"DIRECT".equals(proxy)) {
            int colon=proxy.lastIndexOf(':');route=new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxy.substring(0,colon),Integer.parseInt(proxy.substring(colon+1))));
        }
        HttpURLConnection c=(HttpURLConnection)url.openConnection(route);c.setConnectTimeout(timeout);c.setReadTimeout(timeout);
        // Require a real network request, while allowing Wikimedia's normal CDN caching.
        c.setUseCaches(false);c.setInstanceFollowRedirects(false);c.setRequestProperty("User-Agent","ape-jev-content-admission/1");
        long start=System.nanoTime();JSONObject result=new JSONObject();
        try {
            int code=c.getResponseCode();result.put("http_status",code);
            JSONObject headers=new JSONObject();
            for(String name:new String[]{"Server","Date","Retry-After","Content-Type","X-Cache","X-Cache-Status","X-Request-Id","Age"}) {
                String value=c.getHeaderField(name);if(value!=null)headers.put(name.toLowerCase(java.util.Locale.ROOT),value);
            }
            result.put("headers",headers);InputStream stream=code==200?c.getInputStream():c.getErrorStream();
            ByteArrayOutputStream bytes=new ByteArrayOutputStream();byte[] buffer=new byte[8192];int n;
            if(stream!=null)try{while((n=stream.read(buffer))!=-1){if(bytes.size()+n>2*1024*1024)throw new IOException("Content exceeds bound");bytes.write(buffer,0,n);}}finally{stream.close();}
            result.put("body",new String(bytes.toByteArray(),"UTF-8"));
        } finally{c.disconnect();}
        result.put("elapsed_ns",System.nanoTime()-start).put("wall_time_ms",System.currentTimeMillis());System.out.println(result.toString());
    }
}
