#!/usr/bin/env ruby

require_relative 'shared_constants'

# Bot response formatting module
module BotResponseFormatter
  extend self

  # Format tally response with optional last entry
  def format_tally_response(user, substance, totals, last_entry = nil)
    base_response = format_basic_tally(user, substance, totals)
    
    if last_entry && !last_entry.empty?
      last_info = format_last_dose_info(last_entry)
      "#{base_response} #{last_info}"
    else
      base_response
    end
  end

  # Format last dose entry response
  def format_last_entry_response(entry, context = :last)
    return format_error_response(SharedConstants::ErrorMessages::NO_DATA) if entry.nil? || entry.empty?
    
    timestamp, name, substance, dose, route, comment = entry
    
    case context
    when :last
      format_last_dose_response(timestamp, name, substance, dose, route, comment)
    when :full
      format_full_entry_response(timestamp, name, substance, dose, route, comment)
    else
      format_basic_entry_response(timestamp, substance, dose, route)
    end
  end

  # Format help response
  def format_help_response
    commands = SharedConstants::Bot::COMMANDS
    
    help_text = []
    help_text << "Available commands:"
    help_text << "#{commands[:tally]} <substance> [user] - Get usage count for substance"
    help_text << "#{commands[:last]} <substance> [user] - Get last dose info"
    help_text << "#{commands[:listdrugs]} [user] - List all substances used"
    help_text << "#{commands[:wrapped]} [user] [year] - Generate year-end summary"
    help_text << "#{commands[:annotate]} <comment> - Add comment to your last dose"
    help_text << "#{commands[:help]} - Show this help message"
    
    help_text.join(" | ")
  end

  # Format listdrugs response
  def format_listdrugs_response(user, substances)
    return format_error_response("No substances found for #{user}") if substances.empty?
    
    # Group substances by frequency for better organization
    if substances.length > 20
      top_substances = substances.take(20)
      "#{user}'s substances (top 20): #{top_substances.join(', ')}... (#{substances.length} total)"
    else
      "#{user}'s substances: #{substances.join(', ')}"
    end
  end

  # Format wrapped generation response
  def format_wrapped_response(user, year, url = nil)
    if url
      "#{user}'s Substance Wrapped #{year}: #{url}"
    else
      format_error_response("Failed to generate wrapped for #{user} (#{year})")
    end
  end

  # Format annotation confirmation
  def format_annotation_response(user, comment)
    "Annotation added: \"#{comment.strip}\" - will be applied to your last dose"
  end

  # Format error response
  def format_error_response(message)
    "Error: #{message}"
  end

  # Format truncated response if too long
  def format_truncated_response(text)
    OutputFormatter.truncate_text(text, SharedConstants::Bot::MAX_RESPONSE_LENGTH)
  end

  # Format user mention
  def format_user_mention(user)
    return "User" if user.nil? || user.empty?
    user.to_s.strip
  end

  # Format substance name for display
  def format_substance_name(substance)
    return "unknown" if substance.nil? || substance.empty?
    substance.to_s.strip
  end

  # Format dose amount for display
  def format_dose_display(dose)
    return "unknown amount" if dose.nil? || dose.empty?
    dose.to_s.strip
  end

  # Format route for display
  def format_route_display(route)
    return "" if route.nil? || route.empty?
    route.to_s.strip
  end

  # Format timestamp for display
  def format_timestamp_display(timestamp)
    return "unknown time" if timestamp.nil?
    
    begin
      parsed_time = Time.parse(timestamp.to_s)
      parsed_time.strftime("%m/%d/%Y %H:%M")
    rescue ArgumentError
      timestamp.to_s
    end
  end

  # Format count display
  def format_count_display(count)
    return "0" if count.nil?
    count.to_s
  end

  # Format comment for display
  def format_comment_display(comment)
    return "" if comment.nil? || comment.empty?
    
    cleaned_comment = comment.to_s.strip
    return "" if cleaned_comment.empty?
    
    " (#{cleaned_comment})"
  end

  # Format success response
  def format_success_response(message)
    message.to_s
  end

  # Format warning response
  def format_warning_response(message)
    "Warning: #{message}"
  end

  # Format status response
  def format_status_response(message)
    "Status: #{message}"
  end

  private

  # Format basic tally information
  def format_basic_tally(user, substance, totals)
    formatted_user = format_user_mention(user)
    formatted_substance = format_substance_name(substance)
    formatted_count = format_count_display(totals)
    
    "#{formatted_user} has used #{formatted_substance} #{formatted_count} times"
  end

  # Format last dose information
  def format_last_dose_info(entry)
    timestamp, _, substance, dose, route, comment = entry
    
    formatted_timestamp = format_timestamp_display(timestamp)
    formatted_dose = format_dose_display(dose)
    formatted_route = format_route_display(route)
    formatted_comment = format_comment_display(comment)
    
    route_text = formatted_route.empty? ? "" : " via #{formatted_route}"
    
    "Last: #{formatted_dose}#{route_text} at #{formatted_timestamp}#{formatted_comment}"
  end

  # Format last dose response
  def format_last_dose_response(timestamp, name, substance, dose, route, comment)
    formatted_timestamp = format_timestamp_display(timestamp)
    formatted_name = format_user_mention(name)
    formatted_substance = format_substance_name(substance)
    formatted_dose = format_dose_display(dose)
    formatted_route = format_route_display(route)
    formatted_comment = format_comment_display(comment)
    
    route_text = formatted_route.empty? ? "" : " via #{formatted_route}"
    
    "#{formatted_name} last dosed #{formatted_substance} (#{formatted_dose})#{route_text} at #{formatted_timestamp}#{formatted_comment}"
  end

  # Format full entry response
  def format_full_entry_response(timestamp, name, substance, dose, route, comment)
    formatted_timestamp = format_timestamp_display(timestamp)
    formatted_name = format_user_mention(name)
    formatted_substance = format_substance_name(substance)
    formatted_dose = format_dose_display(dose)
    formatted_route = format_route_display(route)
    formatted_comment = format_comment_display(comment)
    
    route_text = formatted_route.empty? ? "" : " via #{formatted_route}"
    
    "On #{formatted_timestamp}, #{formatted_name} took: #{formatted_substance} (#{formatted_dose})#{route_text}#{formatted_comment}"
  end

  # Format basic entry response
  def format_basic_entry_response(timestamp, substance, dose, route)
    formatted_timestamp = format_timestamp_display(timestamp)
    formatted_substance = format_substance_name(substance)
    formatted_dose = format_dose_display(dose)
    formatted_route = format_route_display(route)
    
    route_text = formatted_route.empty? ? "" : " via #{formatted_route}"
    
    "#{formatted_substance} (#{formatted_dose})#{route_text} at #{formatted_timestamp}"
  end
end