import Foundation
import Capacitor

@objc(CraftLaunchFilesPlugin)
public class CraftLaunchFilesPlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "CraftLaunchFilesPlugin"
    public let jsName = "CraftLaunchFiles"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "saveTextFile", returnType: CAPPluginReturnPromise)
    ]

    @objc func saveTextFile(_ call: CAPPluginCall) {
        guard let fileName = call.getString("fileName"), let contents = call.getString("contents") else {
            call.reject("fileName and contents are required")
            return
        }

        do {
            let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let exportFolder = documentsUrl.appendingPathComponent("ProjectCraft Pro", isDirectory: true)
            try FileManager.default.createDirectory(at: exportFolder, withIntermediateDirectories: true)

            let fileUrl = exportFolder.appendingPathComponent(safeFileName(fileName), isDirectory: false)
            try contents.write(to: fileUrl, atomically: true, encoding: .utf8)

            call.resolve([
                "uri": fileUrl.absoluteString,
                "path": fileUrl.path
            ])
        } catch {
            call.reject("Unable to save export file", nil, error)
        }
    }

    private func safeFileName(_ value: String) -> String {
        let blockedCharacters = CharacterSet(charactersIn: "/\\:\n\r\t")
        let cleaned = value
            .components(separatedBy: blockedCharacters)
            .filter { !$0.isEmpty }
            .joined(separator: "-")
            .trimmingCharacters(in: CharacterSet(charactersIn: ". -"))

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

        return String(cleaned.prefix(120))
    }
}
