#!/usr/bin/env ruby
require 'csv'
require 'date'

class SubstanceWrapped
  def initialize(csv_data)
    @data = parse_csv(csv_data)
  end
  
  def parse_csv(csv_data)
    entries = []
    csv_data.each do |row|
      next if row.length < 5 || row[0].nil? || row[0].empty?
      begin
        entries << {
          timestamp: DateTime.parse(row[0]),
          user: row[1],
          substance: row[2],
          dose: row[3],
          route: row[4]
        }
      rescue => e
        # Skip malformed entries
      end
    end
    entries
  end
  
  def monthly_summary
    monthly = {}
    @data.each do |entry|
      month_key = entry[:timestamp].strftime('%Y-%m')
      monthly[month_key] ||= {}
      monthly[month_key][entry[:substance]] ||= { count: 0, doses: [] }
      monthly[month_key][entry[:substance]][:count] += 1
      
      # Extract numeric dose if it ends with 'mg'
      if entry[:dose] =~ /^(\d+(?:\.\d+)?)mg$/
        monthly[month_key][entry[:substance]][:doses] << $1.to_f
      end
    end
    
    # Calculate averages
    monthly.each do |month, substances|
      substances.each do |substance, data|
        if data[:doses].any?
          data[:avg_dose] = (data[:doses].sum / data[:doses].length).round(1)
        end
      end
    end
    
    monthly
  end
  
  def time_of_day_analysis
    periods = {
      'Morning (6-11)' => (6..11),
      'Afternoon (12-17)' => (12..17), 
      'Evening (18-23)' => (18..23),
      'Night (0-5)' => (0..5)
    }
    
    analysis = {}
    periods.each { |period, _| analysis[period] = {} }
    
    @data.each do |entry|
      hour = entry[:timestamp].hour
      period = periods.find { |_, range| range.include?(hour) }&.first
      next unless period
      
      analysis[period][entry[:substance]] ||= 0
      analysis[period][entry[:substance]] += 1
    end
    
    analysis
  end
  
  def top_substances(limit = 5)
    counts = Hash.new(0)
    @data.each { |entry| counts[entry[:substance]] += 1 }
    counts.sort_by { |_, count| -count }.take(limit)
  end
  
  def route_analysis
    routes = Hash.new { |h, k| h[k] = Hash.new(0) }
    @data.each do |entry|
      routes[entry[:substance]][entry[:route]] += 1
    end
    routes
  end
  
  def day_of_week_analysis
    days = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday]
    analysis = Hash.new { |h, k| h[k] = 0 }
    
    @data.each do |entry|
      day = days[entry[:timestamp].wday]
      analysis[day] += 1
    end
    
    analysis
  end
  
  def peak_month
    monthly = monthly_summary
    month_totals = {}
    monthly.each do |month, substances|
      month_totals[month] = substances.values.sum { |data| data[:count] }
    end
    month_totals.max_by { |_, total| total }
  end
  
  def generate_wrapped
    monthly = monthly_summary
    time_analysis = time_of_day_analysis
    top_subs = top_substances
    route_stats = route_analysis
    peak_month_name, peak_count = peak_month
    day_stats = day_of_week_analysis
    
    output = []
    output << "Your Substance Wrapped 2025"
    output << ""
    output << "Top 5 Substances:"
    top_subs.each_with_index do |(substance, count), i|
      output << "  #{i + 1}. #{substance}: #{count} uses"
    end
    
    output << ""
    output << "Monthly Breakdown:"
    monthly.keys.sort.each do |month|
      substances = monthly[month]
      output << "  #{Date.strptime(month, '%Y-%m').strftime('%B %Y')}:"
      substances.sort_by { |_, data| -data[:count] }.take(3).each do |substance, data|
        avg_text = data[:avg_dose] ? " (avg #{data[:avg_dose]}mg)" : ""
        output << "    • #{substance}: #{data[:count]} uses#{avg_text}"
      end
    end
    
    output << ""
    output << "Peak Usage Times:"
    time_analysis.each do |period, substances|
      next if substances.empty?
      total = substances.values.sum
      output << "  #{period}: #{total} total uses"
    end
    
    output << ""
    output << "Most Active Day:"
    top_day = day_stats.max_by { |_, count| count }
    output << "  #{top_day[0]} (#{top_day[1]} uses)"
    
    output << ""
    output << "Route Preferences:"
    route_stats.sort_by { |sub, _| -top_subs.to_h[sub].to_i }.take(3).each do |substance, routes|
      top_route = routes.max_by { |_, count| count }
      output << "  #{substance}: #{top_route[0]} (#{top_route[1]}/#{routes.values.sum} uses)"
    end
    
    output << ""
    output << "Overall Stats:"
    output << "  • Total entries: #{@data.length}"
    output << "  • Peak month: #{Date.strptime(peak_month_name, '%Y-%m').strftime('%B')} (#{peak_count} uses)"
    output << "  • Unique substances: #{@data.map { |e| e[:substance] }.uniq.count}"
    
    output.join("\n")
  end
end

# Bot integration method
def generate_substance_wrapped(csv_data)
  wrapped = SubstanceWrapped.new(csv_data)
  wrapped.generate_wrapped
end

# Test with file if run directly
if __FILE__ == $0
  csv_data = CSV.read('/home/josie/loogs/josie.csv')
  puts generate_substance_wrapped(csv_data)
end