// Copyright 2023-2024 Gentoo Authors
// Distributed under the terms of the GNU General Public License v2

namespace Gdmt.Launcher

module Dispatcher =
    open SimpleLog.SimpleLog

    open Gdmt.Shared
    open Gdmt.Shared.Types

    open Gdmt.Launcher.Subcommands

    let Dispatch (args: StringList) : int =
        match args with
        | [] ->
            LogMessage Error $"No GDMT subcommand given"

            1
        | [ "--help" ]
        | [ "-h" ]
        | [ "help" ] ->
            printfn " Provide \"list\" or a GDMT subcommand with arguments."

            0
        | [ "--list" ]
        | [ "list" ] ->
            LogMessage Debug $"{GdmtSubcommands.Length} GDMT subcommands are available"
            printfn " Following GDMT subcommands are available: %s" (GdmtSubcommands |> String.concat ", ")

            0
        | subcommandName :: subcommandArguments ->
            match subcommandName with
            | sc when Array.contains sc GdmtSubcommands ->
                // Supported.
                ()
            | sc ->
                LogMessage Error $"Subcommand {sc} is not officially supported"
                LogMessage Error $"Providing {sc} can be a spelling mistake"

            try
                let arguments = subcommandArguments |> List.map (fun s -> sprintf "'%s'" s)
                ExecProcess($"gdmt-{subcommandName}" :: arguments).Run().Check()

                0
            with _ex ->
                LogMessage Error $"Subcommand {subcommandName} failed"

                1
