require "json"

module JosieHealth::LUT
  # Provides access to bundled data files
  module DataFiles
    # Embed data files at compile time
    DRUGS_DATA    = {{ read_file("#{__DIR__}/../data/drugs.json") }}
    COMBOS_DATA   = {{ read_file("#{__DIR__}/../data/combos.json") }}
    CAFFEINE_DATA = {{ read_file("#{__DIR__}/../data/caffeine.json") }}
    ALCOHOL_DATA  = {{ read_file("#{__DIR__}/../data/alcohol.json") }}
    MEDS_DATA     = {{ read_file("#{__DIR__}/../data/meds.json") }}
    CANNABIS_DATA = {{ read_file("#{__DIR__}/../data/cannabis.json") }}

    @@drugs : JSON::Any?
    @@combos : JSON::Any?
    @@caffeine : JSON::Any?
    @@alcohol : JSON::Any?
    @@meds : JSON::Any?
    @@cannabis : JSON::Any?

    # Load and cache drugs.json
    def self.drugs : JSON::Any
      @@drugs ||= JSON.parse(DRUGS_DATA)
    end

    # Load and cache combos.json
    def self.combos : JSON::Any
      @@combos ||= JSON.parse(COMBOS_DATA)
    end

    # Load and cache caffeine.json
    def self.caffeine : JSON::Any
      @@caffeine ||= JSON.parse(CAFFEINE_DATA)
    end

    # Load and cache alcohol.json
    def self.alcohol : JSON::Any
      @@alcohol ||= JSON.parse(ALCOHOL_DATA)
    end

    # Load and cache meds.json
    def self.meds : JSON::Any
      @@meds ||= JSON.parse(MEDS_DATA)
    end

    # Load and cache cannabis.json
    def self.cannabis : JSON::Any
      @@cannabis ||= JSON.parse(CANNABIS_DATA)
    end

    # Get substance info from drugs.json
    def self.substance_info(name : String) : JSON::Any?
      drugs[name]?
    end

    # Get interaction info from combos.json
    def self.interaction(substance1 : String, substance2 : String) : JSON::Any?
      if combo = combos[substance1]?
        combo[substance2]?
      elsif combo = combos[substance2]?
        combo[substance1]?
      end
    end

    # Get all substance names from drugs.json
    def self.all_substances : Array(String)
      drugs.as_h.keys
    end

    # Get categories for a substance
    def self.categories(name : String) : Array(String)
      if info = substance_info(name)
        if cats = info["categories"]?
          cats.as_a.map(&.as_s)
        else
          [] of String
        end
      else
        [] of String
      end
    end

    # Get pretty name for a substance
    def self.pretty_name(name : String) : String?
      substance_info(name).try(&.["pretty_name"]?.try(&.as_s))
    end
  end
end
