package com.android.commands.monkey.ape.jev;
import org.json.*;
import java.util.*;
import java.nio.file.*;
/** Offline frozen-method replay only. No transport, Provider or device objects. */
public class WitnessReplay {
 public static void main(String[] args)throws Exception {
  JSONArray inputs=new JSONArray(new String(Files.readAllBytes(Paths.get(args[0])),"UTF-8")),output=new JSONArray();
  for(int i=0;i<inputs.length();i++) {
   JSONObject input=inputs.getJSONObject(i);JSONArray hs=input.getJSONArray("history");
   Set<String> wanted=JevHistoryPairwiseProtocol.selectionFeatures(input.getJSONObject("candidate"));
   Map<String,Set<String>> features=new LinkedHashMap<String,Set<String>>();Map<String,Integer> scores=new LinkedHashMap<String,Integer>();
   for(int j=0;j<hs.length();j++) {JSONObject h=hs.getJSONObject(j);String id=h.getString("id");Set<String> fs=JevHistoryPairwiseProtocol.selectionFeatures(h.getJSONObject("control"));features.put(id,fs);
    int score=0;for(String f:fs)if(wanted.contains(f))score+=f.startsWith("label:")?100:f.startsWith("word:")?10:f.startsWith("resource_id:")?8:2;scores.put(id,score);
   }
   List<String> ranked=new ArrayList<String>(features.keySet());Collections.sort(ranked,(a,b)->Integer.compare(scores.get(b),scores.get(a)));
   List<String> selected=JevHistoryPairwiseProtocol.selectHistoryFeatures(wanted,features.keySet(),features);JSONArray rows=new JSONArray();
   for(int j=0;j<hs.length();j++) {JSONObject h=hs.getJSONObject(j);String id=h.getString("id");JSONArray hit=new JSONArray();int labels=0,words=0,resources=0,other=0;
    for(String f:features.get(id))if(wanted.contains(f)){hit.put(f);if(f.startsWith("label:"))labels+=100;else if(f.startsWith("word:"))words+=10;else if(f.startsWith("resource_id:"))resources+=8;else other+=2;}
    rows.put(new JSONObject().put("id",id).put("features",new JSONArray(features.get(id))).put("matched_features",hit).put("label_score",labels).put("word_score",words).put("resource_id_score",resources).put("other_score",other)
     .put("score",scores.get(id)).put("rank",ranked.indexOf(id)+1).put("selected",selected.contains(id)).put("raw_descriptor_complete",h.getBoolean("raw_descriptor_complete")).put("source",h));
   }
   output.put(new JSONObject().put("case",input.getString("case")).put("candidate_features",new JSONArray(wanted)).put("selected",new JSONArray(selected)).put("expected_selected",input.getJSONArray("expected_selected"))
    .put("selected_matches",new JSONArray(selected).toString().equals(input.getJSONArray("expected_selected").toString())).put("rows",rows));
  }
  Files.write(Paths.get(args[1]),output.toString(2).getBytes("UTF-8"));System.out.println("Offline Witness cases="+output.length());
 }
}
