module MarkdownLint
  # defines a single rule
  class Rule
    attr_accessor :id, :description

    def initialize(id, description, fallback_docs: nil, &)
      @id = id
      @description = description
      @generate_docs = fallback_docs
      @docs_overridden = false
      @aliases = []
      @tags = []
      @params = {}
      instance_eval(&)
    end

    def check(&block)
      @check = block unless block.nil?
      @check
    end

    def fix(&block)
      @fix = block unless block.nil?
      @fix
    end

    def tags(*tags)
      @tags = tags.flatten.map(&:to_sym) unless tags.empty?
      @tags
    end

    def aliases(*aliases)
      @aliases.concat(aliases)
      @aliases
    end

    def params(params = nil)
      unless params.nil?
        # Normalize string values to symbols where the rule's default is
        # a symbol AND the string looks like a simple identifier, so that
        # style files can use either :atx or "atx". Values like "---"
        # (MD035 hr style) are left as strings.
        params = params.each_with_object({}) do |(k, v), h|
          h[k] = if v.is_a?(String) && @params[k].is_a?(Symbol) &&
                    v.match?(/\A[a-z][a-z_]*\z/)
                   v.to_sym
                 else
                   v
                 end
        end
        @params.update(params)
      end
      @params
    end

    def docs(url = nil, &block)
      if block_given? != url.nil?
        raise ArgumentError, 'Give either a URL or a block, not both'
      end

      raise 'A docs url is already set within this rule' if @docs_overridden

      @generate_docs = block_given? ? block : lambda { |_, _| url }
      @docs_overridden = true
    end

    def docs_url
      @generate_docs&.call(id, description)
    end
  end

  # defines a ruleset
  class RuleSet
    attr_reader :rules

    def initialize
      @rules = {}
    end

    def rule(id, description, &)
      @rules[id] =
        Rule.new(id, description, :fallback_docs => @fallback_docs, &)
    end

    def load(rules_file)
      instance_eval(File.read(rules_file), rules_file)
      @rules
    end

    def docs(url = nil, &block)
      if block_given? != url.nil?
        raise ArgumentError, 'Give either a URL or a block, not both'
      end

      @fallback_docs = block_given? ? block : lambda { |_, _| url }
    end

    def load_default
      load(File.expand_path('rules.rb', __dir__))
    end
  end
end
