///|
/// One of the four standard discovery flags that `@lander.cli` enables by
/// default. Pass a value to `StandardFlags::without` when a custom command
/// defines its own option or flag with the same id.
#derive(Eq, Debug)
pub(all) enum StandardFlag {
  /// `--environment `
  Environment
  /// `--config `
  Config
  /// `--isolated`
  Isolated
  /// `--project `
  Project
}

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

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

///|
/// The active set of standard discovery flags for a root argparse command.
/// Pass `options()` and `flags()` to `@argparse.Command` when building a
/// custom command under `@lander.command`, and call `without` to omit any flag
/// that the application defines itself.
#derive(Eq, Debug)
pub struct StandardFlags {
  priv environment : Bool
  priv config : Bool
  priv isolated : Bool
  priv project : Bool
}

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

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

///|
/// A set with all four standard discovery flags enabled.
pub fn StandardFlags::all() -> StandardFlags {
  { environment: true, config: true, isolated: true, project: true, }
}

///|
/// An empty set with no standard discovery flags enabled.
pub fn StandardFlags::none() -> StandardFlags {
  { environment: false, config: false, isolated: false, project: false, }
}

///|
/// Return a new set without `flag`. Earlier sets do not change.
pub fn StandardFlags::without(
  self : StandardFlags,
  flag : StandardFlag,
) -> StandardFlags {
  match flag {
    Environment => { ..self, environment: false, }
    Config => { ..self, config: false, }
    Isolated => { ..self, isolated: false, }
    Project => { ..self, project: false, }
  }
}

///|
/// Whether `flag` is enabled in this set.
pub fn StandardFlags::contains(
  self : StandardFlags,
  flag : StandardFlag,
) -> Bool {
  match flag {
    Environment => self.environment
    Config => self.config
    Isolated => self.isolated
    Project => self.project
  }
}

///|
/// The active standard options (`--environment`, `--config`, `--project`) in
/// deterministic order.
pub fn StandardFlags::options(
  self : StandardFlags,
) -> Array[@argparse.OptionArg] {
  let result : Array[@argparse.OptionArg] = []
  if self.environment {
    result.push(standard_environment_option())
  }
  if self.config {
    result.push(standard_config_option())
  }
  if self.project {
    result.push(standard_project_option())
  }
  result
}

///|
/// The active standard flags (`--isolated`).
pub fn StandardFlags::flags(self : StandardFlags) -> Array[@argparse.FlagArg] {
  if self.isolated {
    [standard_isolated_flag()]
  } else {
    []
  }
}

///|
fn standard_environment_option() -> @argparse.OptionArg {
  @argparse.OptionArg(
    "environment",
    long="environment",
    global=true,
    about="The environment name, for example Staging.",
  )
}

///|
fn standard_config_option() -> @argparse.OptionArg {
  @argparse.OptionArg(
    "config",
    long="config",
    global=true,
    about="The primary configuration file.",
  )
}

///|
fn standard_isolated_flag() -> @argparse.FlagArg {
  @argparse.FlagArg(
    "isolated",
    long="isolated",
    global=true,
    about="Skip the optional configuration layers.",
  )
}

///|
fn standard_project_option() -> @argparse.OptionArg {
  @argparse.OptionArg(
    "project",
    long="project",
    global=true,
    about="The workspace member, by path or name.",
  )
}

///|
priv enum CommandFactory {
  Bare((String) -> @argparse.Command)
  WithStandard((String, StandardFlags) -> @argparse.Command)
}

///|
/// The parsed inputs of a run, before configuration or services exist.
priv struct ParsedArguments {
  matches : @argparse.Matches
  discovery_options : @conventions.DiscoveryOptions
  overrides : @config.ConfigSource?
}

///|
/// A help or version request of the argument parse, with the text that argparse
/// renders. It is not a failure: the driver writes the text one time to standard
/// output, and the run ends with code 0 and the reason `Requested`, before the
/// configuration load (design D6). It is an error, as `StopRequested` is from the
/// factory, so that it ends the run at the parse in each driver.
priv suberror DisplayRequested {
  DisplayRequested(String)
}

///|
/// Parse once before the driver loads configuration or calls the factory.
/// The driver supplies the resolved variable snapshot, shared by all readers.
/// A parse error raises `UsageError`. A help or version request raises
/// `DisplayRequested`. The parse never ends the process.
fn[S] parse_arguments(
  host : Host[S],
  env~ : @sorted_map.SortedMap[String, String],
) -> ParsedArguments raise {
  let active = if host.standard_flags {
    StandardFlags::all()
  } else {
    StandardFlags::none()
  }
  let command = match host.make_command {
    Some(Bare(make)) => make(host.name.to_string())
    Some(WithStandard(make)) => make(host.name.to_string(), active)
    None =>
      @argparse.Command(
        host.name.to_string(),
        options=active.options(),
        flags=active.flags(),
      )
  }
  let matches = match
    command.parse_outcome(argv=host.args[:], env=Map::from_iter(env.iter())) {
    Parsed(matches) => matches
    Help(text) | Version(text) => raise DisplayRequested(text)
    Failed(error) => raise UsageError(error.to_string())
  }
  let environment = standard_option(matches, "environment")
  let config = match standard_option(matches, "config") {
    Some(path) => @config.SourceSelection::Explicit(path)
    None => @config.SourceSelection::Discover
  }
  let project = standard_option(matches, "project")
  let isolated = matches.flags.get("isolated").unwrap_or(false)
  let profiles = profile_options(matches)
  let overrides = if host.mappings.is_empty() {
    None
  } else {
    Some(to_overrides(matches, host.mappings))
  }
  {
    matches,
    discovery_options: @conventions.DiscoveryOptions::new(
      environment?,
      config~,
      isolated~,
      project?,
      profiles~,
    ),
    overrides,
  }
}

///|
/// Standard profile lists are parsed at the argument boundary, including
/// when no profile policy is enabled. The global argparse result preserves
/// repeated option order across subcommands.
fn profile_options(
  matches : @argparse.Matches,
) -> @config.ProfileSelection raise UsageError {
  let values = matches.values.get("profiles").unwrap_or([])
  let disabled = matches.flags.get("no-profiles").unwrap_or(false)
  if disabled && !values.is_empty() {
    raise UsageError("--no-profiles conflicts with --profiles")
  }
  if disabled {
    return Disabled
  }
  if values.is_empty() {
    return Unspecified
  }
  let names = []
  for value in values {
    let parsed = @config.ProfileNames::parse_csv(value, origin=Discovery) catch {
      error => raise UsageError(error.message())
    }
    names.append(parsed.names())
  }
  Selected(@config.ProfileNames::new(names))
}

///|
/// Empty standard values fail at the argument boundary. The host resolves and
/// parses the environment name next. Config and project selectors keep
/// conventions text.
fn standard_option(
  matches : @argparse.Matches,
  id : String,
) -> String? raise UsageError {
  guard matches.values.get(id) is Some([.., value]) else { return None }
  if value.is_empty() {
    raise UsageError("--\{id} requires a non-empty value")
  }
  Some(value)
}

///|
/// Set the command factory. The run gives it the application name and parses
/// its command once, before configuration and hooks.
pub fn[S] command(
  builder : HostBuilder[S],
  make : (String) -> @argparse.Command,
  mappings~ : Array[Mapping] = [],
) -> HostBuilder[S] {
  { ..builder, make_command: Some(Bare(make)), mappings: mappings.copy(), }
}

///|
/// Set a command factory that receives both the application name and the
/// active `StandardFlags` of the host. When `disable_standard_flags` is set,
/// the callback receives `StandardFlags::none()`.
pub fn[S] command_with_standard(
  builder : HostBuilder[S],
  make : (String, StandardFlags) -> @argparse.Command,
  mappings~ : Array[Mapping] = [],
) -> HostBuilder[S] {
  {
    ..builder,
    make_command: Some(WithStandard(make)),
    mappings: mappings.copy(),
  }
}

///|
/// Enable the four standard discovery flags on the default root command and
/// pass `StandardFlags::all()` to `command_with_standard`.
pub fn[S] enable_standard_flags(builder : HostBuilder[S]) -> HostBuilder[S] {
  { ..builder, standard_flags: true, }
}

///|
/// Disable the four standard discovery flags on the default root command and
/// pass `StandardFlags::none()` to `command_with_standard`.
pub fn[S] disable_standard_flags(builder : HostBuilder[S]) -> HostBuilder[S] {
  { ..builder, standard_flags: false, }
}