import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {
    var statusItem: NSStatusItem?
    var scriptProcess: Process?

    func applicationDidFinishLaunching(_ notification: Notification) {
        app.setActivationPolicy(.prohibited)

        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

        if let button = statusItem?.button {
            let bundle = Bundle.main
            var icon: NSImage?
            if let url = bundle.url(forResource: "MenuBarIcon@2x", withExtension: "png"),
               let img = NSImage(contentsOf: url) {
                img.isTemplate = true
                icon = img
            } else if let url = bundle.url(forResource: "MenuBarIcon", withExtension: "png"),
                      let img = NSImage(contentsOf: url) {
                img.isTemplate = true
                icon = img
            }
            if let icon = icon {
                button.image = icon
            } else {
                button.title = "☁"
            }
        }

        let menu = NSMenu()
        let openLog = NSMenuItem(title: "Open Log", action: #selector(openLog), keyEquivalent: "")
        openLog.target = self
        menu.addItem(openLog)
        menu.addItem(NSMenuItem.separator())
        let quit = NSMenuItem(title: "Quit Photon Uploader", action: #selector(quitApp), keyEquivalent: "q")
        quit.target = self
        menu.addItem(quit)
        statusItem?.menu = menu

        launchScript()
    }

    func launchScript() {
        guard let resourcePath = Bundle.main.resourcePath else { return }
        let scriptDir = (resourcePath as NSString).deletingLastPathComponent
        let scriptPath = "\(scriptDir)/MacOS/upload.sh"

        let proc = Process()
        proc.executableURL = URL(fileURLWithPath: "/bin/bash")
        proc.arguments = [scriptPath, "--background"]
        try? proc.run()
        scriptProcess = proc
    }

    @objc func openLog() {
        let logPath = (NSHomeDirectory() as NSString)
            .appendingPathComponent("Documents/Photon/photon-upload.log")
        NSWorkspace.shared.open(URL(fileURLWithPath: logPath))
    }

    @objc func quitApp() {
        scriptProcess?.terminate()
        app.terminate(nil)
    }
}

let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.run()
