package com.theaimartco.taim.accessdriver;
import android.app.*;
import android.content.*;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.*;
import android.view.*;
import android.view.accessibility.*;
import org.json.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;

/** Dedicated fixture only: grants no sensor access beyond its own permission-dialog tests. */
public final class AccessDriver extends Instrumentation {
    private static final String PKG="com.theaimartco.taim.platformprobe",CAMERA="android.permission.CAMERA";
    private Activity activity;private Object permissions;private int checks;private String mode="suite";private boolean production;
    @Override public void onCreate(Bundle args){super.onCreate(args);if(args!=null){mode=args.getString("mode","suite");production="true".equals(args.getString("production"));}start();}
    private Object field(Object owner,String name)throws Exception{Class<?> type=owner.getClass();while(type!=null){try{Field f=type.getDeclaredField(name);f.setAccessible(true);return f.get(owner);}catch(NoSuchFieldException e){type=type.getSuperclass();}}throw new NoSuchFieldException(name);}
    private Object invoke(Object owner,String name,Class<?>[] types,Object... arguments){Object[] value=new Object[1];runOnMainSync(()->{try{Method method=owner.getClass().getDeclaredMethod(name,types);method.setAccessible(true);value[0]=method.invoke(owner,arguments);}catch(Exception error){throw new RuntimeException(error);}});return value[0];}
    private JSONObject status(String name)throws Exception{return ((JSONArray)invoke(permissions,"status",new Class<?>[]{String[].class},(Object)new String[]{name})).getJSONObject(0);}
    private void require(boolean condition,String message){if(!condition)throw new AssertionError(message);checks++;android.util.Log.i("TaimAccessTest","check "+checks+": "+message);}
    private AccessibilityNodeInfo findIn(AccessibilityNodeInfo root,String label){if(root==null)return null;if(label.contentEquals(root.getText()==null?"":root.getText())||label.contentEquals(root.getHintText()==null?"":root.getHintText())||label.contentEquals(root.getContentDescription()==null?"":root.getContentDescription()))return root;for(int i=0;i<root.getChildCount();i++){AccessibilityNodeInfo n=findIn(root.getChild(i),label);if(n!=null)return n;}return null;}
    private AccessibilityNodeInfo find(String label){return findIn(getUiAutomation().getRootInActiveWindow(),label);}
    private AccessibilityNodeInfo waitNode(String label)throws Exception{long end=SystemClock.uptimeMillis()+15000;do{AccessibilityNodeInfo node=find(label);if(node!=null)return node;Thread.sleep(100);}while(SystemClock.uptimeMillis()<end);throw new AssertionError("Missing "+label);}
    private void waitSelection(int start,int end)throws Exception{long until=SystemClock.uptimeMillis()+7000;do{AccessibilityNodeInfo n=waitNode("Probe input");if(n.getTextSelectionStart()==start && n.getTextSelectionEnd()==end)return;Thread.sleep(100);}while(SystemClock.uptimeMillis()<until);throw new AssertionError("Selection mismatch "+start+":"+end);}
    private void select(int start,int end)throws Exception{Bundle args=new Bundle();args.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT,start);args.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT,end);if(!waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_SET_SELECTION,args))throw new AssertionError("Selection rejected");waitSelection(start,end);}
    private java.util.List<AccessibilityNodeInfo> denialButtons(AccessibilityNodeInfo root){java.util.ArrayList<AccessibilityNodeInfo> buttons=new java.util.ArrayList<>();for(String id:new String[]{"permission_deny_button","permission_deny_and_dont_ask_again_button"})buttons.addAll(root.findAccessibilityNodeInfosByViewId("com.android.permissioncontroller:id/"+id));return buttons;}
    private void deny(int code)throws Exception{invoke(permissions,"begin",new Class<?>[]{int.class,String[].class},code,new String[]{CAMERA});runOnMainSync(()->activity.requestPermissions(new String[]{CAMERA},code));long until=SystemClock.uptimeMillis()+12000;boolean clicked=false;while(SystemClock.uptimeMillis()<until){AccessibilityNodeInfo root=getUiAutomation().getRootInActiveWindow();if(root!=null)for(AccessibilityNodeInfo node:denialButtons(root)){if(node.performAction(AccessibilityNodeInfo.ACTION_CLICK)){clicked=true;break;}}if(clicked)break;Thread.sleep(100);}if(!clicked)throw new AssertionError("Permission denial UI missing");until=SystemClock.uptimeMillis()+7000;while((Boolean)invoke(permissions,"busy",new Class<?>[0]) && SystemClock.uptimeMillis()<until)Thread.sleep(100);if((Boolean)invoke(permissions,"busy",new Class<?>[0]))throw new AssertionError("Permission callback missing");waitForIdleSync();Thread.sleep(200);}
    private View virtual(View root){if(root.getClass().getSimpleName().equals("TaimAccessibility"))return root;if(root instanceof ViewGroup){ViewGroup g=(ViewGroup)root;for(int i=0;i<g.getChildCount();i++){View result=virtual(g.getChildAt(i));if(result!=null)return result;}}return null;}
    private JSONObject node(int id,Integer parent,String role,String name,int state)throws Exception{return new JSONObject().put("id",id).put("parent",parent==null?JSONObject.NULL:parent).put("role",role).put("name",name).put("state",state).put("actions",0).put("bounds",new JSONArray(new int[]{0,0,100,40}));}
    private String scene(long revision,JSONArray nodes)throws Exception{return new JSONObject().put("revision",revision).put("tree",new JSONObject().put("clip",new JSONArray(new int[]{0,0,300,300})).put("nodes",nodes)).toString();}
    @Override public void onStart(){Bundle result=new Bundle();int code=Activity.RESULT_CANCELED;try{
        activity=startActivitySync(new Intent(Intent.ACTION_MAIN).setComponent(new ComponentName(PKG,"com.theaimartco.taim.TaimProbeActivity")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));waitNode("Count: 0");permissions=field(field(activity,"services"),"permissionManager");
        if(mode.equals("history")){JSONObject before=status(CAMERA);require(before.getBoolean("settingsRequired") && before.getBoolean("requestedBefore"),"Denial history survives a new process");getUiAutomation().grantRuntimePermission(PKG,CAMERA);JSONObject granted=status(CAMERA);require(granted.getBoolean("granted") && !granted.getBoolean("settingsRequired"),"Settings grant clears denial evidence");}
        else if(mode.equals("revoked")){JSONObject revoked=status(CAMERA);require(!revoked.getBoolean("granted") && revoked.getBoolean("canAskAgain") && !revoked.getBoolean("settingsRequired"),"Revocation after observed grant does not reuse stale denial");}
        else {
            activity.getSharedPreferences("taim.permissions.v1",Context.MODE_PRIVATE).edit().clear().commit();
            JSONObject normal=status("android.permission.INTERNET");require(normal.getBoolean("granted") && !normal.getBoolean("canAskAgain"),"Normal permission needs no dialog");
            require(status("android.permission.RECORD_AUDIO").getString("state").equals("notDeclared"),"Undeclared permission distinguished");
            require(status("android.permission.TAIM_UNKNOWN_PERMISSION").getString("state").equals("unavailable"),"Unknown OS permission distinguished");
            JSONObject first=status(CAMERA);require(first.getString("state").equals("notRequested") && first.getBoolean("canAskAgain") && !first.getBoolean("shouldShowRationale"),"First request is not permanently denied");
            invoke(permissions,"begin",new Class<?>[]{int.class,String[].class},6100,new String[]{CAMERA});invoke(permissions,"finish",new Class<?>[]{int.class,String[].class,int[].class},6100,new String[0],new int[0]);JSONObject cancelled=status(CAMERA);require(cancelled.getString("state").equals("cancelled") && cancelled.getBoolean("canAskAgain"),"Empty callback is cancellation");
            deny(6101);JSONObject denied=status(CAMERA);require(denied.getString("state").equals("denied") && denied.getBoolean("shouldShowRationale") && denied.getBoolean("canAskAgain"),"First real denial remains requestable");
            deny(6102);JSONObject blocked=status(CAMERA);require(blocked.getBoolean("settingsRequired") && !blocked.getBoolean("canAskAgain"),"Repeated denial without rationale routes to settings");
            require(((String[])invoke(permissions,"requestable",new Class<?>[]{String[].class},(Object)new String[]{CAMERA})).length==0,"Blocked permission is not prompted repeatedly");
            waitNode("Permissions observed");require(true,"Permission changes reach the typed Rust event stream");
            for(String kind:new String[]{"overlay","writeSettings","installPackages","allFiles","exactAlarms","batteryOptimization","fullScreenIntent"}){JSONObject value=(JSONObject)invoke(permissions,"special",new Class<?>[]{String.class,boolean.class},kind,false);if(!value.has("supported")||!value.has("granted"))throw new AssertionError("Special access status invalid");}require(true,"Special-access statuses use separate APIs");
            Bundle text=new Bundle();text.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE,"A🌍नमस्ते");require(waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_SET_TEXT,text),"Accessibility text update accepted");waitNode("Input: A🌍नमस्ते");
            select(1,3);require(true,"UTF16 selection preserves an astral character");
            require(waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_COPY),"Accessibility copy dispatch");long until=SystemClock.uptimeMillis()+5000;android.content.ClipboardManager clipboard=activity.getSystemService(android.content.ClipboardManager.class);while((clipboard.getPrimaryClip()==null || !"🌍".contentEquals(clipboard.getPrimaryClip().getItemAt(0).getText())) && SystemClock.uptimeMillis()<until)Thread.sleep(100);if(clipboard.getPrimaryClip()==null || !"🌍".contentEquals(clipboard.getPrimaryClip().getItemAt(0).getText()))throw new AssertionError("Copy changed selected Unicode");
            require(waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_CUT),"Accessibility cut dispatch");waitNode("Input: Aनमस्ते");
            require(waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_PASTE),"Accessibility paste dispatch");waitNode("Input: A🌍नमस्ते");
            if(production){
                select(1,3);final boolean[] accepted=new boolean[2];runOnMainSync(()->{try{android.content.ClipboardManager clipboardManager=activity.getSystemService(android.content.ClipboardManager.class);clipboardManager.setPrimaryClip(android.content.ClipData.newPlainText("Taim fixture","marker"));View view=virtual(activity.getWindow().getDecorView());Map<?,?> map=(Map<?,?>)field(view,"nodes");int target=-1;for(Object raw:map.values()){JSONObject node=(JSONObject)raw;if(node.optString("name").equals("Probe input"))target=node.getInt("id");}Bundle selection=new Bundle();selection.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT,0);selection.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT,1);AccessibilityNodeProvider provider=view.getAccessibilityNodeProvider();accepted[0]=provider.performAction(target,AccessibilityNodeInfo.ACTION_COPY,null);accepted[1]=provider.performAction(target,AccessibilityNodeInfo.ACTION_SET_SELECTION,selection);}catch(Exception error){throw new RuntimeException(error);}});waitSelection(0,1);long copiedUntil=SystemClock.uptimeMillis()+5000;while((clipboard.getPrimaryClip()==null || !"🌍".contentEquals(clipboard.getPrimaryClip().getItemAt(0).getText())) && SystemClock.uptimeMillis()<copiedUntil)Thread.sleep(100);require(accepted[0] && accepted[1] && clipboard.getPrimaryClip()!=null && "🌍".contentEquals(clipboard.getPrimaryClip().getItemAt(0).getText()),"Copy precedes a later selection in the same semantic batch");
            }
            select(0,0);Bundle movement=new Bundle();movement.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT,AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER);waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,movement);waitSelection(1,1);waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,movement);waitSelection(3,3);require(true,"Character movement does not split surrogate pairs");
            Bundle invalid=new Bundle();invalid.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT,99999);invalid.putInt(AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT,99999);require(!waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_SET_SELECTION,invalid),"Invalid selection rejected");
            require(waitNode("Probe input").performAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS),"Accessibility keyboard focus release");Thread.sleep(200);
            AccessibilityNodeInfo secret=waitNode("Probe password");require(secret.isPassword() && secret.getText()==null && !secret.getActionList().contains(AccessibilityNodeInfo.AccessibilityAction.ACTION_COPY) && !secret.getActionList().contains(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_SELECTION),"Secure field does not expose text operations");
            if(production){
                JSONObject workSpec=new JSONObject().put("persisted",true).put("charging",false).put("batteryNotLow",false).put("storageNotLow",false).put("backoff",10000).put("backoffPolicy","linear").put("network","none").put("interval",JSONObject.NULL);JSONObject row=new JSONObject().put("id",1).put("generation","fixture").put("earliest",0).put("spec",workSpec);
                Class<?> work=activity.getClassLoader().loadClass("com.theaimartco.taim.TaimWork");Method build=work.getDeclaredMethod("build",Context.class,JSONObject.class);build.setAccessible(true);boolean bootDenied=false;try{build.invoke(null,activity,row);}catch(java.lang.reflect.InvocationTargetException error){bootDenied=error.getCause() instanceof SecurityException;}workSpec.put("persisted",false);Object transientJob=build.invoke(null,activity,row);require(bootDenied && transientJob instanceof android.app.job.JobInfo && !((android.app.job.JobInfo)transientJob).isPersisted(),"Persisted jobs require explicit boot permission; transient jobs do not");
                View view=virtual(activity.getWindow().getDecorView());final android.view.inputmethod.InputConnection[] connection=new android.view.inputmethod.InputConnection[1];
                runOnMainSync(()->{try{Map<?,?> map=(Map<?,?>)field(view,"nodes");int target=-1;for(Object raw:map.values()){JSONObject node=(JSONObject)raw;if(node.optString("name").equals("Probe password"))target=node.getInt("id");}android.util.SparseArray<android.view.autofill.AutofillValue> values=new android.util.SparseArray<>();values.put(target,android.view.autofill.AutofillValue.forText("test-only-autofill"));view.autofill(values);}catch(Exception error){throw new RuntimeException(error);}});waitNode("Secure autofill passed");
                runOnMainSync(()->{try{connection[0]=((android.widget.EditText)field(activity,"editor")).onCreateInputConnection(new android.view.inputmethod.EditorInfo());}catch(Exception error){throw new RuntimeException(error);}});
                final boolean[] outcome=new boolean[1];runOnMainSync(()->outcome[0]=connection[0].performContextMenuAction(android.R.id.selectAll));require(outcome[0],"Secure IME can select all without exposing text");Thread.sleep(250);
                runOnMainSync(()->outcome[0]=connection[0].finishComposingText());Thread.sleep(300);waitNode("Secure autofill passed");require(outcome[0],"Empty composition finish preserves selected password");
                runOnMainSync(()->{connection[0].closeConnection();connection[0].closeConnection();outcome[0]=connection[0].commitText("STALE_SHOULD_NOT_APPEAR",1);});require(!outcome[0],"Closed secure connection rejects stale writes");Thread.sleep(300);waitNode("Secure autofill passed");require(true,"Secure connection cleanup does not erase the password");
            }
            Class<?> type=activity.getClassLoader().loadClass("com.theaimartco.taim.TaimAccessibility"),host=activity.getClassLoader().loadClass("com.theaimartco.taim.TaimActivity");Constructor<?> constructor=type.getDeclaredConstructor(host);constructor.setAccessible(true);Object[] isolated=new Object[1];runOnMainSync(()->{try{isolated[0]=constructor.newInstance(activity);}catch(Exception e){throw new RuntimeException(e);}});Object bridge=isolated[0];AccessibilityNodeProvider provider=((View)bridge).getAccessibilityNodeProvider();
            JSONArray nodes=new JSONArray().put(node(1,null,"Group","Root",0)).put(node(2,1,"StaticText","Visible",0)).put(node(3,1,"SecureField","Secret",0).put("value",new JSONObject().put("text","NEVER_EXPOSE")).put("live",2)).put(node(4,1,"StaticText","Hidden",128));
            invoke(bridge,"publish",new Class<?>[]{String.class},scene(1,nodes));
            require(provider.createAccessibilityNodeInfo(4)==null && !provider.performAction(4,AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS,null),"Hidden nodes cannot receive accessibility focus");
            require(provider.findAccessibilityNodeInfosByText("Visible",3).isEmpty() && provider.findAccessibilityNodeInfosByText("Visible",1).size()==1,"Search respects subtree boundaries");
            require(provider.findAccessibilityNodeInfosByText("NEVER_EXPOSE",-1).isEmpty(),"Search never exposes secure values");
            require(provider.createAccessibilityNodeInfo(1).getChildCount()==2,"Hidden children excluded from hierarchy");
            JSONArray cycle=new JSONArray().put(node(5,6,"Group","Cycle",0)).put(node(6,5,"Group","Cycle",0));invoke(bridge,"publish",new Class<?>[]{String.class},scene(2,cycle));require(provider.createAccessibilityNodeInfo(2)!=null,"Cyclic snapshot rejected atomically");
            provider.performAction(2,AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS,null);nodes.getJSONObject(1).put("state",128);invoke(bridge,"publish",new Class<?>[]{String.class},scene(3,nodes));require(provider.findFocus(AccessibilityNodeInfo.FOCUS_ACCESSIBILITY)==null,"Hiding focused node clears accessibility focus");
            require(provider.createAccessibilityNodeInfo(3).getLiveRegion()==View.ACCESSIBILITY_LIVE_REGION_NONE,"Secure field never becomes a live announcement");
            require(!provider.performAction(3,AccessibilityNodeInfo.ACTION_CLICK,null),"Unadvertised action rejected locally");
        }
        result.putInt("checks",checks);result.putString("stream","Accessibility and permission "+mode+" passed\n");code=Activity.RESULT_OK;
    }catch(Throwable error){result.putInt("checks",checks);result.putString("stream","Access fixture failed: "+error+"\n");}finish(code,result);}
}
