package ai.z.chat;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

@CapacitorPlugin(name = "Installer")
public class InstallerPlugin extends Plugin {
    private static final String TAG = "InstallerPlugin";

    @PluginMethod
    public void installApk(PluginCall call) {
        String path = call.getString("path", "");
        if (path.isEmpty()) {
            call.reject("No path provided");
            return;
        }

        File apkFile = new File(path);
        if (!apkFile.exists()) {
            call.reject("APK file not found: " + path);
            return;
        }

        try {
            Context context = getContext();
            Uri apkUri = FileProvider.getUriForFile(
                context,
                context.getPackageName() + ".fileprovider",
                apkFile
            );

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            context.startActivity(intent);

            call.resolve(new JSObject()
                .put("installed", true)
                .put("path", apkFile.getAbsolutePath())
                .put("size", apkFile.length()));
        } catch (Exception e) {
            call.reject("Install failed: " + e.getMessage());
        }
    }

    @PluginMethod
    public void exportApk(PluginCall call) {
        String path = call.getString("path", "");
        String name = call.getString("name", "app.apk");
        if (path.isEmpty()) {
            call.reject("No path provided");
            return;
        }

        File apkFile = new File(path);
        if (!apkFile.exists()) {
            call.reject("APK file not found: " + path);
            return;
        }

        try {
            Context context = getContext();
            File outRoot = context.getExternalFilesDir(android.os.Environment.DIRECTORY_DOWNLOADS);
            if (outRoot == null) {
                outRoot = context.getFilesDir();
            }
            File outDir = new File(outRoot, "ZAI-Chat");
            if (!outDir.exists()) outDir.mkdirs();
            File outFile = new File(outDir, name);
            try (FileInputStream fis = new FileInputStream(apkFile);
                 FileOutputStream fos = new FileOutputStream(outFile)) {
                byte[] buf = new byte[8192];
                int r;
                while ((r = fis.read(buf)) > 0) fos.write(buf, 0, r);
            }
            call.resolve(new JSObject()
                .put("exported", true)
                .put("path", outFile.getAbsolutePath())
                .put("name", name));
        } catch (Exception e) {
            call.reject("Export failed: " + e.getMessage());
        }
    }

    @PluginMethod
    public void getDeviceInfo(PluginCall call) {
        JSObject info = new JSObject();
        info.put("sdk", Build.VERSION.SDK_INT);
        info.put("release", Build.VERSION.RELEASE);
        info.put("device", Build.DEVICE);
        info.put("model", Build.MODEL);
        info.put("manufacturer", Build.MANUFACTURER);
        info.put("abi", Build.SUPPORTED_ABIS.length > 0 ? Build.SUPPORTED_ABIS[0] : "unknown");
        info.put("package", getContext().getPackageName());
        info.put("filesDir", getContext().getFilesDir().getAbsolutePath());
        call.resolve(info);
    }

    @PluginMethod
    public void openFile(PluginCall call) {
        String path = call.getString("path", "");
        String mimeType = call.getString("mimeType", "*/*");
        if (path.isEmpty()) {
            call.reject("No path provided");
            return;
        }

        File file = new File(path);
        if (!file.exists()) {
            call.reject("File not found: " + path);
            return;
        }

        try {
            Context context = getContext();
            Uri uri = FileProvider.getUriForFile(
                context,
                context.getPackageName() + ".fileprovider",
                file
            );

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, mimeType);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            context.startActivity(intent);
            call.resolve(new JSObject().put("opened", true));
        } catch (Exception e) {
            call.reject("Open failed: " + e.getMessage());
        }
    }
}
