#!/usr/bin/env ruby

require 'csv'

# Helper functions for LUT processing
module LutHelper
  # Inverts a hash mapping to create a lookup table
  def self.invert_hash(input_hash)
    inverted = {}
    input_hash.each do |key, values|
      values.each do |value|
        inverted[value] = key
      end
    end
    inverted
  end

  # Load and cache drug LUT
  def self.drug_lut
    @drug_lut ||= begin
      require_relative '../lut_drug'
      invert_hash(LUT_DRUG_IN)
    end
  end

  # Load and cache ROA LUT
  def self.roa_lut
    @roa_lut ||= begin
      require_relative '../lut_roa'
      invert_hash(LUT_ROA_IN)
    end
  end

  # Normalize substance using LUT
  def self.normalize_substance_with_lut(substance)
    return nil if substance.nil?
    
    # Clean the substance name first
    cleaned = substance.to_s.gsub(/\p{C}/, '').strip
    return nil if cleaned.empty?
    
    # Try direct lookup first
    normalized = drug_lut[cleaned]
    return normalized if normalized
    
    # Try case-insensitive lookup
    cleaned_lower = cleaned.downcase
    normalized = drug_lut[cleaned_lower]
    return normalized if normalized
    
    # Try with non-alphanumeric characters removed
    cleaned_alphanum = cleaned.gsub(/[^a-zA-Z0-9]/, '').downcase
    normalized = drug_lut[cleaned_alphanum]
    return normalized if normalized
    
    # If not found in LUT, return cleaned version (fallback to old behavior)
    cleaned_alphanum.empty? ? nil : cleaned_alphanum
  end

  # Normalize route using LUT
  def self.normalize_route_with_lut(route)
    return nil if route.nil?
    
    # Clean the route name first
    cleaned = route.to_s.gsub(/\p{C}/, '').strip
    return nil if cleaned.empty?
    
    # Try direct lookup first
    normalized = roa_lut[cleaned]
    return normalized if normalized
    
    # Try case-insensitive lookup
    cleaned_lower = cleaned.downcase
    normalized = roa_lut[cleaned_lower]
    return normalized if normalized
    
    # If not found in LUT, return cleaned lowercase version (fallback)
    cleaned_lower
  end

  # Processes CSV data with drug and ROA LUTs
  def self.process_csv_with_luts(user, year)
    csv_file = ENV['DATA_CSV_PATH'] || 'data.csv'
    logs = CSV.read(csv_file, headers: true)
    
    entries = logs.dup
    
    # Normalize substances and routes using centralized LUT functions
    entries.each do |entry|
      entry['med'] = normalize_substance_with_lut(entry['med']) || 'unknown'
      entry['ROA'] = normalize_route_with_lut(entry['ROA']) || 'unknown'
    end
    
    # Filter out unknown substances and select user
    entries = entries.reject { |v| v['med'] == 'unknown' }
    entries = entries.select { |v| v['user'] == user }
    
    # Convert to standard CSV format
    csv_data = [['timestamp', 'user', 'substance', 'dose', 'route']]
    entries.each do |entry|
      timestamp = entry['timestamp'] || entry['date'] || Time.now.strftime('%Y-%m-%d %H:%M:%S')
      csv_data << [timestamp, entry['user'], entry['med'], entry['amount'], entry['ROA']]
    end
    
    csv_data
  end
end
