"""
Module for QAQC master log parser.
"""
module QaqcMasterLog

using Dates

"""
Metadata(not results) of QAQC run from master log.

# Fields
- `timestamp`: in UTC
- `runid`
- `shifters`
- `shiftscript_version::VersionNumber`
"""
struct QaqcMasterLogMetadata
    timestamp::DateTime
    runid::Int64
    shifters::String
    shiftscript_version::VersionNumber
end

"""
    parse_master_log(logfile::AbstractString)

Parse master log.
If the `logfile` is empty, return `nothing`.

# Examples

```jldoctest
julia> PSBoardDataBase.QaqcMasterLog.parse_master_log("../test/input/log/57_long.log")
PSBoardDataBase.QaqcMasterLog.QaqcMasterLogMetadata(Dates.DateTime("2024-07-26T10:33:05"), 57, "Otsubo", v"1.0.2")

```
"""
function parse_master_log(logfile::AbstractString)
    open(logfile) do f
        first_line = readline(f)
        if isempty(first_line)
            @debug "file $(logfile) is empty"
            @assert read(logfile) |> isempty
            return nothing
        end
        shiftscript_version = split(first_line) |> last |> VersionNumber

        @assert readline(f) |> contains("-----")

        date_line = readline(f)
        @assert date_line |> split |> first |> contains("Date")
        date_part = split(date_line) |> last
        datetime, timezone = split(date_part, '+')
        @assert timezone == "0000" "Unexpected timestamp: timezone is not UTC"
        # Maybe use ZonedDateTime here
        timestamp = datetime |> DateTime

        runid_line = readline(f)
        runid = parse(Int64, runid_line |> split |> last)

        shifters_line = readline(f)
        @assert shifters_line |> split |> first |> contains("Shifters")
        shifters = shifters_line |> split |> last

        return QaqcMasterLogMetadata(timestamp, runid, shifters, shiftscript_version)
    end
end

end
