_nvim := "nvim --headless --noplugin -u tests/minimal_init.lua"
_init := "tests/minimal_init.lua"
_luacov := "tests/.rocks/bin/luacov"
min_coverage := "70"

# Default: run all pre-commit checks via lefthook
default:
    lefthook run pre-commit

# Launch nvim loaded with minimal_init.lua for manual interactive testing
# Note: no --noplugin so that plugin/*.lua in rtp (including this repo) are sourced
dev:
    nvim -u tests/minimal_init.lua

# Run all tests, or specific files: just test tests/foo_spec.lua tests/bar_spec.lua
test *files:
    #!/usr/bin/env bash
    set -euo pipefail
    if [ -z "{{files}}" ]; then
        {{_nvim}} \
          -c "lua require('plenary.test_harness').test_directory('tests/', {minimal_init='{{_init}}', sequential=true})" \
          -c "qa"
    else
        for file in {{files}}; do
            {{_nvim}} \
              -c "lua require('plenary.test_harness').test_file('${file}', {minimal_init='{{_init}}'})" \
              -c "qa"
        done
    fi

# Run all tests in a single process and generate a luacov report
coverage:
    #!/usr/bin/env bash
    set -euo pipefail
    rm -f tests/.luacov.stats.out tests/luacov.report.out
    # Single-process: all specs run inside one nvim → luacov collects complete data
    # VimLeavePre in minimal_init.lua flushes stats before cquit
    {{_nvim}} \
      -c "lua require('plenary.test_harness').test_directory('tests/', {minimal_init='{{_init}}', sequential=true})" \
      -c "qa"
    {{_luacov}}
    echo ""
    echo "=== Coverage report ==="
    awk '/^=+$/{found++} found>=3' tests/luacov.report.out

# Run coverage and fail if total is below min_coverage (default: 80%)
# Override: just check-coverage min_coverage=90
check-coverage min_coverage=min_coverage:
    #!/usr/bin/env bash
    set -euo pipefail
    just coverage
    total=$(awk '/^Total/{print $NF}' tests/luacov.report.out | tr -d '%')
    if [ -z "$total" ]; then
        echo "ERROR: could not parse Total line from tests/luacov.report.out" >&2
        exit 1
    fi
    echo ""
    if awk "BEGIN { exit ($total >= {{min_coverage}}) }"; then
        echo "FAIL: coverage ${total}% is below minimum {{min_coverage}}%" >&2
        exit 1
    fi
    echo "PASS: coverage ${total}% >= {{min_coverage}}%"

# Format all Lua files with stylua
fmt:
    stylua lua/ tests/

# Check formatting without modifying files
fmt-check:
    stylua --check lua/ tests/

# Lint with luacheck (only own source + spec files, not third-party deps)
lint:
    luacheck lua/ tests/ --exclude-files 'tests/.rocks/**'
