using System.Linq;
using System.Threading.Tasks;
using CliFx;
using Serilog;
using ZB.MOM.WW.GRAccess.Cli.Session;

namespace ZB.MOM.WW.GRAccess.Cli
{
    internal static class Program
    {
        [System.STAThread]
        static async Task<int> Main(string[] args)
        {
            // Hidden daemon mode: graccess.exe --daemon --galaxy X --node Y
            if (args.Length >= 1 && args[0] == "--daemon")
                return SessionDaemon.Run(args);

            // Normal CLI mode. Machine JSON must remain parseable on stdout.
            var llmJson = args.Any(arg => arg == "--llm-json");
            Log.Logger = llmJson
                ? new LoggerConfiguration().CreateLogger()
                : new LoggerConfiguration()
                    .WriteTo.Console()
                    .CreateLogger();

            try
            {
                return await new CliApplicationBuilder()
                    .SetTitle("GRAccess CLI")
                    .SetDescription("Aveva System Platform Galaxy management")
                    .AddCommandsFromThisAssembly()
                    .Build()
                    .RunAsync(args);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}
