package Balaji.panel;

import android.content.Context;
import android.util.Log;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

public class RemoteUpdater {
    // ═══════════════════════════════════════════════════
    // EDIT THIS LINE: Point to your .php file
    // ═══════════════════════════════════════════════════
    private static final String SERVER_URL = "https://balajimods.com/api.php";

    public static void sync(Context context) {
        new Thread(() -> {
            try {
                URL url = new URL(SERVER_URL + "?action=manifest");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(10000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();

                    JSONObject json = new JSONObject(sb.toString());
                    
                    // Save the UI config to internal storage
                    File configFile = new File(context.getFilesDir(), "remote_config.json");
                    FileOutputStream fos = new FileOutputStream(configFile);
                    fos.write(json.getJSONObject("ui_config").toString().getBytes());
                    fos.close();

                    // Check for updated asset files (gh, ng, baja, etc)
                    File targetDir = new File(context.getFilesDir(), "remote_payloads");
                    if (!targetDir.exists()) targetDir.mkdirs();

                    JSONObject files = json.getJSONObject("files");
                    for (int i = 0; i < files.names().length(); i++) {
                        String filename = files.names().getString(i);
                        String remoteHash = files.getString(filename);
                        File localFile = new File(targetDir, filename);

                        if (!remoteHash.equals(getMD5(localFile))) {
                            downloadFile(SERVER_URL + "?action=download&file=" + filename, localFile);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e("RemoteUpdater", "Sync failed", e);
            }
        }).start();
    }

    private static void downloadFile(String urlStr, File target) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            FileOutputStream out = new FileOutputStream(target);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
            out.close();
            in.close();
        }
    }

    private static String getMD5(File file) {
        if (!file.exists()) return "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = fis.read(buffer)) > 0) md.update(buffer, 0, len);
            fis.close();
            StringBuilder sb = new StringBuilder();
            for (byte b : md.digest()) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (Exception e) { return ""; }
    }
}