import Foundation

@main
enum GenerateVersionTool {
    static func main() throws {
        guard CommandLine.arguments.count == 3 else {
            fputs("Usage: GenerateVersionTool <repo-dir> <output-path>\n", stderr)
            exit(1)
        }
        let repoDir = CommandLine.arguments[1]
        let outputPath = CommandLine.arguments[2]

        let version = gitDescribe(in: repoDir) ?? "unknown"
        let escaped =
            version
            .replacingOccurrences(of: "\\", with: "\\\\")
            .replacingOccurrences(of: "\"", with: "\\\"")

        let swift = """
            // Auto-generated by GenerateVersion plugin — do not edit.
            enum GeneratedVersion {
                static let value = "\(escaped)"
            }

            """
        try swift.write(toFile: outputPath, atomically: true, encoding: .utf8)
    }

    static func gitDescribe(in dir: String) -> String? {
        let process = Process()
        process.executableURL = URL(fileURLWithPath: "/usr/bin/git")
        process.arguments = ["-C", dir, "describe", "--tags", "--always"]
        let pipe = Pipe()
        process.standardOutput = pipe
        process.standardError = FileHandle.nullDevice
        do {
            try process.run()
            process.waitUntilExit()
            guard process.terminationStatus == 0 else { return nil }
            let data = pipe.fileHandleForReading.readDataToEndOfFile()
            return String(data: data, encoding: .utf8)?
                .trimmingCharacters(in: .whitespacesAndNewlines)
                .replacingOccurrences(of: "^v", with: "", options: .regularExpression)
        } catch {
            return nil
        }
    }
}
