#!/usr/bin/env ruby

module DataAnalysisHelper
  # Calculates route usage statistics from processed data
  def self.count_routes_by_type(data)
    route_counts = Hash.new(0)
    data.each do |entry|
      route = entry[:route]
      next unless route
      
      route_key = route.downcase.to_sym
      route_counts[route_key] += 1
    end
    
    route_counts
  end

  # Calculates time period usage from analysis data
  def self.get_time_period_usage_from_analysis(time_analysis)
    {
      night: time_analysis['Night (0-5)']&.values&.sum || 0,
      morning: time_analysis['Morning (6-11)']&.values&.sum || 0,
      afternoon: time_analysis['Afternoon (12-17)']&.values&.sum || 0,
      evening: time_analysis['Evening (18-23)']&.values&.sum || 0
    }
  end

  # Calculates seasonal breakdown from monthly data
  def self.get_seasonal_breakdown(monthly)
    seasons = { "Spring" => 0, "Summer" => 0, "Fall" => 0, "Winter" => 0 }
    
    monthly.each do |month_key, substances|
      month_num = month_key.split('-')[1].to_i
      total_uses = substances.values.sum { |data| data[:count] }
      
      case month_num
      when 3, 4, 5
        seasons["Spring"] += total_uses
      when 6, 7, 8
        seasons["Summer"] += total_uses
      when 9, 10, 11
        seasons["Fall"] += total_uses
      when 12, 1, 2
        seasons["Winter"] += total_uses
      end
    end
    
    seasons
  end

  # Calculates substance usage statistics
  def self.get_substance_counts(data)
    counts = Hash.new(0)
    data.each { |entry| counts[entry[:substance]] += 1 }
    counts
  end

  # Finds the hardest day
  def self.find_hardest_day(data)
    daily_counts = {}
    data.each do |entry|
      date = entry[:timestamp].to_date
      daily_counts[date] ||= 0
      daily_counts[date] += 1
    end
    
    return nil if daily_counts.empty?
    hardest_date, count = daily_counts.max_by { |_, count| count }
    [hardest_date, count]
  end

  # Gets all doses for a specific day
  def self.get_doses_on_day(data, date)
    data.select { |entry| entry[:timestamp].to_date == date }
        .map { |entry| 
          {
            time: entry[:timestamp].strftime('%H:%M'),
            substance: entry[:substance],
            dose: entry[:dose],
            route: entry[:route]
          }
        }
        .sort_by { |entry| entry[:time] }
  end

  # Calculates longest sober streak in a year
  def self.calculate_longest_sober_streak(data, year)
    return 0 if data.empty?
    
    # Get all unique dates with doses
    dose_dates = data.map { |entry| entry[:timestamp].to_date }.uniq.sort
    
    # Start and end dates for the year
    year_start = Date.new(year, 1, 1)
    year_end = Date.new(year, 12, 31)
    
    # If generating for current year, don't count future dates
    if year == Date.today.year
      year_end = [year_end, Date.today].min
    end
    
    # Calculate gaps between dose dates
    max_streak = 0
    
    # Check gap from year start to first dose
    if dose_dates.any? && dose_dates.first > year_start
      max_streak = (dose_dates.first - year_start).to_i
    end
    
    # Check gaps between consecutive dose dates
    dose_dates.each_cons(2) do |date1, date2|
      gap = (date2 - date1).to_i - 1
      max_streak = [max_streak, gap].max if gap > 0
    end
    
    # Check gap from last dose to year end
    if dose_dates.any? && dose_dates.last < year_end
      gap = (year_end - dose_dates.last).to_i
      max_streak = [max_streak, gap].max
    end
    
    # If no doses in the year, the whole year is sober
    if dose_dates.empty?
      max_streak = (year_end - year_start).to_i + 1
    end
    
    max_streak
  end
end
