program search_sofi
   use, intrinsic :: iso_fortran_env, only: int32, real64
   implicit none

   ! Standort Minga (München)
   real(real64), parameter :: lat = 48.173333_real64
   real(real64), parameter :: lon = 11.635000_real64
   real(real64), parameter :: elev = 515.0_real64

   character(len=8)  :: dt_date, dt_time
   character(len=5)  :: dt_zone
   integer(int32)    :: y, m, d, h, mn, s
   integer(int32)    :: step_i
   real(real64)      :: start_jd, current_jd, fine_jd, best_jd
   real(real64)      :: az_m, alt_m, dist_k, phase_p, angle_s, az_s, alt_s
   real(real64)      :: dx_s, dy_s, eclipse_f, sep_deg, min_sep_deg
   real(real64)      :: best_az_s, best_alt_s, coverage_pct
   character(len=32) :: phase_str
   character(len=4096) :: sys_cmd
   logical           :: eclipse_found

   print *, "=========================================================="
   print *, "  SUCHE NACH DER NAECHSTEN SONNENFINSTERNIS FUER MINGA   "
   print *, "=========================================================="
   print '(A,F9.6,A,F9.6,A,F5.1,A)', "Standort: ", lat, " N, ", lon, " E, ", elev, " m"

   ! Aktuelles Datum & Zeit als Startpunkt einlesen
   call date_and_time(date=dt_date, time=dt_time, zone=dt_zone)
   read (dt_date(1:4), '(I4)') y
   read (dt_date(5:6), '(I2)') m
   read (dt_date(7:8), '(I2)') d
   read (dt_time(1:2), '(I2)') h
   read (dt_time(3:4), '(I2)') mn
   read (dt_time(5:6), '(I2)') s

   start_jd = date_to_jd(y, m, d, 12, 0, 0) ! Start um 12:00 Uhr
   current_jd = start_jd
   eclipse_found = .false.

   print '(A,I2.2,A,I2.2,A,I4,A)', "Suche startet ab: ", d, ".", m, ".", y, " ..."
   print *, "Durchsuche Tage (schrittweise) ..."

   do while (.not. eclipse_found)
      ! Datum für aktuellen Tag berechnen
      call jd_to_date(current_jd, y, m, d, h, mn, s)

      ! Abfrage via get_moon.py
      call query_moon(lat, lon, elev, y, m, d, 12, 0, 0, dt_zone, &
                      az_m, alt_m, dist_k, phase_p, phase_str, angle_s, &
                      az_s, alt_s, dx_s, dy_s, eclipse_f)

      sep_deg = sqrt(dx_s**2 + dy_s**2)

      ! Potenzielle Finsternis in der Nähe (Abstand < 2.0 Grad)
      if (sep_deg < 2.0_real64) then
         print '(A,I2.2,A,I2.2,A,I4,A)', " -> Nahe Konjunktion am ", d, ".", m, ".", y, " entdeckt. Starte Feinsuche..."

         min_sep_deg = 999.0_real64

         ! 24-Stunden Feinsuche im 2-Minuten-Raster (-12h bis +12h) mit Integer-Schleifenvariable
         do step_i = -360, 360
            fine_jd = current_jd + real(step_i, real64) * (2.0_real64 / 1440.0_real64)
            call jd_to_date(fine_jd, y, m, d, h, mn, s)

            call query_moon(lat, lon, elev, y, m, d, h, mn, s, dt_zone, &
                            az_m, alt_m, dist_k, phase_p, phase_str, angle_s, &
                            az_s, alt_s, dx_s, dy_s, eclipse_f)

            sep_deg = sqrt(dx_s**2 + dy_s**2)

            if (sep_deg < min_sep_deg) then
               min_sep_deg = sep_deg
               best_jd = fine_jd
               best_az_s = az_s
               best_alt_s = alt_s
            end if
         end do

         ! Bewertung des Maximums
         if (min_sep_deg < 0.55_real64) then
            call jd_to_date(best_jd, y, m, d, h, mn, s)

            if (best_alt_s > -0.5_real64) then
               ! In Minga sichtbar!
               eclipse_found = .true.
               coverage_pct = max(0.0_real64, min(100.0_real64, (1.0_real64 - min_sep_deg / 0.52_real64) * 100.0_real64))

               print *, ""
               print *, "=========================================================="
               print *, "   GEFUNDEN: NAECHSTE VISIBEL SONNENFINSTERNIS IN MINGA!  "
               print *, "=========================================================="
               print '(A,I2.2,A,I2.2,A,I4)', "Datum:              ", d, ".", m, ".", y
               print '(A,I2.2,A,I2.2,A,I2.2,A,A)', "Uhrzeit (Lokal):    ", h, ":", mn, ":", s, " (", dt_zone, ")"
               print '(A,F5.1,A)', "Sonnenhoehe:        ", best_alt_s, " deg"
               print '(A,F5.1,A)', "Sonnenazimut:       ", best_az_s, " deg"
               print '(A,F6.3,A)', "Min. Winkelabstand: ", min_sep_deg, " deg"
               print '(A,F5.1,A)', "Max. Verdeckung:    ~", coverage_pct, " %"
               print *, "=========================================================="
            else
               print '(A,I2.2,A,I2.2,A,I4,A,F5.1,A)', " -> Sonnenfinsternis am ", d, ".", m, ".", y, &
                  " ist unter dem Horizont in Minga (Hoehe: ", best_alt_s, " deg)."
            end if
         end if
      end if

      ! 1 Tag weiter springen
      current_jd = current_jd + 1.0_real64
   end do

contains

   ! Hilfssubroutine zur Abfrage von get_moon.py
   subroutine query_moon(lat, lon, elev, y, m, d, h, mn, s, tz_str, &
                         az_m, alt_m, dist_k, phase_p, phase_str, angle_s, &
                         az_s, alt_s, dx_s, dy_s, eclipse_f)
      real(real64), intent(in) :: lat, lon, elev
      integer, intent(in)      :: y, m, d, h, mn, s
      character(len=*), intent(in) :: tz_str
      real(real64), intent(out) :: az_m, alt_m, dist_k, phase_p, angle_s, az_s, alt_s, dx_s, dy_s, eclipse_f
      character(len=*), intent(out) :: phase_str
      character(len=4096) :: cmd

      write (cmd, '(A,F9.6,A,F9.6,A,F6.1,A,I4.4,A,I2.2,A,I2.2,A,I2.2,A,I2.2,A,I2.2,A,A,A)') &
         "python3 /var/www/html/moon/get_moon.py ", &
         lat, " ", lon, " ", elev, " ", &
         y, " ", m, " ", d, " ", &
         h, " ", mn, " ", s, " ", tz_str, &
         " > sofi_tmp.txt"

      call execute_command_line(trim(cmd))

      open (unit=30, file="sofi_tmp.txt", status="old", action="read")
      read (30, *) az_m, alt_m, dist_k, phase_p, phase_str, angle_s, az_s, alt_s, dx_s, dy_s, eclipse_f
      close (30)
      call execute_command_line("rm sofi_tmp.txt")
   end subroutine query_moon

   ! Datum zu Julianischem Datum
   function date_to_jd(y, m, d, h, mn, s) result(jd)
      integer, intent(in) :: y, m, d, h, mn, s
      real(real64) :: jd, ut
      integer :: yr, mo, a, b
      yr = y
      mo = m
      if (mo <= 2) then
         yr = yr - 1
         mo = mo + 12
      end if
      a = yr / 100
      b = 2 - a + (a / 4)
      ut = real(h, real64) + real(mn, real64) / 60.0_real64 + real(s, real64) / 3600.0_real64
      jd = floor(365.25_real64 * real(yr + 4716, real64)) + &
           floor(30.6001_real64 * real(mo + 1, real64)) + &
           real(d, real64) + (ut / 24.0_real64) + real(b, real64) - 1524.5_real64
   end function date_to_jd

   ! Julianisches Datum zu Datum
   subroutine jd_to_date(jd, y, m, d, h, mn, s)
      real(real64), intent(in) :: jd
      integer, intent(out) :: y, m, d, h, mn, s
      real(real64) :: z, f, a, alpha, b, c, d_num, e, day_frac, ut
      z = floor(jd + 0.5_real64)
      f = (jd + 0.5_real64) - z
      if (z < 2299161.0_real64) then
         a = z
      else
         alpha = floor((z - 1867216.25_real64) / 36524.25_real64)
         a = z + 1.0_real64 + alpha - floor(alpha / 4.0_real64)
      end if
      b = a + 1524.0_real64
      c = floor((b - 122.1_real64) / 365.25_real64)
      d_num = floor(365.25_real64 * c)
      e = floor((b - d_num) / 30.6001_real64)
      day_frac = b - d_num - floor(30.6001_real64 * e) + f
      d = int(day_frac)
      ut = (day_frac - real(d, real64)) * 24.0_real64
      h = int(ut)
      mn = int((ut - real(h, real64)) * 60.0_real64)
      s = nint(((ut - real(h, real64)) * 60.0_real64 - real(mn, real64)) * 60.0_real64)
      if (s >= 60) then
         s = s - 60
         mn = mn + 1
      end if
      if (mn >= 60) then
         mn = mn - 60
         h = h + 1
      end if
      if (e < 14.0_real64) then
         m = int(e - 1.0_real64)
      else
         m = int(e - 13.0_real64)
      end if
      if (m > 2) then
         y = int(c - 4716.0_real64)
      else
         y = int(c - 4715.0_real64)
      end if
   end subroutine jd_to_date

end program search_sofi
