package com.craftlaunch.studio.mobile;

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.FileOutputStream;
import java.nio.charset.StandardCharsets;

@CapacitorPlugin(name = "CraftLaunchFiles")
public class CraftLaunchFilesPlugin extends Plugin {
    @PluginMethod
    public void saveTextFile(PluginCall call) {
        String fileName = call.getString("fileName");
        String contents = call.getString("contents");

        if (fileName == null || contents == null) {
            call.reject("fileName and contents are required");
            return;
        }

        try {
            File exportDir = new File(getContext().getCacheDir(), "ProjectCraft Pro");
            if (!exportDir.exists() && !exportDir.mkdirs()) {
                call.reject("Unable to create export directory");
                return;
            }

            File outputFile = new File(exportDir, safeFileName(fileName));
            try (FileOutputStream outputStream = new FileOutputStream(outputFile, false)) {
                outputStream.write(contents.getBytes(StandardCharsets.UTF_8));
            }

            JSObject result = new JSObject();
            result.put("uri", outputFile.toURI().toString());
            result.put("path", outputFile.getAbsolutePath());
            call.resolve(result);
        } catch (Exception error) {
            call.reject("Unable to save export file", error);
        }
    }

    private String safeFileName(String value) {
        String cleaned = value.trim()
            .replaceAll("[\\\\/:\\n\\r\\t]+", "-")
            .replaceAll("^[.\\- ]+|[.\\- ]+$", "");

        if (cleaned.isEmpty()) {
            return "projectcraft-pro-export.txt";
        }

        return cleaned.length() > 120 ? cleaned.substring(0, 120) : cleaned;
    }
}
