module JosieHealth::Utils
  module Timestamp
    # Parse HHMM format (e.g., "0130" = 1 hour 30 minutes ago) to Time
    # Supports formats: HHMM, HMM, MM (pads with zeros)
    # Returns nil if invalid format or out of range
    def self.parse_ago(ago_str : String) : Time?
      # Pad to 4 digits (e.g., "30" -> "0030", "230" -> "0230")
      padded = ago_str.rjust(4, '0')

      if match = padded.match(/^(\d{2})(\d{2})$/)
        hours = match[1].to_i
        minutes = match[2].to_i

        return nil if hours > 23 || minutes > 59

        Time.utc - hours.hours - minutes.minutes
      end
    end

    # Parse HHMM format to RFC3339 string
    # Returns current time as RFC3339 if parsing fails
    def self.parse_ago_rfc3339(ago_str : String) : String
      if time = parse_ago(ago_str)
        time.to_rfc3339
      else
        Time.utc.to_rfc3339
      end
    end

    # Parse various timestamp formats to RFC3339
    # Supports:
    #   - Full ISO: 2025-01-15T14:30:00 or 2025-01-15T14:30
    #   - Time with colon: HH:MM (assumes today)
    #   - Time without colon: HHMM (assumes today)
    # Returns nil if invalid format
    def self.parse_timestamp(ts : String) : String?
      now = Time.utc

      # Full ISO format: 2025-01-15T14:30:00 or 2025-01-15T14:30
      if match = ts.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/)
        year = match[1].to_i
        month = match[2].to_i
        day = match[3].to_i
        hour = match[4].to_i
        minute = match[5].to_i
        second = match[6]?.try(&.to_i) || 0
        begin
          return Time.utc(year, month, day, hour, minute, second).to_rfc3339
        rescue
          return nil
        end
      end

      # Time with colon: HH:MM (assumes today)
      if match = ts.match(/^(\d{1,2}):(\d{2})$/)
        hour = match[1].to_i
        minute = match[2].to_i
        return nil if hour > 23 || minute > 59
        return Time.utc(now.year, now.month, now.day, hour, minute, 0).to_rfc3339
      end

      # Time without colon: HHMM (assumes today)
      if match = ts.match(/^(\d{2})(\d{2})$/)
        hour = match[1].to_i
        minute = match[2].to_i
        return nil if hour > 23 || minute > 59
        return Time.utc(now.year, now.month, now.day, hour, minute, 0).to_rfc3339
      end

      nil
    end

    # Format RFC3339 timestamp for display
    # Shows time only if today, otherwise shows date and time
    def self.format_display(rfc3339 : String) : String
      begin
        time = Time.parse_rfc3339(rfc3339)
        now = Time.utc
        if time.year == now.year && time.month == now.month && time.day == now.day
          time.to_s("%H:%M")
        else
          time.to_s("%Y-%m-%d %H:%M")
        end
      rescue
        rfc3339
      end
    end

    # Get current time as RFC3339
    def self.now_rfc3339 : String
      Time.utc.to_rfc3339
    end
  end
end
