require "irc"
require "time"
require "json"

class MedicationTracker
  @client : IRC::Client

  def initialize
    @irc_server = ENV["IRC_SERVER"]? || "irc.libera.chat"
    @irc_port = ENV["IRC_PORT"]?.try(&.to_i) || 6697
    @irc_channel = ENV["IRC_CHANNEL"]? || "##drugs"
    @irc_nick = ENV["IRC_NICK"]? || "josie_health_bot"
    @irc_ssl = ENV["IRC_SSL"]?.try(&.downcase) != "false"

    # Setup IRC client
    @client = IRC::Client.new(@irc_server, @irc_port, @irc_nick, ssl: @irc_ssl)
    setup_handlers
  end

  def start
    puts "Starting IRC medication tracker..."
    puts "Connecting to #{@irc_server}:#{@irc_port} as #{@irc_nick}"
    puts "Joining #{@irc_channel}"
    
    @client.connect
    @client.join(@irc_channel)
    
    # Keep the connection alive
    loop do
      sleep 30
      @client.ping(@irc_server) if @client.connected?
    end
  end

  private def setup_handlers
    @client.on_connect do
      puts "Connected to IRC server"
    end

    @client.on_join do |message|
      puts "Joined #{message.params[0]}" if message.prefix.try(&.nick) == @irc_nick
    end

    @client.on_privmsg do |message|
      next unless message.params[0] == @irc_channel
      
      nick = message.prefix.try(&.nick)
      text = message.params[1]
      
      next unless nick && text
      
      spawn process_message(nick, text)
    end

    @client.on_disconnect do
      puts "Disconnected from IRC server"
      sleep 5
      puts "Reconnecting..."
      @client.connect
      @client.join(@irc_channel)
    end
  end

  private def process_message(nick : String, text : String)
    return unless medication_event = extract_medication(text)
    
    canonical_name = JosieHealth::LUT.normalize_substance(medication_event[:substance])
    return unless canonical_name
    
    event = {
      "timestamp" => Time.utc,
      "user_id" => nick.downcase,
      "medication_name" => canonical_name,
      "dosage" => medication_event[:dosage],
      "unit" => medication_event[:unit],
      "route" => medication_event[:route],
      "source" => "irc",
      "channel" => @irc_channel,
      "raw_message" => text,
    }
    
    begin
      @collection.insert_one(event)
      puts "Recorded: #{nick} took #{medication_event[:dosage]}#{medication_event[:unit]} #{canonical_name}"
    rescue ex
      puts "Error saving medication event: #{ex.message}"
    end
  end


# Main execution
begin
  tracker = MedicationTracker.new
  tracker.start
rescue ex
  puts "Error: #{ex.message}"
  puts ex.backtrace.join("\n")
  exit 1
end