package command

import (
	"context"
	"fmt"
	"net"
	"os/signal"
	"time"

	"github.com/qsfera/server/pkg/config/configlog"
	"github.com/qsfera/server/pkg/log"
	"github.com/qsfera/server/pkg/registry"
	"github.com/qsfera/server/pkg/runner"
	"github.com/qsfera/server/pkg/tracing"
	"github.com/qsfera/server/services/collaboration/pkg/config"
	"github.com/qsfera/server/services/collaboration/pkg/config/parser"
	"github.com/qsfera/server/services/collaboration/pkg/connector"
	"github.com/qsfera/server/services/collaboration/pkg/helpers"
	"github.com/qsfera/server/services/collaboration/pkg/server/debug"
	"github.com/qsfera/server/services/collaboration/pkg/server/grpc"
	"github.com/qsfera/server/services/collaboration/pkg/server/http"
	"github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool"
	"github.com/opencloud-eu/reva/v2/pkg/store"

	"github.com/spf13/cobra"
	"go-micro.dev/v4/selector"
	microstore "go-micro.dev/v4/store"
)

// Server is the entrypoint for the server command.
func Server(cfg *config.Config) *cobra.Command {
	return &cobra.Command{
		Use:   "server",
		Short: fmt.Sprintf("start the %s service without runtime (unsupervised mode)", cfg.Service.Name),
		PreRunE: func(cmd *cobra.Command, args []string) error {
			return configlog.ReturnFatal(parser.ParseConfig(cfg))
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			logger := log.Configure(cfg.Service.Name, cfg.Commons, cfg.LogLevel)
			traceProvider, err := tracing.GetTraceProvider(cmd.Context(), cfg.Commons.TracesExporter, cfg.Service.Name)
			if err != nil {
				return err
			}

			var cancel context.CancelFunc
			if cfg.Context == nil {
				cfg.Context, cancel = signal.NotifyContext(context.Background(), runner.StopSignals...)
				defer cancel()
			}
			ctx := cfg.Context

			// prepare components
			if err := helpers.RegisterQsferaService(ctx, cfg, logger); err != nil {
				return err
			}

			tm, err := pool.StringToTLSMode(cfg.CS3Api.GRPCClientTLS.Mode)
			if err != nil {
				return err
			}
			gatewaySelector, err := pool.GatewaySelector(
				cfg.CS3Api.Gateway.Name,
				pool.WithTLSCACert(cfg.CS3Api.GRPCClientTLS.CACert),
				pool.WithTLSMode(tm),
				pool.WithRegistry(registry.GetRegistry()),
				pool.WithTracerProvider(traceProvider),
			)
			if err != nil {
				return err
			}

			// use the AppURLs helper (an atomic pointer) to fetch and store the app URLs
			// this is required as the app URLs are fetched periodically in the background
			// and read when handling requests
			appURLs := helpers.NewAppURLs()

			ticker := time.NewTicker(cfg.CS3Api.APPRegistrationInterval)
			defer ticker.Stop()
			go func() {
				for ; true; <-ticker.C {
					// fetch and store the app URLs
					v, err := helpers.GetAppURLs(cfg, logger)
					if err != nil {
						logger.Warn().Err(err).Msg("Failed to get app URLs")
						// empty map to clear previous URLs
						v = make(map[string]map[string]string)
					}
					appURLs.Store(v)

					// register the app provider
					if err := helpers.RegisterAppProvider(ctx, cfg, logger, gatewaySelector, appURLs); err != nil {
						logger.Warn().Err(err).Msg("Failed to register app provider")
					}
				}
			}()

			st := store.Create(
				store.Store(cfg.Store.Store),
				store.TTL(cfg.Store.TTL),
				microstore.Nodes(cfg.Store.Nodes...),
				microstore.Database(cfg.Store.Database),
				microstore.Table(cfg.Store.Table),
				store.Authentication(cfg.Store.AuthUsername, cfg.Store.AuthPassword),
			)

			gr := runner.NewGroup()

			// start GRPC server
			grpcServer, teardown, err := grpc.Server(
				grpc.AppURLs(appURLs),
				grpc.Config(cfg),
				grpc.Logger(logger),
				grpc.TraceProvider(traceProvider),
				grpc.Store(st),
			)
			defer teardown()
			if err != nil {
				logger.Error().Err(err).Str("transport", "grpc").Msg("Failed to initialize server")
				return err
			}

			l, err := net.Listen("tcp", cfg.GRPC.Addr)
			if err != nil {
				return err
			}
			gr.Add(runner.NewGolangGrpcServerRunner(cfg.Service.Name+".grpc", grpcServer, l))

			// start debug server
			debugServer, err := debug.Server(
				debug.Logger(logger),
				debug.Context(ctx),
				debug.Config(cfg),
			)
			if err != nil {
				logger.Error().Err(err).Str("transport", "debug").Msg("Failed to initialize server")
				return err
			}
			gr.Add(runner.NewGolangHttpServerRunner(cfg.Service.Name+".debug", debugServer))

			// start HTTP server
			httpServer, err := http.Server(
				http.Adapter(connector.NewHttpAdapter(gatewaySelector, cfg, st, selector.NewSelector(selector.Registry(registry.GetRegistry())))),
				http.Logger(logger),
				http.Config(cfg),
				http.Context(ctx),
				http.TracerProvider(traceProvider),
				http.Store(st),
			)
			if err != nil {
				logger.Info().Err(err).Str("transport", "http").Msg("Failed to initialize server")
				return err
			}
			gr.Add(runner.NewGoMicroHttpServerRunner("collaboration_http", httpServer))

			grResults := gr.Run(ctx)

			// return the first non-nil error found in the results
			for _, grResult := range grResults {
				if grResult.RunnerError != nil {
					return grResult.RunnerError
				}
			}
			return nil
		},
	}
}
