

def is-windows [] {
    $nu.os-info | get "family" | str starts-with "windows"
}


def --wrapped run-cmd [...cmd: string] {
    print $"\n(ansi blue)Running(ansi reset) ($cmd | str join ' ')"
    let elapsed = timeit {|| ^($cmd | first) ...($cmd | skip 1)}
    print $"(ansi magenta)($cmd | first) took ($elapsed)(ansi reset)"
}


def flush-artifacts [
    build_dir: string, dirty: bool
] {
    if ($build_dir | path exists) {
        if $dirty == false {
            print $"(ansi yellow)Removing artifacts(ansi reset) ($build_dir)"
            rm -r $build_dir
        }
    }
}


# Build the docs.
#
# Note, there is no check against what
# version of doxygen is used.
def "nur docs" [
    --dirty (-d) # Do not flush previous build artifacts
    --open (-o) # Open the built docs in your default browser
] {
    let build_dir = "docs/html"
    flush-artifacts $build_dir $dirty
    cd docs
    run-cmd doxygen
    if $open {
        let root_pg = $nur.project-path | path join $"($build_dir)/index.html"
        start $root_pg
    }
}


def changed-files [] {
    let status = git status --short | lines
    if ($status | length) == 0 {
        print $"(ansi red)No file changes detected via (ansi cyan)`git status`(ansi reset)"
        print $"Perhaps you want to format all files? (ansi cyan)`nur fmt -a`"
        return []
    }
    let changed = (
        $status
        | each {$in | str trim | split column --regex '\s+' -n 2}
        | flatten
        | rename "state" "name"
    )
    # print $changed
    let result = (
        $changed
        | where {$in.state | split chars | each {$in in ['A' 'M' 'R']} | any {$in}}
        | get "name"
        | each {
            if ($in | str contains " -> ") {
                $in | parse "{a} -> {b}" | get "b" | $in.0
            } else { $in }
        }
    )
    # print $result
    $result
}


def get-clang-format-version [bin_name: string] {
    if (which $bin_name | is-empty) {
        null
    } else {
        let version = (
            ^$bin_name --version
            | split column ' '
            | values
            | flatten
            | last
        )
        print $"($bin_name) --version: ($version)"
        $version | parse "{major}.{minor}.{patch}"
    }
}


def match-version [
    bin_name: string,
    expected: string = "14",
    --throw
] {
    let version = get-clang-format-version $bin_name
    if ($version | is-empty) {
        if $throw {
            error make {
                msg: $"($bin_name) not found. Ensure it is installed and added to your PATH."
            }
        }
        false
    } else { 
        if ($version.major.0 == $expected) {
            true
        } else if $throw {
            error make {
                msg: $"Failed to find clang-format v($expected).x"
            }
        } else {
            false
        }
    }
}


# Run clang-format on C++ files.
#
# By default, only changed C++ sources are formatted (uses `git status`).
# The clang-format version is expected to be v14.
# If v14 is not found, then an error is thrown.
def "nur fmt" [
    --all (-a) # Format all C++ sources
] {
    let all_files = glob "**/*.{h,cpp,c,ino}" --exclude [
        "**/build/**"
        "utility/**"
        "clock-arch.*"
        "Dns.*"
    ] | path relative-to $nur.project-path
    let files = if $all {
        $all_files
    } else {
        let changes = changed-files
        (
            $all_files
            | where {
                ($in | path split) in (
                    $changes | each {$in | path split}
                )
            }
        )
    }

    let bin_name = if (is-windows) {
        let bin_name = "clang-format"
        let is_expected = match-version $bin_name --throw
        "clang-format"
    } else {
        let bin_name = "clang-format-14"
        let is_expected = match-version $bin_name
        if ($is_expected == false) {
            let bin_name = "clang-format"
            let is_expected = match-version $bin_name --throw
            $bin_name
        } else {
            $bin_name
        }
    }

    if ($files | length) > 0 {
        print $files
        let elapsed = timeit {|| $files | par-each {|f| ^$bin_name "-i" "--style" "file" $f}}
        print $"clang-format took ($elapsed) using parallelism!"
    }
    print $"(ansi blue)Applied clang-format to ($files | length) files(ansi reset)"
}
