#!/usr/bin/env ruby
# frozen_string_literal: true
#
# os-backlog CLI: board-ensure, activate, archive.
#
# Usage:
#   os-backlog board-ensure NAME --project Dev|Clients
#   os-backlog activate NAME
#   os-backlog archive NAME --yes
#
# Talks to Planka over the network (the installed planka-api gem,
# credentials from PLANKA_BASE_URL/USERNAME/PASSWORD).
#
# Fails soft: if the gem or Planka credentials are unavailable, prints one
# clear error and exits nonzero. Never destructive.

require_relative "../lib/backlog"

def fail_soft(message)
  warn "os-backlog: #{message}"
  exit 1
end

def build_client
  require "planka_api"
  client = Planka::Client.new
  client.login
  client
rescue LoadError
  fail_soft("the planka-api gem is not installed/loadable; cannot reach Planka")
rescue StandardError => e
  fail_soft("could not authenticate to Planka: #{e.message}")
end

def parse_project_flag(args)
  idx = args.index("--project")
  return "Dev" unless idx

  args.delete_at(idx)
  project = args.delete_at(idx)
  project || fail_soft("--project requires a value (Dev or Clients)")
end

command, *rest = ARGV

case command
when "board-ensure"
  name = rest.shift
  fail_soft("board-ensure requires a board name") unless name
  project = parse_project_flag(rest)
  client = build_client
  result = Backlog::BoardEnsurer.new(client: client).ensure(name, project_name: project)
  puts "board #{result.board['name']} (#{result.created ? 'created' : 'existing'}) " \
       "in project #{project}; lists created: #{result.lists_created.join(', ')}; " \
       "labels created: #{result.labels_created.join(', ')}"
when "activate"
  name = rest.shift
  fail_soft("activate requires a board name") unless name
  client = build_client
  board = Backlog::BoardEnsurer.new(client: client).activate(name)
  puts "activated: #{board['name']}"
when "archive"
  name = rest.shift
  fail_soft("archive requires a board name") unless name
  fail_soft("archive requires explicit --yes (human go-ahead only)") unless rest.include?("--yes")

  client = build_client
  board = Backlog::BoardEnsurer.new(client: client).archive(name)
  puts "archived: #{board['name']}"
when nil, "-h", "--help"
  puts <<~USAGE
    usage: os-backlog <command> [options]

    commands:
      board-ensure NAME --project Dev|Clients
      activate NAME
      archive NAME --yes
  USAGE
  exit(command.nil? ? 1 : 0)
else
  fail_soft("unknown command #{command.inspect}")
end
