///|
/// The version of the app that a user asks for.
#derive(Eq, Debug)
pub(all) enum VersionChoice {
  Newest
  Exact(@contracts.Version)
}

///|
/// A release of the app that a provider can install.
#derive(Eq, Debug)
pub(all) struct DesktopRelease {
  version : @contracts.Version
  /// The archives for this machine. A provider that installs without archives has none.
  files : ReleaseFiles?
}

///|
/// An app that is installed for an instance.
#derive(Eq, Debug)
pub(all) struct InstalledApp {
  instance : @app.InstanceName
  /// An app that an older `mise run desktop:install` made does not say its version.
  version : @contracts.Version?
  /// The program that `mission-control desktop` starts.
  program : @core.FolderPath
}

///|
/// A step of an installation, in the order in which the steps occur.
#derive(Eq, Debug)
pub(all) enum InstallEvent {
  /// The installation gets an archive now.
  ArchiveStarted(ArchiveFile)
  /// More of the archive is there. The parts grow.
  ArchiveProgress(ReceivedPart)
  /// The installed app has the engine of the release, so the new app gets a copy.
  EngineKept(EngineId)
  /// The new app is complete and replaces the old one now.
  Replacing
  /// A step that the app does not need did not work. The text is a sentence for people.
  Incomplete(String)
  /// The new app is in its place.
  Installed(@contracts.Version)
}

///|
/// Raised when a source cannot give a release. Each text is a sentence for people.
#derive(Eq, Debug)
pub(all) suberror SourceError {
  /// The source has no release of the app with this version.
  NoRelease(VersionChoice, source~ : String)
  /// The list of the release is wrong, or a newer command is necessary.
  BadRelease(ReleaseError, source~ : String)
  /// The source did not give a file.
  NotReceived(String)
}

///|
/// Raised when a provider did not do its work. The installed app then did not change.
/// Each text is a sentence for people.
#derive(Eq, Debug)
pub(all) suberror ProviderError {
  /// The releases have no app for the operating system and the processor, such as
  /// `linux-arm64`.
  NoAppForMachine(String)
  FromSource(SourceError)
  /// The archive does not have the size or the SHA-256 of the list.
  WrongArchive(FileName)
  /// The app in the folder runs.
  AppRuns(folder~ : @core.FolderPath)
  /// Another run changes the app of the instance.
  OtherRun(@app.InstanceName)
  Failed(String)
}

///|
/// Installs the desktop app and says which one is installed. `mission-control desktop
/// install` and `mission-control desktop update` use only this trait, so another program
/// can give another installation, for example one with a signed installer.
pub(open) trait DesktopProvider {
  /// The app of this instance only. The app of another instance is not an answer.
  async fn installed(Self, @app.InstanceName) -> InstalledApp? raise ProviderError
  /// The release that `install` can install. It changes nothing.
  async fn available(Self, VersionChoice) -> DesktopRelease raise ProviderError
  /// Installs the release in the place of the app of this instance. After an error, the
  /// old app is complete and opens.
  async fn install(
    Self,
    @app.InstanceName,
    DesktopRelease,
    report~ : async (InstallEvent) -> Unit noraise,
  ) -> InstalledApp raise ProviderError
}

///|
/// Gives the files of the releases. The installation checks the size and the SHA-256 of
/// each archive, so a source has no check.
pub(open) trait ReleaseSource {
  /// The list of the newest release, or of one version.
  async fn release(Self, VersionChoice) -> ReleaseList raise SourceError
  /// Gives the bytes of an archive of the release with this version, in their order.
  /// `write` raises an error to stop the source, and the source passes it on.
  async fn fetch(
    Self,
    @contracts.Version,
    ArchiveFile,
    write~ : async (BytesView) -> Unit,
  ) -> Unit
}

///|
/// What an installation gets from its source.
#derive(Eq, Debug)
pub(all) enum InstallPlan {
  /// The machine has the engine, so only the app comes from the source.
  AppOnly(app~ : ArchiveFile, EngineId)
  AppAndEngine(app~ : ArchiveFile, engine~ : ArchiveFile, EngineId)
}

///|
/// Selects the archives. `here` is the engine that the machine has and that is complete.
pub fn InstallPlan::InstallPlan(
  files : ReleaseFiles,
  here : EngineId?,
) -> InstallPlan {
  if here == Some(files.engine_id) {
    AppOnly(app=files.app, files.engine_id)
  } else {
    AppAndEngine(app=files.app, engine=files.engine, files.engine_id)
  }
}

///|
/// The problem, as text for people.
pub fn SourceError::message(self : SourceError) -> String {
  match self {
    NoRelease(Newest, source~) => "\{source} has no release of the desktop app."
    NoRelease(Exact(version), source~) =>
      "\{source} has no desktop app of the version \{version.to_string()}."
    BadRelease(NewerFormat(_) as error, source~) =>
      "A newer mission-control is necessary for the release in \{source}. \{error.message()} This command has the version \{@contracts.version().to_string()}."
    BadRelease(error, source~) =>
      "The release in \{source} cannot be used. \{error.message()}"
    NotReceived(text) => text
  }
}

///|
/// The problem, as text for people.
pub fn ProviderError::message(self : ProviderError) -> String {
  match self {
    NoAppForMachine(machine) =>
      "There is no desktop app for \{machine}. Use the same UI in your browser: mission-control web"
    FromSource(error) => error.message()
    WrongArchive(name) =>
      "The archive \{name.to_string()} is damaged: its size or its SHA-256 is not the one of the release. Run the command again."
    AppRuns(folder~) =>
      "The desktop app in \{folder.to_string()} runs. Close its windows and stop its servers. 'mission-control status' shows the instances that run, because the app can also serve an instance with another name. 'mission-control stop --instance NAME' stops one. Then run the command again."
    OtherRun(instance) =>
      "Another run changes the app of the instance \{instance.to_string()} now. Wait for its end, and then run the command again."
    Failed(text) => text
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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