require_relative "test_helper"
require "tmpdir"
require "json"

class WakeupTest < Minitest::Test
  W = Backlog::Wakeup

  def test_tier_mapping
    assert_equal :afk_ready, W.tier("afk-ready")
    assert_equal :afk_ready, W.tier("bug, afk-ready")
    assert_equal :semi, W.tier("semi")
    assert_equal :notify, W.tier("hitl")
    assert_equal :notify, W.tier("")
    assert_equal :notify, W.tier(nil)
  end

  def test_eligible_projects_requires_git_tracker_and_optin
    projects = {
      "/p/planka" => { "name" => "planka-proj", "tracker" => "planka:board" },
      "/p/forgejo-in" => { "name" => "fin", "tracker" => "forgejo:jared/fin" },
      "/p/forgejo-out" => { "name" => "fout", "tracker" => "forgejo:jared/fout" },
      "/p/github-in" => { "name" => "gin", "tracker" => "github:jared/gin" }
    }
    reader = ->(path) { path.end_with?("-in") ? "tracker=x\nwakeup=true\n" : "tracker=x\n" }
    rows = W.eligible_projects(projects, config_reader: reader)
    assert_equal %w[/p/forgejo-in /p/github-in], rows.map { |r| r[:path] }
    assert_equal "jared/fin", rows.first[:repo_slug]
    assert_equal "forgejo", rows.first[:tracker_kind]
  end

  def test_new_issues_baselines_on_nil_last_seen
    issues = [{ "index" => "5" }, { "index" => "3" }]
    assert_equal [], W.new_issues(issues, nil)
    assert_equal [{ "index" => "5" }], W.new_issues(issues, 3)
    assert_equal 5, W.highest_index(issues)
    assert_equal 9, W.highest_index(issues, 9)
  end

  def test_tmux_command_follows_adr_0036_naming
    cmd = W.tmux_command(project: "llf-schema", path: "/p/llf", issue_index: "12", prompt: "hi")
    assert_equal %w[tmux new-session -d -s cc-llf-schema-issue12 -c /p/llf claude hi], cmd
  end

  def test_session_prompt_carries_tier_and_body
    issue = { "index" => "7", "title" => "T", "body" => "Body\n**Discoverer:** x" }
    semi = W.session_prompt(issue: issue, tier: :semi, url: "u")
    assert_includes semi, "TRIAGE ONLY"
    assert_includes semi, "**Discoverer:** x"
    afk = W.session_prompt(issue: issue, tier: :afk_ready, url: "u")
    assert_includes afk, "afk-ready"
  end

  def test_state_reads_missing_as_empty_and_records_atomically
    Dir.mktmpdir do |dir|
      state = W::State.new(path: File.join(dir, "wakeup-state.json"))
      assert_nil state.last_seen("jared/x")
      state.record("jared/x", 7)
      assert_equal 7, W::State.new(path: File.join(dir, "wakeup-state.json")).last_seen("jared/x")
    end
  end
end
