///|
/// A command the CLI, the web UI and the desktop shell all understand. A
/// command is a single word, such as `version`, or a noun and a verb, such as
/// `kb validate`.
#derive(Eq, Debug)
pub(all) enum Command {
  Help
  Version
  Kb(KbCommand)
  Config(ConfigCommand)
}

///|
/// A verb of the `kb` noun, which checks and inspects knowledge bundles.
#derive(Eq, Debug)
pub(all) enum KbCommand {
  Validate
  Rules(RulesCommand)
  Profiles(ProfilesCommand)
}

///|
/// A verb of `kb rules`.
#derive(Eq, Debug)
pub(all) enum RulesCommand {
  List
  Show
  Check
  Test
}

///|
/// A verb of `kb profiles`.
#derive(Eq, Debug)
pub(all) enum ProfilesCommand {
  List
  Show
}

///|
/// A verb of the `config` noun.
#derive(Eq, Debug)
pub(all) enum ConfigCommand {
  Show
}

///|
/// A noun that groups commands. The help text lists each noun once.
#derive(Eq, Debug)
pub(all) enum Noun {
  Kb
  KbRules
  KbProfiles
  Config
}

///|
/// Raised when a text names no command.
#derive(Eq, Debug)
pub(all) suberror CommandError {
  /// The words are not the path or an alias of a command. The text is the
  /// words that were read, joined with spaces, such as `kb nope`.
  UnknownCommand(String)
  /// The words name a noun but no verb, such as `kb`.
  MissingVerb(Noun)
}

///|
/// Every command, in the order that the help text lists them.
pub let commands : ReadOnlyArray[Command] = [
  Kb(Validate),
  Kb(Rules(List)),
  Kb(Rules(Show)),
  Kb(Rules(Check)),
  Kb(Rules(Test)),
  Kb(Profiles(List)),
  Kb(Profiles(Show)),
  Config(Show),
  Help,
  Version,
]

///|
/// The nouns at the top of the command tree, in help order.
pub let nouns : ReadOnlyArray[Noun] = [Kb, Config]

///|
/// Reads a command path, such as `kb validate` or `version`. Words are
/// separated by spaces. `--help`, `-h`, `--version` and `-V` are accepted.
pub fn Command::Command(path : String) -> Command raise CommandError {
  let words = path
    .split(" ")
    .filter(w => w.length() > 0)
    .map(w => w.to_owned())
    .collect()
  let (command, rest) = Command::parse(words)
  guard rest.length() == 0 else { raise UnknownCommand(words.join(" ")) }
  command
}

///|
/// Reads the command at the start of the arguments, and returns it with the
/// arguments that follow it. No arguments is the help command.
pub fn Command::parse(
  args : ArrayView[String],
) -> (Command, ArrayView[String]) raise CommandError {
  // The verb after a noun; a missing verb or an option ends the path.
  fn verb(i : Int32) -> String? {
    match args.get(i) {
      Some(word) if !word.has_prefix("-") => Some(word)
      _ => None
    }
  }

  fn unknown(n : Int32) -> CommandError {
    UnknownCommand(args[0:n].iter().collect().join(" "))
  }

  match args.get(0) {
    None => (Help, args)
    Some("help" | "--help" | "-h") => (Help, args[1:])
    Some("version" | "--version" | "-V") => (Version, args[1:])
    Some("kb") =>
      match verb(1) {
        None => raise MissingVerb(Kb)
        Some("validate") => (Kb(Validate), args[2:])
        Some("rules") =>
          match verb(2) {
            None => raise MissingVerb(KbRules)
            Some("list") => (Kb(Rules(List)), args[3:])
            Some("show") => (Kb(Rules(Show)), args[3:])
            Some("check") => (Kb(Rules(Check)), args[3:])
            Some("test") => (Kb(Rules(Test)), args[3:])
            Some(_) => raise unknown(3)
          }
        Some("profiles") =>
          match verb(2) {
            None => raise MissingVerb(KbProfiles)
            Some("list") => (Kb(Profiles(List)), args[3:])
            Some("show") => (Kb(Profiles(Show)), args[3:])
            Some(_) => raise unknown(3)
          }
        Some(_) => raise unknown(2)
      }
    Some("config") =>
      match verb(1) {
        None => raise MissingVerb(Config)
        Some("show") => (Config(Show), args[2:])
        Some(_) => raise unknown(2)
      }
    Some(_) => raise unknown(1)
  }
}

///|
/// The words of the command on the command line, such as `["kb", "validate"]`.
pub fn Command::path(self : Command) -> Array[String] {
  match self {
    Help => ["help"]
    Version => ["version"]
    Kb(Validate) => ["kb", "validate"]
    Kb(Rules(verb)) =>
      [
        "kb",
        "rules",
        match verb {
          List => "list"
          Show => "show"
          Check => "check"
          Test => "test"
        },
      ]
    Kb(Profiles(verb)) =>
      [
        "kb",
        "profiles",
        match verb {
          List => "list"
          Show => "show"
        },
      ]
    Config(Show) => ["config", "show"]
  }
}

///|
/// The command path as one text, such as `kb validate`.
pub fn Command::path_text(self : Command) -> String {
  self.path().join(" ")
}

///|
/// The noun that the command belongs to. `help` and `version` have none.
pub fn Command::noun(self : Command) -> Noun? {
  match self {
    Help | Version => None
    Kb(Validate) => Some(Kb)
    Kb(Rules(_)) => Some(KbRules)
    Kb(Profiles(_)) => Some(KbProfiles)
    Config(_) => Some(Config)
  }
}

///|
/// The ID of the Proton command that the desktop shell exposes: the path
/// joined with `.` after `mission-control.`.
pub fn Command::proton_id(self : Command) -> String {
  "mission-control." + self.path().join(".")
}

///|
/// One line that describes the command in the help text.
pub fn Command::description(self : Command) -> String {
  match self {
    Help => "Print this help"
    Version => "Print the version"
    Kb(Validate) => "Check bundles, sets of documents or one document"
    Kb(Rules(List)) => "List the active rules"
    Kb(Rules(Show)) => "Show one rule and where it comes from"
    Kb(Rules(Check)) => "Check that rule packs parse"
    Kb(Rules(Test)) => "Run the test cases of rule packs"
    Kb(Profiles(List)) => "List the built-in profiles"
    Kb(Profiles(Show)) => "Show the keys and rules of one profile"
    Config(Show) =>
      "Show the merged configuration and where each value comes from"
  }
}

///|
/// The words of the noun on the command line, such as `["kb", "rules"]`.
pub fn Noun::path(self : Noun) -> Array[String] {
  match self {
    Kb => ["kb"]
    KbRules => ["kb", "rules"]
    KbProfiles => ["kb", "profiles"]
    Config => ["config"]
  }
}

///|
/// The noun path as one text, such as `kb rules`.
pub fn Noun::path_text(self : Noun) -> String {
  self.path().join(" ")
}

///|
/// One line that describes the noun in the help text.
pub fn Noun::description(self : Noun) -> String {
  match self {
    Kb => "Check and inspect knowledge bundles"
    KbRules => "List, show, check and test rules"
    KbProfiles => "List and show profiles"
    Config => "Show the configuration"
  }
}

///|
/// The commands whose path starts with the path of the noun, in help order.
pub fn Noun::commands(self : Noun) -> Array[Command] {
  let prefix = self.path()
  commands.iter().filter(c => extends_path(c.path(), prefix)).collect()
}

///|
/// True when `path` is longer than `prefix` and starts with its words.
fn extends_path(path : Array[String], prefix : Array[String]) -> Bool {
  guard path.length() > prefix.length() else { return false }
  for i, word in prefix {
    guard path[i] == word else { return false }
  }
  true
}

///|
/// Raised when a text is not a version.
#derive(Eq, Debug)
pub(all) suberror VersionError {
  /// The text is not three non-negative integers joined with `.`, without
  /// leading zeros.
  InvalidVersion(String)
}

///|
/// A version such as `0.0.2`: three non-negative integer parts.
#derive(Eq, Compare, Hash, Debug)
struct Version {
  major : Int32
  minor : Int32
  patch : Int32
}

///|
/// Parses `X.Y.Z`. Each part is a non-negative integer with at most nine
/// digits and no leading zero.
pub fn Version::Version(text : String) -> Version raise VersionError {
  let parts = text.split(".").map(p => p.to_owned()).collect()
  guard parts.length() == 3 else { raise InvalidVersion(text) }
  let numbers = []
  for part in parts {
    let ok = part.length() > 0 &&
      part.length() <= 9 &&
      part.iter().all(c => c >= '0' && c <= '9') &&
      !(part.length() > 1 && part.has_prefix("0"))
    guard ok else { raise InvalidVersion(text) }
    let mut n = 0
    for c in part {
      n = n * 10 + (c.to_int() - '0'.to_int())
    }
    numbers.push(n)
  }
  { major: numbers[0], minor: numbers[1], patch: numbers[2], }
}

///|
pub fn Version::major(self : Version) -> Int32 {
  self.major
}

///|
pub fn Version::minor(self : Version) -> Int32 {
  self.minor
}

///|
pub fn Version::patch(self : Version) -> Int32 {
  self.patch
}

///|
pub fn Version::to_string(self : Version) -> String {
  "\{self.major}.\{self.minor}.\{self.patch}"
}

///|
pub impl Show for Version with fn output(self, logger) {
  logger.write_string(self.to_string())
}

///|
/// The version text of this module. `scripts/versions.mbtx` sets it to the
/// workspace version.
let current_version : String = "0.3.0"

///|
/// The version of this module. It matches the workspace version.
pub fn Version::current() -> Version {
  // A test checks that the text above parses.
  Version::Version(current_version) catch {
    _ => abort("the contract version is not a version: \{current_version}")
  }
}

///|
/// The version of this module. It matches the workspace version.
pub fn version() -> Version {
  Version::current()
}

///|
pub extend Command with Eq::{not_equal, equal}

///|
pub extend Command with @debug.Debug::{to_repr}

///|
pub extend KbCommand with Eq::{not_equal, equal}

///|
pub extend KbCommand with @debug.Debug::{to_repr}

///|
pub extend RulesCommand with Eq::{not_equal, equal}

///|
pub extend RulesCommand with @debug.Debug::{to_repr}

///|
pub extend ProfilesCommand with Eq::{not_equal, equal}

///|
pub extend ProfilesCommand with @debug.Debug::{to_repr}

///|
pub extend ConfigCommand with Eq::{not_equal, equal}

///|
pub extend ConfigCommand with @debug.Debug::{to_repr}

///|
pub extend Noun with Eq::{not_equal, equal}

///|
pub extend Noun with @debug.Debug::{to_repr}

///|
pub extend CommandError with Eq::{not_equal, equal}

///|
pub extend CommandError with @debug.Debug::{to_repr}

///|
pub extend VersionError with Eq::{not_equal, equal}

///|
pub extend VersionError with @debug.Debug::{to_repr}

///|
pub extend Version with Eq::{not_equal, equal}

///|
pub extend Version with Compare::{op_lt, op_le, op_ge, compare, op_gt}

///|
pub extend Version with Hash::{hash, hash_combine}

///|
pub extend Version with @debug.Debug::{to_repr}

///|
pub extend Version with Show::{output}