using System;
using System.Threading;
using CliFx;

namespace MxAccess.Cli
{
    public static class Program
    {
        // The whole CLI runs on a dedicated STA thread. The [STAThread] attribute
        // on Main is necessary but not sufficient: CliFx awaits ICommand.ExecuteAsync,
        // and any thread switch off the COM apartment puts our LMXProxyServer events
        // out of reach. A dedicated thread we own and join eliminates that risk.
        //
        // The COM event pump itself is driven by Application.DoEvents() inside
        // MxSession.WaitForUpdate / PumpOnce — see Mx/MxSession.cs.
        [STAThread]
        public static int Main(string[] args)
        {
            int cliFxExit = 0;
            var thread = new Thread(() =>
            {
                cliFxExit = new CliApplicationBuilder()
                    .SetTitle("mxa")
                    .SetExecutableName("mxa")
                    .SetDescription("Read / write / subscribe AVEVA System Platform tags via MxAccess.")
                    .AddCommandsFromThisAssembly()
                    .Build()
                    .RunAsync(args)
                    .GetAwaiter()
                    .GetResult();
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.IsBackground = false;
            thread.Start();
            thread.Join();

            // CliFx returns its own exit code from RunAsync; commands signal
            // soft failures (e.g. timeout, non-Ok MxStatusCategory) via
            // Environment.ExitCode. Fold both so a failure from either path
            // surfaces as a non-zero process exit.
            return cliFxExit != 0 ? cliFxExit : Environment.ExitCode;
        }
    }
}
