# frozen_string_literal: true

require 'irb/completion'
require 'pp'

# see: https://ruby-doc.org/3.2.2/stdlibs/irb/IRB.html#module-IRB-label-History
# IRB.conf[:SAVE_HISTORY] = nil
IRB.conf[:SAVE_HISTORY] ||= 1000
IRB.conf[:HISTORY_FILE] ||= File.join(ENV["XDG_DATA_HOME"], "irb", "history")

IRB.conf[:PROMPT_MODE] = :DEFAULT
IRB.conf[:INSPECT_MODE] = :pp

IRB.conf[:AUTO_INDENT] = true
# IRB.conf[:USE_READLINE] = true
# IRB.conf[:USE_MULTILINE] = false
IRB.conf[:USE_AUTOCOMPLETE] = false
# IRB.conf[:USE_COLORIZE] = false

def c()
  system('clear')
end

def t()
  Time.now
end

def P(*args)
  p(*args)
  nil
end

# class Object
#  # create bang methods to reveal method origins
#  methods.grep(/methods$/).each do |plural|
#    singular = plural.to_s.sub(/s$/, '').to_sym
#    singular = :method unless respond_to? singular
#    define_method "#{plural}!" do |*args|
#      Hash[
#        send(plural, *args).map do |name|
#          method = send(singular, name)
#          [method, method.source_location]
#        end
#      ]
#    end
#  end
# end

# %w[
#   English
#   base64
#   bigdecimal
#   cgi
#   date
#   digest
#   erb
#   etc
#   fcntl
#   fiber
#   fileutils
#   io/console
#   ipaddr
#   json
#   logger
#   net/http
#   open3
#   openssl
#   optparse
#   ostruct
#   pathname
#   pp
#   securerandom
#   set
#   shellwords
#   socket
#   stringio
#   syslog
#   tempfile
#   thread
#   time
#   tsort
#   uri
#   yaml
# ].each { require(_1) }
#
# module Kernel
#   def clear! = system(*%w[clear --], exception: true) unless respond_to?(:clear!)
#   def methods! = (methods - Object.methods).sort unless respond_to?(:methods!)
#   def own_methods! = (methods - self.class.superclass.instance_methods).sort unless respond_to?(:own_methods!)
#
#   unless respond_to?(:assert!)
#     def assert!(c, m = nil, &msg)
#       raise(msg&.call || m) unless c
#
#       c
#     end
#   end
# end

class Module
  unless instance_methods.include?(:edit!)
    def edit!
      case Object.const_source_location(name)
      in []
        warn(inspect)
      in [path, lineno]
        system(*ENV.fetch('EDITOR').shellsplit, "#{path}:#{lineno}")
      end
    end
  end
end

class Class
  unless instance_methods.include?(:edit!)
    def edit!
      case Object.const_source_location(name)
      in []
        warn(inspect)
      in [path, lineno]
        system(*ENV.fetch('EDITOR').shellsplit, "#{path}:#{lineno}")
      end
    end
  end
end

class Method
  unless instance_methods.include?(:edit!)
    def edit!
      source_location => [path, lineno]
      if File.file?(path.to_s)
        system(*ENV.fetch('EDITOR').shellsplit, "#{path}:#{lineno}")
      else
        warn(inspect)
      end
    end
  end
end
