using System.CommandLine;
using System.CommandLine.Parsing;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;

namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;

public static class DeployCommands
{
    /// <summary>
    /// Builds the <c>deploy</c> command group with all sub-commands.
    /// </summary>
    /// <param name="urlOption">Global management URL option.</param>
    /// <param name="formatOption">Global output format option.</param>
    /// <param name="usernameOption">Global username option.</param>
    /// <param name="passwordOption">Global password option.</param>
    /// <returns>The configured <c>deploy</c> <see cref="Command"/> with all sub-commands attached.</returns>
    public static Command Build(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
    {
        var command = new Command("deploy") { Description = "Deployment operations" };

        command.Add(BuildInstance(urlOption, formatOption, usernameOption, passwordOption));
        command.Add(BuildSite(urlOption, formatOption, usernameOption, passwordOption));
        command.Add(BuildArtifacts(urlOption, formatOption, usernameOption, passwordOption));
        command.Add(BuildStatus(urlOption, formatOption, usernameOption, passwordOption));

        return command;
    }

    private static Command BuildInstance(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
    {
        var idOption = new Option<int>("--id") { Description = "Instance ID", Required = true };
        var cmd = new Command("instance") { Description = "Deploy a single instance" };
        cmd.Add(idOption);
        cmd.SetAction(async (ParseResult result) =>
        {
            var id = result.GetValue(idOption);
            return await CommandHelpers.ExecuteCommandAsync(
                result, urlOption, formatOption, usernameOption, passwordOption, new MgmtDeployInstanceCommand(id));
        });
        return cmd;
    }

    /// <summary>
    /// Builds <c>deploy site</c> — bulk-deploy every instance at one site.
    ///
    /// <para>
    /// Sits under <c>deploy</c> alongside <c>deploy instance</c> and
    /// <c>deploy artifacts</c>, naming the SCOPE of the deploy as the verb, which
    /// is the convention the group already follows. Note it is deliberately NOT
    /// fleet-wide when <c>--site-id</c> is omitted (the pattern <c>deploy
    /// artifacts</c> uses): a bulk instance deploy is far more consequential than
    /// an artifact push, so the target site is required rather than defaulted.
    /// </para>
    /// </summary>
    private static Command BuildSite(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
    {
        var siteIdOption = new Option<int>("--site-id") { Description = "Target site ID", Required = true };
        var cmd = new Command("site") { Description = "Deploy every deployable instance at a site" };
        cmd.Add(siteIdOption);
        cmd.SetAction(async (ParseResult result) =>
        {
            var siteId = result.GetValue(siteIdOption);
            return await CommandHelpers.ExecuteCommandAsync(
                result, urlOption, formatOption, usernameOption, passwordOption,
                new MgmtDeploySiteCommand(siteId),
                // A bulk deploy is N instance round-trips; the default 30 s client
                // timeout would abandon the request while the server is still
                // applying. Matches the server-side long-running Ask window.
                timeout: BulkDeployTimeout);
        });
        return cmd;
    }

    /// <summary>
    /// Client-side timeout for the bulk site deploy, matching the management
    /// service's long-running command Ask window.
    /// </summary>
    internal static readonly TimeSpan BulkDeployTimeout = TimeSpan.FromMinutes(5);

    private static Command BuildArtifacts(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
    {
        var siteIdOption = new Option<int?>("--site-id") { Description = "Target site ID (all sites if omitted)" };
        var cmd = new Command("artifacts") { Description = "Deploy artifacts to site(s)" };
        cmd.Add(siteIdOption);
        cmd.SetAction(async (ParseResult result) =>
        {
            var siteId = result.GetValue(siteIdOption);
            return await CommandHelpers.ExecuteCommandAsync(
                result, urlOption, formatOption, usernameOption, passwordOption, new MgmtDeployArtifactsCommand(siteId));
        });
        return cmd;
    }

    private static Command BuildStatus(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
    {
        var instanceIdOption = new Option<int?>("--instance-id") { Description = "Filter by instance ID" };
        var statusOption = new Option<string?>("--status") { Description = "Filter by status" };
        var pageOption = new Option<int>("--page") { Description = "Page number" };
        pageOption.DefaultValueFactory = _ => 1;
        var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" };
        pageSizeOption.DefaultValueFactory = _ => 50;

        var cmd = new Command("status") { Description = "Query deployment status" };
        cmd.Add(instanceIdOption);
        cmd.Add(statusOption);
        cmd.Add(pageOption);
        cmd.Add(pageSizeOption);
        cmd.SetAction(async (ParseResult result) =>
        {
            var instanceId = result.GetValue(instanceIdOption);
            var status = result.GetValue(statusOption);
            var page = result.GetValue(pageOption);
            var pageSize = result.GetValue(pageSizeOption);
            return await CommandHelpers.ExecuteCommandAsync(
                result, urlOption, formatOption, usernameOption, passwordOption,
                new QueryDeploymentsCommand(instanceId, status, page, pageSize));
        });
        return cmd;
    }
}
