import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PUBGConfigEnhancer {
    private static final String TAG = "PUBGConfigEnhancer";
    private static final String PUBG_CONFIG_PATH = 
            Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/Android/data/com.tencent.tmgp.pubgmhd/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Config/Android/";

    private final Context mContext;

    public PUBGConfigEnhancer(Context context) {
        this.mContext = context;
    }

    public Map<String, String> readConfigFile(String fileName) {
        File configFile = new File(PUBG_CONFIG_PATH + fileName);
        if (!configFile.exists() || !configFile.isFile()) {
            Log.e(TAG, "File not exist: " + configFile.getAbsolutePath());
            return null;
        }

        Map<String, String> configMap = new HashMap<>();
        String currentSection = "";
        try (BufferedReader br = new BufferedReader(new FileReader(configFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.startsWith(";") || line.isEmpty()) {
                    continue;
                }
                if (line.startsWith("[") && line.endsWith("]")) {
                    currentSection = line.substring(1, line.length() - 1);
                    continue;
                }
                if (line.contains("=")) {
                    String[] keyValue = line.split("=", 2);
                    if (keyValue.length == 2) {
                        String key = currentSection + "#" + keyValue[0].trim();
                        String value = keyValue[1].trim();
                        configMap.put(key, value);
                        Log.d(TAG, "Read config: " + key + " = " + value);
                    }
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Read config failed: ", e);
            return null;
        }
        return configMap;
    }

    public boolean modifyConfigValue(String fileName, String section, String key, String newValue) {
        File configFile = new File(PUBG_CONFIG_PATH + fileName);
        if (!configFile.exists() || !configFile.isFile()) {
            Log.e(TAG, "File not exist: " + configFile.getAbsolutePath());
            return false;
        }

        File tempFile = new File(PUBG_CONFIG_PATH + "temp_" + fileName);
        String targetSection = "[" + section + "]";
        boolean sectionFound = false;
        boolean keyModified = false;

        try (BufferedReader br = new BufferedReader(new FileReader(configFile));
             BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile))) {

            String line;
            while ((line = br.readLine()) != null) {
                String originalLine = line;
                line = line.trim();

                if (line.equals(targetSection)) {
                    sectionFound = true;
                    bw.write(originalLine);
                    bw.newLine();
                    while ((line = br.readLine()) != null) {
                        String innerLine = line;
                        line = line.trim();
                        if (line.startsWith("[") && line.endsWith("]")) {
                            if (!keyModified) {
                                bw.write(key + "=" + newValue);
                                bw.newLine();
                                keyModified = true;
                            }
                            bw.write(innerLine);
                            bw.newLine();
                            break;
                        }
                        if (line.startsWith(key + "=")) {
                            bw.write(key + "=" + newValue);
                            bw.newLine();
                            keyModified = true;
                        } else {
                            bw.write(innerLine);
                            bw.newLine();
                        }
                    }
                    if (!keyModified && sectionFound) {
                        bw.write(key + "=" + newValue);
                        bw.newLine();
                        keyModified = true;
                    }
                } else {
                    bw.write(originalLine);
                    bw.newLine();
                }
            }

            if (!sectionFound) {
                bw.write(targetSection);
                bw.newLine();
                bw.write(key + "=" + newValue);
                bw.newLine();
                keyModified = true;
            }

        } catch (IOException e) {
            Log.e(TAG, "Modify config failed: ", e);
            tempFile.delete();
            return false;
        }

        if (configFile.delete() && tempFile.renameTo(configFile)) {
            Log.d(TAG, "Config modified successfully");
            return true;
        } else {
            Log.e(TAG, "Replace config file failed");
            tempFile.delete();
            return false;
        }
    }
}