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

import java.util.LinkedHashMap;
import java.util.Map;
import org.json.JSONObject;

/** Opt-in, invocation-local host diagnostics. No node/evidence cache or production logging. */
final class JevReviewProfile implements AutoCloseable {
    private static final ThreadLocal<JevReviewProfile> ACTIVE=new ThreadLocal<JevReviewProfile>();
    private final Map<String,long[]> phases=new LinkedHashMap<String,long[]>();
    private final JevReviewProfile previous;
    JevReviewProfile(){previous=ACTIVE.get();ACTIVE.set(this);}
    static long start(){return ACTIVE.get()==null?0:System.nanoTime();}
    static void end(String phase,long start){if(start!=0)add(phase,System.nanoTime()-start,1);}
    static void add(String phase,long nanos,long count){
        JevReviewProfile p=ACTIVE.get();if(p==null)return;
        long[] v=p.phases.get(phase);if(v==null){v=new long[2];p.phases.put(phase,v);}v[0]+=nanos;v[1]+=count;
    }
    JSONObject snapshot(){
        JSONObject out=new JSONObject();
        for(Map.Entry<String,long[]> e:phases.entrySet())outPut(out,e.getKey(),e.getValue());
        return out;
    }
    private static void outPut(JSONObject out,String key,long[] value){try{
        out.put(key,new JSONObject().put("ns",value[0]).put("count",value[1]));
    }catch(org.json.JSONException e){throw new IllegalStateException(e);}}
    public void close(){ACTIVE.set(previous);}
}
