#!/usr/bin/env ruby
# Non-destructive mechanical migration pass.
#
#   adr-migrate [--root DIR]                  convert detected units into new
#                                             ADRs under docs/adr/; print the
#                                             work manifest (JSON) of fields
#                                             needing LLM fill
#   adr-migrate [--root DIR] --apply-fills F  apply LLM fills from JSON file F
#                                             ({relpath: {field: text}}); only
#                                             pending-marker fields are fillable
#
# Never deletes, moves, or edits source files; writes only under docs/adr/.

require "json"
require "fileutils"
require_relative "../lib/adr"

root = Dir.pwd
fills_path = nil
ARGV.each_with_index do |arg, i|
  root = ARGV[i + 1] if arg == "--root"
  fills_path = ARGV[i + 1] if arg == "--apply-fills"
end

repo = Adr::Repository.new(root: root)
FileUtils.mkdir_p(repo.dir)
migrator = Adr::Migrator.new(repository: repo, detector: Adr::Detector.new(root: root))

if fills_path
  migrator.apply_fills!(JSON.parse(File.read(fills_path)))
  puts JSON.pretty_generate("applied" => true,
                            "report" => File.join("docs", "adr", Adr::MigrationReport::FILENAME))
else
  puts JSON.pretty_generate(migrator.migrate!)
end
