!> Build/version identity for the solver.
!!
!! `solver_version` is the static manifest copy — keep it equal to the
!! `version` field in `fpm.toml`; release preflight (`scripts/release.sh`)
!! verifies both against the tag.  `git_describe` comes from the checked-in
!! include `version_describe.inc`, which holds an empty string in the
!! repository and is overwritten by `scripts/gen_version_describe.sh` in
!! release builds (the include is regenerated, never committed with a
!! non-empty value).
module version_info
  implicit none
  private
  public :: solver_version, solver_build, handle_version_flag

  !> Static manifest version (must match fpm.toml `version`).
  character(len=*), parameter :: solver_version = '0.1.0'
  include 'version_describe.inc'

contains

  !> Full build identity: the stamped `git describe` string when present,
  !! otherwise the recognizable unstamped fallback `v<version>-dev`.
  pure function solver_build() result(build)
    character(len=:), allocatable :: build

    if (len(git_describe) > 0) then
      build = git_describe
    else
      build = 'v'//solver_version//'-dev'
    end if
  end function solver_build

  !> Shared `--version` handler for all driver programs. If `--version` is on
  !! the command line, print `<exe_name> <build-id>` and `stop 0`. Called
  !! pre-`MPI_Init` by every driver, so the `stop 0` is correct (single image,
  !! no ranks to orphan) and `euler[_1d|_2d] --version` works without mpirun.
  subroutine handle_version_flag(exe_name)
    character(len=*), intent(in) :: exe_name
    integer :: i, arg_len, arg_stat
    character(len=32) :: arg

    do i = 1, command_argument_count()
      call get_command_argument(i, arg, arg_len, arg_stat)
      if (arg_stat == 0 .and. trim(arg) == '--version') then
        write (*, '(a)') trim(exe_name)//' '//solver_build()
        stop 0
      end if
    end do
  end subroutine handle_version_flag

end module version_info
