// Copyright 2023 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package featurecontrol

import (
	"errors"
	"fmt"
	"log/slog"
	"strings"
)

const (
	FeatureAlertNamesInMetrics   = "alert-names-in-metrics"
	FeatureReceiverNameInMetrics = "receiver-name-in-metrics"
	FeatureGroupKeyInMetrics     = "group-key-in-metrics"
	FeatureClassicMode           = "classic-mode"
	FeatureUTF8StrictMode        = "utf8-strict-mode"
	FeatureAutoGOMEMLIMIT        = "auto-gomemlimit"
	FeatureEventRecorder         = "event-recorder"
)

var AllowedFlags = []string{
	FeatureAlertNamesInMetrics,
	FeatureReceiverNameInMetrics,
	FeatureGroupKeyInMetrics,
	FeatureClassicMode,
	FeatureUTF8StrictMode,
	FeatureAutoGOMEMLIMIT,
	FeatureEventRecorder,
}

type Flagger interface {
	EnableAlertNamesInMetrics() bool
	EnableReceiverNamesInMetrics() bool
	EnableGroupKeyInMetrics() bool
	ClassicMode() bool
	UTF8StrictMode() bool
	EnableAutoGOMEMLIMIT() bool
	EnableEventRecorder() bool
}

type Flags struct {
	logger                       *slog.Logger
	enableAlertNamesInMetrics    bool
	enableReceiverNamesInMetrics bool
	enableGroupKeyInMetrics      bool
	classicMode                  bool
	utf8StrictMode               bool
	enableAutoGOMEMLIMIT         bool
	enableEventRecorder          bool
}

func (f *Flags) EnableAlertNamesInMetrics() bool {
	return f.enableAlertNamesInMetrics
}

func (f *Flags) EnableReceiverNamesInMetrics() bool {
	return f.enableReceiverNamesInMetrics
}

func (f *Flags) EnableGroupKeyInMetrics() bool {
	return f.enableGroupKeyInMetrics
}

func (f *Flags) ClassicMode() bool {
	return f.classicMode
}

func (f *Flags) UTF8StrictMode() bool {
	return f.utf8StrictMode
}

func (f *Flags) EnableAutoGOMEMLIMIT() bool {
	return f.enableAutoGOMEMLIMIT
}

func (f *Flags) EnableEventRecorder() bool {
	return f.enableEventRecorder
}

type flagOption func(flags *Flags)

func enableReceiverNameInMetrics() flagOption {
	return func(configs *Flags) {
		configs.enableReceiverNamesInMetrics = true
	}
}

func enableGroupKeyInMetrics() flagOption {
	return func(configs *Flags) {
		configs.enableGroupKeyInMetrics = true
	}
}

func enableClassicMode() flagOption {
	return func(configs *Flags) {
		configs.classicMode = true
	}
}

func enableUTF8StrictMode() flagOption {
	return func(configs *Flags) {
		configs.utf8StrictMode = true
	}
}

func enableAutoGOMEMLIMIT() flagOption {
	return func(configs *Flags) {
		configs.enableAutoGOMEMLIMIT = true
	}
}

func enableEventRecorder() flagOption {
	return func(configs *Flags) {
		configs.enableEventRecorder = true
	}
}

func enableAlertNamesInMetrics() flagOption {
	return func(configs *Flags) {
		configs.enableAlertNamesInMetrics = true
	}
}

func NewFlags(logger *slog.Logger, features string) (Flagger, error) {
	fc := &Flags{logger: logger}
	opts := []flagOption{}

	if len(features) == 0 {
		return NoopFlags{}, nil
	}

	for feature := range strings.SplitSeq(features, ",") {
		switch feature {
		case FeatureAlertNamesInMetrics:
			opts = append(opts, enableAlertNamesInMetrics())
			logger.Warn("Alert names in metrics enabled")
		case FeatureReceiverNameInMetrics:
			opts = append(opts, enableReceiverNameInMetrics())
			logger.Warn("Experimental receiver name in metrics enabled")
		case FeatureGroupKeyInMetrics:
			opts = append(opts, enableGroupKeyInMetrics())
			logger.Warn("Experimental group key in metrics enabled")
		case FeatureClassicMode:
			opts = append(opts, enableClassicMode())
			logger.Warn("Classic mode enabled")
		case FeatureUTF8StrictMode:
			opts = append(opts, enableUTF8StrictMode())
			logger.Warn("UTF-8 strict mode enabled")
		case FeatureAutoGOMEMLIMIT:
			opts = append(opts, enableAutoGOMEMLIMIT())
			logger.Warn("Automatically set GOMEMLIMIT to match the Linux container or system memory limit.")
		case FeatureEventRecorder:
			opts = append(opts, enableEventRecorder())
			logger.Warn("Experimental event recorder enabled")
		default:
			return nil, fmt.Errorf("unknown option '%s' for --enable-feature", feature)
		}
	}

	for _, opt := range opts {
		opt(fc)
	}

	if fc.classicMode && fc.utf8StrictMode {
		return nil, errors.New("cannot have both classic and UTF-8 modes enabled")
	}

	return fc, nil
}

type NoopFlags struct{}

func (n NoopFlags) EnableAlertNamesInMetrics() bool { return false }

func (n NoopFlags) EnableReceiverNamesInMetrics() bool { return false }

func (n NoopFlags) EnableGroupKeyInMetrics() bool { return false }

func (n NoopFlags) ClassicMode() bool { return false }

func (n NoopFlags) UTF8StrictMode() bool { return false }

func (n NoopFlags) EnableAutoGOMEMLIMIT() bool { return false }

func (n NoopFlags) EnableEventRecorder() bool { return false }
