package serverimp

import (
	"context"
	"os"
	"strings"
	"time"

	"github.com/mitchellh/mapstructure"
	"github.com/tech/sendico/chain/gateway/internal/keymanager"
	vaultmanager "github.com/tech/sendico/chain/gateway/internal/keymanager/vault"
	gatewayservice "github.com/tech/sendico/chain/gateway/internal/service/gateway"
	"github.com/tech/sendico/chain/gateway/storage"
	gatewaymongo "github.com/tech/sendico/chain/gateway/storage/mongo"
	"github.com/tech/sendico/pkg/api/routers"
	"github.com/tech/sendico/pkg/db"
	"github.com/tech/sendico/pkg/merrors"
	msg "github.com/tech/sendico/pkg/messaging"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/server/grpcapp"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
)

type Imp struct {
	logger mlogger.Logger
	file   string
	debug  bool

	config *config
	app    *grpcapp.App[storage.Repository]
}

type config struct {
	*grpcapp.Config `yaml:",inline"`
	Chains          []chainConfig       `yaml:"chains"`
	ServiceWallet   serviceWalletConfig `yaml:"service_wallet"`
	KeyManagement   keymanager.Config   `yaml:"key_management"`
}

type chainConfig struct {
	Name        string        `yaml:"name"`
	RPCURLEnv   string        `yaml:"rpc_url_env"`
	ChainID     uint64        `yaml:"chain_id"`
	NativeToken string        `yaml:"native_token"`
	Tokens      []tokenConfig `yaml:"tokens"`
}

type serviceWalletConfig struct {
	Chain         string `yaml:"chain"`
	Address       string `yaml:"address"`
	AddressEnv    string `yaml:"address_env"`
	PrivateKeyEnv string `yaml:"private_key_env"`
}

type tokenConfig struct {
	Symbol      string `yaml:"symbol"`
	Contract    string `yaml:"contract"`
	ContractEnv string `yaml:"contract_env"`
}

// Create initialises the chain gateway server implementation.
func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
	return &Imp{
		logger: logger.Named("server"),
		file:   file,
		debug:  debug,
	}, nil
}

func (i *Imp) Shutdown() {
	if i.app == nil {
		return
	}

	timeout := 15 * time.Second
	if i.config != nil && i.config.Runtime != nil {
		timeout = i.config.Runtime.ShutdownTimeout()
	}

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	i.app.Shutdown(ctx)
}

func (i *Imp) Start() error {
	cfg, err := i.loadConfig()
	if err != nil {
		return err
	}
	i.config = cfg

	repoFactory := func(logger mlogger.Logger, conn *db.MongoConnection) (storage.Repository, error) {
		return gatewaymongo.New(logger, conn)
	}

	cl := i.logger.Named("config")
	networkConfigs := resolveNetworkConfigs(cl.Named("network"), cfg.Chains)
	walletConfig := resolveServiceWallet(cl.Named("wallet"), cfg.ServiceWallet)
	keyManager, err := resolveKeyManager(i.logger.Named("key_manager"), cfg.KeyManagement)
	if err != nil {
		return err
	}

	serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
		executor := gatewayservice.NewOnChainExecutor(logger, keyManager)
		opts := []gatewayservice.Option{
			gatewayservice.WithNetworks(networkConfigs),
			gatewayservice.WithServiceWallet(walletConfig),
			gatewayservice.WithKeyManager(keyManager),
			gatewayservice.WithTransferExecutor(executor),
		}
		return gatewayservice.NewService(logger, repo, producer, opts...), nil
	}

	app, err := grpcapp.NewApp(i.logger, "chain_gateway", cfg.Config, i.debug, repoFactory, serviceFactory)
	if err != nil {
		return err
	}
	i.app = app

	return i.app.Start()
}

func (i *Imp) loadConfig() (*config, error) {
	data, err := os.ReadFile(i.file)
	if err != nil {
		i.logger.Error("could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
		return nil, err
	}

	cfg := &config{
		Config: &grpcapp.Config{},
	}
	if err := yaml.Unmarshal(data, cfg); err != nil {
		i.logger.Error("failed to parse configuration", zap.Error(err))
		return nil, err
	}

	if cfg.Runtime == nil {
		cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
	}

	if cfg.GRPC == nil {
		cfg.GRPC = &routers.GRPCConfig{
			Network:          "tcp",
			Address:          ":50070",
			EnableReflection: true,
			EnableHealth:     true,
		}
	}

	return cfg, nil
}

func resolveNetworkConfigs(logger mlogger.Logger, chains []chainConfig) []gatewayservice.Network {
	result := make([]gatewayservice.Network, 0, len(chains))
	for _, chain := range chains {
		if strings.TrimSpace(chain.Name) == "" {
			logger.Warn("skipping unnamed chain configuration")
			continue
		}
		rpcURL := strings.TrimSpace(os.Getenv(chain.RPCURLEnv))
		if rpcURL == "" {
			logger.Warn("chain RPC endpoint not configured", zap.String("chain", chain.Name), zap.String("env", chain.RPCURLEnv))
		}
		contracts := make([]gatewayservice.TokenContract, 0, len(chain.Tokens))
		for _, token := range chain.Tokens {
			symbol := strings.TrimSpace(token.Symbol)
			if symbol == "" {
				logger.Warn("skipping token with empty symbol", zap.String("chain", chain.Name))
				continue
			}
			addr := strings.TrimSpace(token.Contract)
			env := strings.TrimSpace(token.ContractEnv)
			if addr == "" && env != "" {
				addr = strings.TrimSpace(os.Getenv(env))
			}
			if addr == "" {
				if env != "" {
					logger.Warn("token contract not configured", zap.String("token", symbol), zap.String("env", env), zap.String("chain", chain.Name))
				} else {
					logger.Warn("token contract not configured", zap.String("token", symbol), zap.String("chain", chain.Name))
				}
				continue
			}
			contracts = append(contracts, gatewayservice.TokenContract{
				Symbol:          symbol,
				ContractAddress: addr,
			})
		}

		result = append(result, gatewayservice.Network{
			Name:         chain.Name,
			RPCURL:       rpcURL,
			ChainID:      chain.ChainID,
			NativeToken:  chain.NativeToken,
			TokenConfigs: contracts,
		})
	}
	return result
}

func resolveServiceWallet(logger mlogger.Logger, cfg serviceWalletConfig) gatewayservice.ServiceWallet {
	address := strings.TrimSpace(cfg.Address)
	if address == "" && cfg.AddressEnv != "" {
		address = strings.TrimSpace(os.Getenv(cfg.AddressEnv))
	}

	privateKey := strings.TrimSpace(os.Getenv(cfg.PrivateKeyEnv))

	if address == "" {
		if cfg.AddressEnv != "" {
			logger.Warn("service wallet address not configured", zap.String("env", cfg.AddressEnv))
		} else {
			logger.Warn("service wallet address not configured", zap.String("chain", cfg.Chain))
		}
	}
	if privateKey == "" {
		logger.Warn("service wallet private key not configured", zap.String("env", cfg.PrivateKeyEnv))
	}

	return gatewayservice.ServiceWallet{
		Network:    cfg.Chain,
		Address:    address,
		PrivateKey: privateKey,
	}
}

func resolveKeyManager(logger mlogger.Logger, cfg keymanager.Config) (keymanager.Manager, error) {
	driver := strings.ToLower(strings.TrimSpace(string(cfg.Driver)))
	if driver == "" {
		err := merrors.InvalidArgument("key management driver is not configured")
		logger.Error("key management driver missing")
		return nil, err
	}

	switch keymanager.Driver(driver) {
	case keymanager.DriverVault:
		settings := vaultmanager.Config{}
		if len(cfg.Settings) > 0 {
			if err := mapstructure.Decode(cfg.Settings, &settings); err != nil {
				logger.Error("failed to decode vault key manager settings", zap.Error(err), zap.Any("settings", cfg.Settings))
				return nil, merrors.InvalidArgument("invalid vault key manager settings: " + err.Error())
			}
		}
		manager, err := vaultmanager.New(logger, settings)
		if err != nil {
			logger.Error("failed to initialise vault key manager", zap.Error(err))
			return nil, err
		}
		return manager, nil
	default:
		err := merrors.InvalidArgument("unsupported key management driver: " + driver)
		logger.Error("unsupported key management driver", zap.String("driver", driver))
		return nil, err
	}
}
