=begin
  planner_export.lic — save your character for TP Planner.

  Runs INFO, SKILLS BASE, SKILLS and EXPERIENCE once (quietly), saves their text to
  <Lich data folder>/planner_<Name>.json, and stops. Import that file with the planner's
  Import button. It sends only those four look-up commands and nothing else.

  Usage: ;planner_export
=end

require 'json'

module PlannerExport
  # Lich returns the game's XML; keep just the text.
  def self.text(lines)
    (lines || []).map do |l|
      l.gsub(/<[^>]+>/, '').gsub('&gt;', '>').gsub('&lt;', '<').gsub('&quot;', '"').gsub('&amp;', '&').rstrip
    end
  end

  # Start patterns are matched against the game's raw XML, where names and numbers can be
  # wrapped in tags, so they allow tags anywhere. Table-style output (INFO, SKILLS,
  # EXPERIENCE) also starts with <output class="mono"/>.
  MONO = '<output class="mono"\/>'
  STARTS = {
    'info' => /#{MONO}|Name:.*Race:/,
    'skills base' => /#{MONO}|\(at level/,
    'skills' => /#{MONO}|\(at level/,
    'experience' => /#{MONO}|Level:(?:\s|<[^>]*>)*\d/
  }.freeze

  def self.capture(command)
    lines = text(Lich::Util.quiet_command_xml(command, STARTS.fetch(command), /<prompt/, true, 10))
    echo "#{command.upcase} came back empty." if lines.reject(&:empty?).empty?
    lines
  rescue StandardError => e
    echo "Couldn't read #{command.upcase}: #{e.message}"
    []
  end

  def self.run
    data = {
      'format' => 'gs4-planner-capture',
      'version' => 1,
      'captured_at' => Time.now.utc.strftime('%Y-%m-%dT%H:%M:%SZ'),
      'info' => capture('info'),
      'skills_base' => capture('skills base'),
      'skills' => capture('skills'),
      'experience' => capture('experience')
    }
    unless data['info'].any? { |l| l =~ /Name:.*Race:/ }
      echo 'INFO wasn\'t captured, so nothing was saved. Please send the lines above to the planner\'s author.'
      return
    end
    path = File.join($data_dir || '.', "planner_#{Char.name}.json")
    File.write(path, JSON.pretty_generate(data))
    echo "Saved #{path}"
    echo 'Open TP Planner, choose Import, and pick that file.'
  end
end

PlannerExport.run
