using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.GRAccess.Cli.Session;

namespace ZB.MOM.WW.GRAccess.Cli.Commands.Session
{
    [Command("session status", Description = "Show GRAccess session status")]
    public class SessionStatusCommand : ICommand
    {
        [CommandOption("galaxy", 'g', Description = "Galaxy name", IsRequired = true)]
        public string GalaxyName { get; init; }

        public async ValueTask ExecuteAsync(IConsole console)
        {
            var info = SessionInfo.Load(GalaxyName);
            if (info == null)
            {
                await console.Output.WriteLineAsync("No session found.").ConfigureAwait(false);
                return;
            }

            if (!info.IsAlive())
            {
                await console.Output.WriteLineAsync(
                    "Session file exists but daemon is not running (stale). Cleaning up.")
                    .ConfigureAwait(false);
                info.Delete();
                return;
            }

            await console.Output.WriteLineAsync($"Galaxy:  {info.GalaxyName}").ConfigureAwait(false);
            await console.Output.WriteLineAsync($"Node:    {info.NodeName}").ConfigureAwait(false);
            await console.Output.WriteLineAsync($"PID:     {info.ProcessId}").ConfigureAwait(false);
            await console.Output.WriteLineAsync($"Started: {info.StartedAtUtc:u}").ConfigureAwait(false);
            await console.Output.WriteLineAsync($"Pipe:    {info.PipeName}").ConfigureAwait(false);
        }
    }
}
