!> @file euler_driver_2d.f90
!> @brief Driver module for the 2D Euler solver: exposes run_euler_2d as a
!>        reusable subroutine so it can be called from tests or a future launcher.
!!
!! Since phase P1 (Full 2D Parity) the driver is a thin shell over
!! `solver_runtime_2d`: config read -> context init -> run-to-end via the
!! bounded step loop -> final logs -> gather/write. The CLI output is
!! bit-for-bit identical to the pre-P1 monolithic loop (same setup order, same
!! log lines, same plain time accumulation); the attached IPC worker (phase
!! P2) drives the SAME runtime, so both paths observe one numerical run.
module euler_driver_2d
  use config_2d, only: config_2d_t, read_config_2d
  use solver_runtime_2d, only: solver_run_context_2d_t, init_run_context_2d, &
                               run_solver_steps_2d, write_solution_file_2d
  use logger, only: log_finalize, log_info
  implicit none
  private
  public :: run_euler_2d

contains

  !> Run the full 2D Euler solve: read config, init, time-march, gather and write.
  !>
  !> @param nml_file  Path to the namelist input file.
  !> @param ok        Set .true. on success, .false. on any error.
  !> @param message   Human-readable error description when ok is .false.
  subroutine run_euler_2d(nml_file, ok, message)
    character(len=*), intent(in) :: nml_file
    logical, intent(out) :: ok
    character(len=*), intent(out) :: message

    type(config_2d_t) :: cfg
    type(solver_run_context_2d_t) :: ctx
    integer :: status, steps_taken
    logical :: finished
    character(len=512) :: line

    ok = .false.
    message = ''

    call read_config_2d(trim(nml_file), cfg, ok, message)
    if (.not. ok) return

    ctx % nml_file = nml_file
    call init_run_context_2d(ctx, cfg, status, message)
    if (status /= 0) then
      ok = .false.   ! init already finalised the logger on failure
      return
    end if

    call run_solver_steps_2d(ctx, huge(1), steps_taken, finished, status, message)
    if (status /= 0) then
      ok = .false.
      call log_finalize()
      return
    end if

    write (line, '(a,i0,a,es12.5)') 'done: ', ctx % iter, ' steps, t=', ctx % t
    call log_info(trim(line))

    call write_solution_file_2d(ctx, trim(ctx % state % cfg % output_file), ok, message)
    if (.not. ok) then
      call log_finalize()
      return
    end if
    call log_info('wrote "'//trim(ctx % state % cfg % output_file)//'"')
    call log_finalize()
    ok = .true.
  end subroutine run_euler_2d

end module euler_driver_2d
