#!/usr/bin/env ruby

require 'date'

# Shared constants used across the annotate-dr system
# This module centralizes all magic numbers and configuration values
module SharedConstants
  # Time periods for analysis
  TIME_PERIODS = {
    'Morning (6-11)' => (6..11),
    'Afternoon (12-17)' => (12..17),
    'Evening (18-23)' => (18..23),
    'Night (0-5)' => (0..5)
  }.freeze

  # Image generation constants
  module ImageGeneration
    PADDING = 50
    LINE_HEIGHT = 25
    FONT_SIZE = 18
    CHAR_WIDTH = 10
    TITLE_FONT_SIZE = 27  # FONT_SIZE * 1.5
    BACKGROUND_IMAGE = ENV['ASSET_DIR'] ? File.join(ENV['ASSET_DIR'], 'pillsbg.png') : 'assets/pillsbg.png'
    FONTS = {
      regular: 'DejaVu-Sans',
      bold: 'DejaVu-Sans-Bold'
    }.freeze
  end

  # Data processing constants
  module DataProcessing
    DOSE_PATTERN = /^(\d+(?:\.\d+)?)mg$/
    DOSE_THRESHOLD = 0.5  # Minimum percentage of measurable doses to show average
    CSV_HEADERS = %w[timestamp user substance dose route].freeze
    
    # Known text-only doses that should be treated as count=1.0
    KNOWN_TEXT_DOSES = %w[crumbs bump smallline line liner luge pile small large tablet capsule pill drop shot glass beer cigarette zoot monster redbull rockstar nos amp energy drink mate clubmate vodka].freeze
    
    # Known container/quantity words (can come after numbers)
    QUANTITY_CONTAINERS = %w[can cans bottle bottles glass glasses shot shots cup cups pint pints liter liters litre litres ml cl dl].freeze
    
    # Known dose units (case-insensitive)
    KNOWN_UNITS = %w[mg g kg µg μg ug mcg ml l cl dl oz lb iu units unit tabs tab caps cap drops drop MG G KG UG MCG ML L CL DL OZ LB IU UNITS UNIT TABS TAB CAPS CAP DROPS DROP].freeze
    
    # CSV column indices
    CSV_COLUMNS = {
      timestamp: 0,
      user: 1,
      substance: 2,
      dose: 3,
      route: 4,
      comment: 5
    }.freeze
  end

  # Statistical constants
  module Statistics
    OUTLIER_IQR_MULTIPLIER = 1.5
    LARGE_SAMPLE_THRESHOLD = 30
    DEFAULT_BINS = 10
    LOG_BINS = 8
    SKEW_THRESHOLD = 0.8
    
    CRITICAL_VALUES = {
      0.95 => 1.96,
      0.99 => 2.576
    }.freeze
    
    # Dose classification thresholds (multipliers of std deviation)
    DOSE_CLASSIFICATION = {
      conservative_light: -0.5,
      conservative_heavy: 1.5
    }.freeze
  end

  # File paths and names
  module Files
    DATA_CSV = 'data.csv'
    DRUG_LUT = 'lut_drug.rb'
    ROA_LUT = 'lut_roa.rb'
    ASSETS_DIR = 'assets'
    HELPERS_DIR = 'helpers'
    
    # Temporary file prefixes
    TEMP_PREFIX = 'temp_'
    TEMP_CANVAS = 'temp_canvas.png'
    TEMP_BG = 'temp_bg.png'
    TEMP_IMAGE = 'temp_image.png'
  end

  # IRC Bot configuration
  module Bot
    NICK = "annotate"
    CHANNEL = "##drugs"
    SERVER = "irc.libera.chat"
    PORT = 6667
    
    COMMANDS = {
      help: ';help',
      tally: ';tally',
      last: ';last',
      listdrugs: ';listdrugs',
      wrapped: ';wrapped',
      reload: ';reload',
      annotate: ';annotate'
    }.freeze
    
    # Response formatting
    MAX_RESPONSE_LENGTH = 400
    TRUNCATION_SUFFIX = '...'
  end

  # Analysis limits and defaults
  module Analysis
    TOP_SUBSTANCES_LIMIT = 10
    TOP_ROUTES_LIMIT = 3
    TOP_DAYS_LIMIT = 3
    MAX_STREAKS_DISPLAY = 5
    MAX_ONETIME_DISPLAY = 20
    
    # Percentage thresholds for dynamic titles
    SUBSTANCE_DOMINANCE_THRESHOLD = 0.5
    SUBSTANCE_MAJOR_THRESHOLD = 0.3
    TIME_PERIOD_THRESHOLD = 0.4
    ROUTE_THRESHOLD = 0.3
    
    # Streak analysis
    MIN_STREAK_LENGTH = 2  # Only show streaks of 2+ days
  end

  # Color codes for terminal output
  module Colors
    # These correspond to colorize gem methods
    SUBSTANCE = :red
    ROUTE = :green
    COUNT = :blue
    RANGE_MIN = :cyan
    RANGE_MAX = :magenta
    AVERAGE = :yellow
    STATS = :light_blue
    ERROR = :red
    SUCCESS = :green
    WARNING = :yellow
  end

  # Formatting constants
  module Formatting
    SEPARATOR_LENGTH = 80
    SECTION_SEPARATOR = '=' * SEPARATOR_LENGTH
    SUBSECTION_SEPARATOR = '-' * 40
    
    # Indentation levels
    INDENT_LEVEL_1 = "\t"
    INDENT_LEVEL_2 = "\t\t"
    INDENT_LEVEL_3 = "\t\t\t"
    
    # Table formatting
    TABLE_MIN_WIDTH = 20
    TABLE_MAX_WIDTH = 50
  end

  # Error messages
  module ErrorMessages
    NO_DATA = "No data found"
    INVALID_FORMAT = "Invalid format"
    FILE_NOT_FOUND = "File not found"
    PARSING_ERROR = "Error parsing data"
    NETWORK_ERROR = "Network error"
    UNAUTHORIZED = "Unauthorized access"
    INVALID_COMMAND = "Invalid command"
    MISSING_PARAMETER = "Missing required parameter"
  end

  # Success messages
  module SuccessMessages
    DATA_PROCESSED = "Data processed successfully"
    IMAGE_GENERATED = "Image generated successfully"
    REPORT_CREATED = "Report created successfully"
    UPLOAD_COMPLETE = "Upload completed"
  end

  # Validation constants
  module Validation
    MIN_YEAR = 2000
    MAX_YEAR = 2050
    MIN_USERNAME_LENGTH = 1
    MAX_USERNAME_LENGTH = 50
    MIN_SUBSTANCE_LENGTH = 1
    MAX_SUBSTANCE_LENGTH = 100
    
    # Regex patterns
    USERNAME_PATTERN = /^[a-zA-Z0-9_-]+$/
    YEAR_PATTERN = /^\d{4}$/
    TIME_PATTERN = /^\d{2}:\d{2}$/
  end

  # Default values
  module Defaults
    CURRENT_YEAR = Date.today.year
    TIMEZONE = 'UTC'
    DOSE_UNIT = 'mg'
    ROUTE = 'oral'
    CONFIDENCE_LEVEL = 0.95
    HISTOGRAM_BINS = 10
  end
end