module Adr
  # The generated docs/adr/README.md. Always regenerated in full from the
  # directory contents — never appended to, never hand-edited. Content outside
  # the markers is preserved so projects can add prose around the table.
  class Index
    BEGIN_MARKER = "<!-- adr-index:begin -->"
    END_MARKER = "<!-- adr-index:end -->"

    DEFAULT_SKELETON = <<~MD
      <!-- Generated by os-adr. Do not hand-edit the table: it is regenerated in full on every ADR write. -->

      # Architecture Decision Records

      One file per decision, `NNNN-kebab-title.md`, created via `/os-adr:create`.

      #{BEGIN_MARKER}
      #{END_MARKER}
    MD

    def initialize(repository:)
      @repository = repository
    end

    def regenerate!
      File.write(@repository.index_path, content)
    end

    def content
      base = if File.exist?(@repository.index_path) && File.read(@repository.index_path).include?(BEGIN_MARKER)
               File.read(@repository.index_path)
             else
               DEFAULT_SKELETON
             end
      before, _stale, after = split(base)
      "#{before}#{BEGIN_MARKER}\n#{table}#{END_MARKER}#{after}"
    end

    private

    def split(text)
      before, rest = text.split(BEGIN_MARKER, 2)
      _stale, after = rest.split(END_MARKER, 2)
      [before, _stale, after]
    end

    def table
      rows = @repository.entries.map do |entry|
        record = entry.record
        "| #{record.id} | [#{record.title}](#{File.basename(entry.path)}) " \
          "| #{record.status} | #{record.date} |"
      end
      return "" if rows.empty?

      <<~MD
        | ID | Title | Status | Date |
        | --- | --- | --- | --- |
        #{rows.join("\n")}
      MD
    end
  end
end
