#!/usr/bin/swift

import Foundation

private func checkCaptureGroups() -> Bool {
    let fileURL = URL(fileURLWithPath: "./Sources/XcbeautifyLib/CaptureGroups.swift")
    let content: String
    do {
        content = try String(contentsOf: fileURL, encoding: .utf8)
    } catch {
        print("Error: Failed to read \(fileURL.path): \(error)")
        exit(EXIT_FAILURE)
    }

    let lines = content
        .split(whereSeparator: \.isNewline)
        .compactMap { line -> String? in
            guard line.starts(with: "struct") else { return nil }
            return line.lowercased()
        }

    return lines == lines.sorted()

}

private func checkParserRegistration() -> Bool {
    let fileURL = URL(fileURLWithPath: "./Sources/XcbeautifyLib/Parser.swift")
    let content: String
    do {
        content = try String(contentsOf: fileURL, encoding: .utf8)
    } catch {
        print("Error: Failed to read \(fileURL.path): \(error)")
        return false
    }

    let lines = content
        .split(whereSeparator: \.isNewline)

    guard let startIndex = lines.firstIndex(where: { $0.contains("// START SORT") }) else {
        print("Error: '// START SORT' marker not found in Parser.swift.")
        return false
    }
    guard let endIndex = lines.firstIndex(where: { $0.contains("// END SORT") }) else {
        print("Error: '// END SORT' marker not found in Parser.swift.")
        return false
    }

    let filteredLines = Array(lines[(startIndex + 1)..<endIndex])
        .map { $0.lowercased() }

    return filteredLines == filteredLines.sorted()
}

var unsorted = false

if !checkCaptureGroups() {
    print("Found unsorted CaptureGroup(s) in CaptureGroups.swift.")
    unsorted = true
}

if !checkParserRegistration() {
    print("Found unsorted CaptureGroup(s) in Parser.swift.")
    unsorted = true
}

if unsorted {
    exit(EXIT_FAILURE)
} else {
    exit(EXIT_SUCCESS)
}
